QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
NTRIPHttpCodec.cc
Go to the documentation of this file.
1#include "NTRIPHttpCodec.h"
2
3#include <algorithm>
4#include <utility>
5
6#include <QtCore/QCoreApplication>
7#include <QtCore/QRegularExpression>
8#include <QtCore/QUrl>
9
10#include "NTRIPConfiguration.h"
11#include "QGCNetworkClient.h"
12
13namespace {
14bool isToken(char ch)
15{
16 return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') ||
17 QByteArrayView("!#$%&'*+-.^_`|~").contains(ch);
18}
19
20bool isFieldValue(char ch)
21{
22 const auto byte = static_cast<unsigned char>(ch);
23 return ch == '\t' || (byte >= 32 && byte != 127);
24}
25
27std::optional<quint64> unsignedNumber(QByteArrayView text, int base = 10)
28{
29 const auto digit = [base](char ch) {
30 return (ch >= '0' && ch <= '9') || (base == 16 && ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')));
31 };
32 bool ok = false;
33 const quint64 value = text.toULongLong(&ok, base);
34 return ok && std::all_of(text.begin(), text.end(), digit) ? std::optional(value) : std::nullopt;
35}
36
37std::chrono::milliseconds retryAfter(const QHttpHeaders& headers, const QDateTime& utcNow)
38{
39 const QByteArrayView value = headers.value(QHttpHeaders::WellKnownHeader::RetryAfter);
40 if (const auto seconds = unsignedNumber(value)) {
41 const auto maxSeconds = std::chrono::duration_cast<std::chrono::seconds>(NTRIPFailure::MAX_RETRY_AFTER).count();
42 return std::chrono::seconds{(std::min<quint64>) (*seconds, maxSeconds)};
43 }
44 auto deadline = headers.dateTimeValue(QHttpHeaders::WellKnownHeader::RetryAfter);
45 if (!deadline || !utcNow.isValid()) {
46 return {};
47 }
48 // Qt reads the two-digit RFC 850 year as 19yy; RFC 9110 wants the latest century not over 50 years ahead.
49 if (value.indexOf(',') > 3) {
50 *deadline = deadline->addYears(utcNow.date().year() / 100 * 100 - 1900);
51 if (*deadline > utcNow.addYears(50)) {
52 *deadline = deadline->addYears(-100);
53 }
54 }
55 const qint64 maxMs = NTRIPFailure::MAX_RETRY_AFTER.count();
56 return std::chrono::milliseconds{std::clamp(utcNow.msecsTo(*deadline), qint64(0), maxMs)};
57}
58} // namespace
59
61{
62 NTRIPHttpRequest result;
63 result.error = purpose == NTRIPHttpPurpose::Corrections ? config.streamValidationError() : config.validationError();
64 if (!result.error.isEmpty()) {
65 return result;
66 }
67
68 const QUrl url = config.url(purpose == NTRIPHttpPurpose::Corrections);
69 if (!url.isValid() || url.host().isEmpty()) {
70 result.error = QCoreApplication::translate("NTRIPHttpTransport", "Invalid NTRIP endpoint");
71 return result;
72 }
73
74 // Some legacy casters match these header spellings case-sensitively. The fully encoded URL parts and the
75 // Base64 credentials are always valid field values.
76 result.bytes = "GET " + url.path(QUrl::FullyEncoded).toLatin1() + " HTTP/1.1\r\n" +
77 "Host: " + url.authority(QUrl::FullyEncoded).toLatin1() + "\r\n" +
78 "Ntrip-Version: Ntrip/2.0\r\nUser-Agent: NTRIP " + QGCNetworkHelper::defaultUserAgent().toLatin1() +
79 "\r\n";
80 if (!config.username.isEmpty() || !config.password.isEmpty()) {
81 result.bytes += "Authorization: Basic " +
83 "\r\n";
84 }
85 result.bytes += "\r\n";
86 return result;
87}
88
90{
91 *this = NTRIPHttpDecoder{_purpose};
92}
93
95{
96 static const QRegularExpression pattern(
97 QStringLiteral("^(HTTP/1\\.[01]|(?i:ICY|SOURCETABLE)) ([1-5][0-9]{2})(?: ([\\t\\x20-\\x7e\\x80-\\xff]*))?\\z"));
98 const auto match = pattern.match(QString::fromLatin1(line));
99 return match.hasMatch() ? Status{match.captured(2).toInt(), match.captured(3), true} : Status{};
100}
101
102void NTRIPHttpDecoder::_fail(Result& result, const QString& detail, NTRIPError code)
103{
104 if (_pendingFailure) {
105 _finishError(result);
106 return;
107 }
108 _state = State::Failed;
109 _line.clear();
110 result.complete = false;
111 result.failure = NTRIPFailure{code, detail};
112}
113
114void NTRIPHttpDecoder::_finishError(Result& result)
115{
116 static const QRegularExpression htmlTags(QStringLiteral("<[^>]*(?:>|$)"));
117 static const QRegularExpression controls(QStringLiteral("[\\x00-\\x08\\x0e-\\x1f\\x7f]"));
118 QString preview = QString::fromUtf8(_errorBody);
119 preview.remove(htmlTags);
120 preview.remove(controls);
121 preview = preview.simplified().left(MAX_ERROR_PREVIEW_CHARS);
122 result.failure = std::exchange(_pendingFailure, std::nullopt);
123 if (!preview.isEmpty()) {
124 result.failure->detail += QStringLiteral(" \u2014 ") + preview;
125 }
126 _state = State::Failed;
127 _line.clear();
128 _errorBody.clear();
129 result.body.clear();
130 result.connected = false;
131 result.complete = false;
132}
133
134void NTRIPHttpDecoder::_beginIcyBody(Result& result)
135{
136 _beginBody(result);
137 result.body += std::exchange(_line, {});
138}
139
140NTRIPHttpDecoder::Result NTRIPHttpDecoder::feed(QByteArrayView bytes, const QDateTime& utcNow)
141{
142 Result result;
143 while (!bytes.isEmpty() && _state != State::Failed) {
144 if (_state == State::Complete) {
145 _fail(result, tr("Unexpected data after HTTP response"));
146 break;
147 }
148 if (_state == State::IcyHeaders) {
149 const auto first = static_cast<unsigned char>(bytes.front());
150 const bool binary = first >= 127 || (first < 32 && first != '\t' && first != '\r' && first != '\n');
151 // A legacy stream may start mid-frame, not at the RTCM preamble.
152 // Probe optional ASCII headers only until binary or non-header input arrives.
153 if (_headers.isEmpty() &&
154 (binary || (first == '\n' && !_line.endsWith('\r')) || (_line.endsWith('\r') && first != '\n'))) {
155 _beginIcyBody(result);
156 } else if (!_headers.isEmpty() && _line.isEmpty() && binary) {
157 // ICY casters may omit the blank separator even after optional headers.
158 _lineReceived(result, utcNow);
159 continue;
160 }
161 }
162 if (_state == State::Identity || _state == State::ChunkData) {
163 const bool bounded = _state == State::ChunkData || _contentLength.has_value();
164 const auto count =
165 bounded ? static_cast<qsizetype>((std::min<quint64>) (bytes.size(), _remaining)) : bytes.size();
166 if (_pendingFailure) {
167 _errorBody.append(bytes.data(), (std::min) (count, MAX_ERROR_BODY_BYTES - _errorBody.size()));
168 } else {
169 result.body.append(bytes.data(), count);
170 }
171 bytes = bytes.sliced(count);
172 if (bounded && (_remaining -= count) == 0) {
173 _state = _state == State::ChunkData ? State::ChunkEnd : State::Complete;
174 result.complete = _state == State::Complete;
175 }
176 if (_pendingFailure && (_state == State::Complete || _errorBody.size() == MAX_ERROR_BODY_BYTES)) {
177 _finishError(result);
178 }
179 continue;
180 }
181 if (_state == State::ChunkEnd) {
182 if (bytes.front() != (_chunkEndBytes == 0 ? '\r' : '\n')) {
183 _fail(result, tr("Invalid HTTP chunk terminator"));
184 break;
185 }
186 bytes = bytes.sliced(1);
187 if (++_chunkEndBytes == 2) {
188 _chunkEndBytes = 0;
189 _state = State::ChunkSize;
190 }
191 continue;
192 }
193 const char ch = bytes.front();
194 bytes = bytes.sliced(1);
195 if ((ch == '\n' && !_line.endsWith('\r')) || (_line.endsWith('\r') && ch != '\n')) {
196 _fail(result, tr("Invalid HTTP line ending"));
197 break;
198 }
199 _line.append(ch);
200 if ((_state != State::ChunkSize && ++_headerBytes > MAX_HEADER_BYTES) || _line.size() > MAX_LINE_BYTES) {
201 _fail(result, tr("HTTP response header too large"), NTRIPError::HeaderTooLarge);
202 break;
203 }
204 if (ch == '\n') {
205 _line.chop(2);
206 _lineReceived(result, utcNow);
207 _line.clear();
208 }
209 }
210 return result;
211}
212
213void NTRIPHttpDecoder::_lineReceived(Result& result, const QDateTime& utcNow)
214{
215 if (_state == State::Status) {
216 _status = parseStatusLine(_line);
217 if (!_status.valid) {
218 _fail(result, tr("Invalid HTTP status line"));
219 } else if (_line.left(11).compare("SOURCETABLE", Qt::CaseInsensitive) == 0) {
220 if (_purpose == NTRIPHttpPurpose::SourceTable && _status.code == 200) {
221 _state = State::IcyHeaders;
222 result.connected = true;
223 } else {
224 _fail(result, tr("Caster returned a source table; select a valid mountpoint"),
225 NTRIPError::InvalidMountpoint);
226 }
227 } else if (_line.first(3).compare("ICY", Qt::CaseInsensitive) == 0 && _status.code == 200) {
228 _state = State::IcyHeaders;
229 result.connected = true;
230 } else {
231 _http10 = _line.startsWith("HTTP/1.0");
232 _state = State::Headers;
233 }
234 return;
235 }
236 if (_state == State::ChunkSize) {
237 // NTRIP uses no chunk extensions, so everything after ';' (and the whitespace before it) is ignored.
238 QByteArrayView size(_line);
239 if (const qsizetype separator = size.indexOf(';'); separator >= 0) {
240 size = size.first(separator);
241 while (size.endsWith(' ') || size.endsWith('\t')) {
242 size.chop(1);
243 }
244 }
245 const auto length = unsignedNumber(size, 16);
246 if (!length || *length > MAX_CHUNK_BYTES) {
247 _fail(result, tr("Invalid or oversized HTTP chunk"));
248 } else {
249 _remaining = *length;
250 _state = _remaining == 0 ? State::Trailers : State::ChunkData;
251 }
252 return;
253 }
254 if (_line.isEmpty()) {
255 if (_state == State::Trailers) {
256 if (_pendingFailure) {
257 _finishError(result);
258 } else {
259 _state = State::Complete;
260 result.complete = true;
261 }
262 return;
263 }
264 if (_status.code >= 300) {
265 const int status = _status.code;
266 const auto code = status == 401 ? NTRIPError::AuthFailed
267 : status == 400 || status == 403 ? NTRIPError::RequestRejected
268 : NTRIPError::HttpError;
269 const QString detail = status == 401 ? tr("Authentication failed (401): check username and password")
270 : tr("HTTP %1: %2").arg(status).arg(_status.reason);
271 _pendingFailure = NTRIPFailure{code, detail};
272 if (_headers.values(QHttpHeaders::WellKnownHeader::RetryAfter).size() == 1) {
273 _pendingFailure->retryAfter = retryAfter(_headers, utcNow);
274 }
275 if (code == NTRIPError::AuthFailed) {
276 _finishError(result);
277 return;
278 }
279 }
280 const auto lengths = _headers.values(QHttpHeaders::WellKnownHeader::ContentLength);
281 for (const auto& field : lengths) {
282 for (const auto& value : field.split(',')) {
283 const auto length = unsignedNumber(QByteArrayView(value).trimmed());
284 if (!length || (_contentLength && *_contentLength != *length)) {
285 _fail(result, tr("Invalid or conflicting HTTP content length"));
286 return;
287 }
288 _contentLength = *length;
289 }
290 }
291 const auto transfers = _headers.values(QHttpHeaders::WellKnownHeader::TransferEncoding);
292 _chunked = !transfers.isEmpty();
293 if (_chunked && (_http10 || transfers.size() != 1 ||
294 transfers.first().compare("chunked", Qt::CaseInsensitive) != 0 || _contentLength)) {
295 _fail(result, tr("Unsupported or conflicting HTTP transfer encoding"));
296 return;
297 }
298 if (_status.code >= 100 && _status.code < 200) {
299 if (_status.code == 101 || _contentLength || _chunked || ++_informationalResponses > 4) {
300 _fail(result, tr("Unsupported HTTP informational response"));
301 } else {
302 _headers.clear();
303 _state = State::Status;
304 }
305 return;
306 }
307 const auto encodings = _headers.values(QHttpHeaders::WellKnownHeader::ContentEncoding);
308 if (!encodings.isEmpty() &&
309 (encodings.size() != 1 || encodings.first().compare("identity", Qt::CaseInsensitive) != 0)) {
310 _fail(result, tr("Unsupported HTTP content encoding"));
311 return;
312 }
313 if (_pendingFailure) {
314 _beginBody(result);
315 return;
316 }
317 for (const auto& value : _headers.values(QHttpHeaders::WellKnownHeader::ContentType)) {
318 if (_purpose == NTRIPHttpPurpose::Corrections &&
319 value.split(';').first().trimmed().compare("gnss/sourcetable", Qt::CaseInsensitive) == 0) {
320 _fail(result, tr("Caster returned a source table; select a valid mountpoint"),
321 NTRIPError::InvalidMountpoint);
322 return;
323 }
324 }
325 if (_status.code == 204 || _status.code == 205) {
326 if (_chunked || (_contentLength && *_contentLength != 0)) {
327 _fail(result, tr("Unexpected framing for an empty HTTP response"));
328 return;
329 }
330 _contentLength = 0;
331 }
332 result.connected = result.connected || _state != State::IcyHeaders;
333 _beginBody(result);
334 return;
335 }
336
337 const qsizetype colon = _line.indexOf(':');
338 const QByteArrayView line(_line);
339 if (colon <= 0 || !std::all_of(line.begin(), line.begin() + colon, isToken) ||
340 !std::all_of(line.begin() + colon + 1, line.end(), isFieldValue)) {
341 if (_state == State::IcyHeaders && _headers.isEmpty()) {
342 _line += "\r\n";
343 _beginIcyBody(result);
344 return;
345 }
346 _fail(result, tr("Invalid HTTP response header"));
347 return;
348 }
349 if (_headers.size() >= 128) {
350 _fail(result, tr("Too many HTTP response headers"), NTRIPError::HeaderTooLarge);
351 return;
352 }
353 const auto name = line.first(colon);
354 const auto value = line.sliced(colon + 1);
355 if (_state == State::Trailers &&
356 (name.compare("content-length", Qt::CaseInsensitive) == 0 ||
357 name.compare("transfer-encoding", Qt::CaseInsensitive) == 0 ||
358 name.compare("content-encoding", Qt::CaseInsensitive) == 0 ||
359 name.compare("content-type", Qt::CaseInsensitive) == 0 ||
360 name.compare("retry-after", Qt::CaseInsensitive) == 0 || name.compare("host", Qt::CaseInsensitive) == 0)) {
361 _fail(result, tr("Forbidden HTTP trailer"));
362 return;
363 }
364 // Validated above, so append() cannot reject the field.
365 (void) _headers.append(QLatin1StringView(name.data(), name.size()), QLatin1StringView(value.data(), value.size()));
366}
367
368void NTRIPHttpDecoder::_beginBody(Result& result)
369{
370 _remaining = _contentLength.value_or(0);
371 _state = _chunked ? State::ChunkSize : State::Identity;
372 if (!_chunked && _contentLength && _remaining == 0) {
373 if (_pendingFailure) {
374 _finishError(result);
375 } else {
376 _state = State::Complete;
377 result.complete = true;
378 }
379 }
380}
381
383{
384 Result result;
385 if (_pendingFailure) {
386 _finishError(result);
387 } else if ((_state == State::Identity && !_contentLength) ||
388 (_state == State::IcyHeaders && _line.isEmpty() && _headers.isEmpty()) || _state == State::Complete) {
389 _state = State::Complete;
390 result.complete = true;
391 } else if (_state == State::Identity || _state == State::ChunkSize || _state == State::ChunkData ||
392 _state == State::ChunkEnd || _state == State::Trailers) {
393 _fail(result, tr("Caster closed the connection mid-transfer"));
394 } else if (_state != State::Failed) {
395 _fail(result, tr("Caster disconnected before completing the HTTP response"));
396 }
397 return result;
398}
NTRIPErrors::NTRIPError NTRIPError
Definition NTRIPError.h:32
NTRIPHttpPurpose
static constexpr quint64 MAX_CHUNK_BYTES
static constexpr qsizetype MAX_ERROR_PREVIEW_CHARS
Result feed(QByteArrayView bytes, const QDateTime &utcNow)
static constexpr qsizetype MAX_ERROR_BODY_BYTES
static constexpr qsizetype MAX_LINE_BYTES
static constexpr qsizetype MAX_HEADER_BYTES
static Status parseStatusLine(QByteArrayView line)
NTRIPHttpDecoder(NTRIPHttpPurpose purpose=NTRIPHttpPurpose::Corrections)
QByteArray line(std::string_view command)
command as one CR/LF-terminated line.
QString defaultUserAgent()
"<application>/<version> (Qt <version>)".
QString createBasicAuthCredentials(const QString &username, const QString &password)
Base64-encoded UTF-8 username:password, without the authentication scheme.
GPSCommandSequence base(QByteArrayView port, const GPSBaseStationConfig &base)
Streams RTCM3 corrections and the PVTGeodetic survey status over port in the mode base selects.
Definition SBFPlan.cc:49
QString streamValidationError() const
QUrl url(bool withMountpoint=true) const
The caster's HTTP(S) URL, with the mountpoint as its path when withMountpoint is set,...
QString validationError() const
static constexpr std::chrono::milliseconds MAX_RETRY_AFTER
Longest caster Retry-After hint that may delay a reconnect.
Definition NTRIPError.h:37
QByteArray body
Retains valid prefixes when subsequent framing fails.
static NTRIPHttpRequest build(const NTRIPConnectionConfig &config, NTRIPHttpPurpose purpose=NTRIPHttpPurpose::Corrections)