6#include <QtCore/QCoreApplication>
7#include <QtCore/QRegularExpression>
16 return (ch >=
'a' && ch <=
'z') || (ch >=
'A' && ch <=
'Z') || (ch >=
'0' && ch <=
'9') ||
17 QByteArrayView(
"!#$%&'*+-.^_`|~").contains(ch);
20bool isFieldValue(
char ch)
22 const auto byte =
static_cast<unsigned char>(ch);
23 return ch ==
'\t' || (
byte >= 32 &&
byte != 127);
27std::optional<quint64> unsignedNumber(QByteArrayView text,
int base = 10)
29 const auto digit = [
base](
char ch) {
30 return (ch >=
'0' && ch <=
'9') || (
base == 16 && ((ch >=
'a' && ch <=
'f') || (ch >=
'A' && ch <=
'F')));
33 const quint64 value = text.toULongLong(&ok, base);
34 return ok && std::all_of(text.begin(), text.end(), digit) ? std::optional(value) : std::nullopt;
37std::chrono::milliseconds retryAfter(
const QHttpHeaders& headers,
const QDateTime& utcNow)
39 const QByteArrayView value = headers.value(QHttpHeaders::WellKnownHeader::RetryAfter);
40 if (
const auto seconds = unsignedNumber(value)) {
42 return std::chrono::seconds{(std::min<quint64>) (*seconds, maxSeconds)};
44 auto deadline = headers.dateTimeValue(QHttpHeaders::WellKnownHeader::RetryAfter);
45 if (!deadline || !utcNow.isValid()) {
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);
56 return std::chrono::milliseconds{std::clamp(utcNow.msecsTo(*deadline), qint64(0), maxMs)};
64 if (!result.
error.isEmpty()) {
69 if (!url.isValid() || url.host().isEmpty()) {
70 result.
error = QCoreApplication::translate(
"NTRIPHttpTransport",
"Invalid NTRIP endpoint");
76 result.
bytes =
"GET " + url.path(QUrl::FullyEncoded).toLatin1() +
" HTTP/1.1\r\n" +
77 "Host: " + url.authority(QUrl::FullyEncoded).toLatin1() +
"\r\n" +
81 result.
bytes +=
"Authorization: Basic " +
85 result.
bytes +=
"\r\n";
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{};
102void NTRIPHttpDecoder::_fail(Result& result,
const QString& detail,
NTRIPError code)
104 if (_pendingFailure) {
105 _finishError(result);
108 _state = State::Failed;
110 result.complete =
false;
111 result.failure = NTRIPFailure{code, detail};
114void NTRIPHttpDecoder::_finishError(Result& result)
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);
122 result.failure = std::exchange(_pendingFailure, std::nullopt);
123 if (!preview.isEmpty()) {
124 result.failure->detail += QStringLiteral(
" \u2014 ") + preview;
126 _state = State::Failed;
130 result.connected =
false;
131 result.complete =
false;
134void NTRIPHttpDecoder::_beginIcyBody(Result& result)
137 result.body += std::exchange(_line, {});
143 while (!bytes.isEmpty() && _state != State::Failed) {
144 if (_state == State::Complete) {
145 _fail(result, tr(
"Unexpected data after HTTP response"));
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');
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) {
158 _lineReceived(result, utcNow);
162 if (_state == State::Identity || _state == State::ChunkData) {
163 const bool bounded = _state == State::ChunkData || _contentLength.has_value();
165 bounded ?
static_cast<qsizetype
>((std::min<quint64>) (bytes.size(), _remaining)) : bytes.size();
166 if (_pendingFailure) {
169 result.
body.append(bytes.data(), count);
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;
176 if (_pendingFailure && (_state == State::Complete || _errorBody.size() ==
MAX_ERROR_BODY_BYTES)) {
177 _finishError(result);
181 if (_state == State::ChunkEnd) {
182 if (bytes.front() != (_chunkEndBytes == 0 ?
'\r' :
'\n')) {
183 _fail(result, tr(
"Invalid HTTP chunk terminator"));
186 bytes = bytes.sliced(1);
187 if (++_chunkEndBytes == 2) {
189 _state = State::ChunkSize;
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"));
201 _fail(result, tr(
"HTTP response header too large"), NTRIPError::HeaderTooLarge);
206 _lineReceived(result, utcNow);
213void NTRIPHttpDecoder::_lineReceived(Result& result,
const QDateTime& utcNow)
215 if (_state == State::Status) {
217 if (!_status.
valid) {
218 _fail(result, tr(
"Invalid HTTP status line"));
219 }
else if (_line.left(11).compare(
"SOURCETABLE", Qt::CaseInsensitive) == 0) {
221 _state = State::IcyHeaders;
222 result.connected =
true;
224 _fail(result, tr(
"Caster returned a source table; select a valid mountpoint"),
225 NTRIPError::InvalidMountpoint);
227 }
else if (_line.first(3).compare(
"ICY", Qt::CaseInsensitive) == 0 && _status.code == 200) {
228 _state = State::IcyHeaders;
229 result.connected =
true;
231 _http10 = _line.startsWith(
"HTTP/1.0");
232 _state = State::Headers;
236 if (_state == State::ChunkSize) {
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')) {
245 const auto length = unsignedNumber(size, 16);
247 _fail(result, tr(
"Invalid or oversized HTTP chunk"));
249 _remaining = *length;
250 _state = _remaining == 0 ? State::Trailers : State::ChunkData;
254 if (_line.isEmpty()) {
255 if (_state == State::Trailers) {
256 if (_pendingFailure) {
257 _finishError(result);
259 _state = State::Complete;
260 result.complete =
true;
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);
275 if (code == NTRIPError::AuthFailed) {
276 _finishError(result);
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"));
288 _contentLength = *length;
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"));
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"));
303 _state = State::Status;
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"));
313 if (_pendingFailure) {
317 for (
const auto& value : _headers.values(QHttpHeaders::WellKnownHeader::ContentType)) {
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);
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"));
332 result.connected = result.connected || _state != State::IcyHeaders;
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()) {
343 _beginIcyBody(result);
346 _fail(result, tr(
"Invalid HTTP response header"));
349 if (_headers.size() >= 128) {
350 _fail(result, tr(
"Too many HTTP response headers"), NTRIPError::HeaderTooLarge);
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"));
365 (void) _headers.append(QLatin1StringView(name.data(), name.size()), QLatin1StringView(value.data(), value.size()));
368void NTRIPHttpDecoder::_beginBody(Result& result)
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);
376 _state = State::Complete;
377 result.complete =
true;
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;
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"));
NTRIPErrors::NTRIPError NTRIPError
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.
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.
QByteArray body
Retains valid prefixes when subsequent framing fails.
static NTRIPHttpRequest build(const NTRIPConnectionConfig &config, NTRIPHttpPurpose purpose=NTRIPHttpPurpose::Corrections)