5#include "access/http2/http2protocol_p.h"
6#include "access/qhttp2connection_p.h"
10#include "http2/http2frames_p.h"
12#include <private/qnoncontiguousbytedevice_p.h>
13#include <private/qsocketabstraction_p.h>
15#include <QtNetwork/qabstractsocket.h>
17#include <QtCore/qloggingcategory.h>
18#include <QtCore/qendian.h>
19#include <QtCore/qdebug.h>
20#include <QtCore/qlist.h>
21#include <QtCore/qnumeric.h>
22#include <QtCore/qurl.h>
24#include <qhttp2configuration.h>
26#ifndef QT_NO_NETWORKPROXY
27# include <QtNetwork/qnetworkproxy.h>
30#include <qcoreapplication.h>
38using namespace Qt::StringLiterals;
43HPack::HttpHeader build_headers(
const QHttpNetworkRequest &request, quint32 maxHeaderListSize,
46 using namespace HPack;
53 const auto auth = request.url().authority(QUrl::FullyEncoded | QUrl::RemoveUserInfo).toLatin1();
54 header.emplace_back(
":authority", auth);
55 header.emplace_back(
":method", request.methodName());
56 header.emplace_back(
":path", request.uri(useProxy));
57 header.emplace_back(
":scheme", request.url().scheme().toLatin1());
59 HeaderSize size = header_size(header);
63 if (size.second > maxHeaderListSize)
66 const QHttpHeaders requestHeader = request.header();
67 using WK = QHttpHeaders::WellKnownHeader;
68 for (qsizetype i = 0; i < requestHeader.size(); ++i) {
69 const auto name = requestHeader.nameAt(i);
70 const auto value = requestHeader.valueAt(i);
71 const HeaderSize delta = entry_size(name, value);
74 if (std::numeric_limits<quint32>::max() - delta.second < size.second)
76 size.second += delta.second;
77 if (size.second > maxHeaderListSize)
80 if (name == QHttpHeaders::wellKnownHeaderName(WK::Connection)
81 || name == QHttpHeaders::wellKnownHeaderName(WK::Host)
82 || name == QHttpHeaders::wellKnownHeaderName(WK::KeepAlive)
83 || name.compare(
"proxy-connection"_L1, Qt::CaseInsensitive) == 0
84 || name == QHttpHeaders::wellKnownHeaderName(WK::TransferEncoding)) {
91 header.emplace_back(
QByteArray{name.data(), name.size()}.toLower(),
98QUrl urlkey_from_request(
const QHttpNetworkRequest &request)
102 url.setScheme(request.url().scheme());
103 url.setAuthority(request.url().authority(QUrl::FullyEncoded | QUrl::RemoveUserInfo));
104 url.setPath(QLatin1StringView(request.uri(
false)));
112using namespace Http2;
117 const auto h2Config = m_connection->http2Parameters();
120 && m_connection->connectionType() != QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
121 h2Connection = QHttp2Connection::createUpgradedConnection(channel->socket, h2Config);
124 QHttp2Stream *stream = h2Connection->getStream(1);
126 Q_ASSERT(channel->reply);
127 connectStream({ channel->request, channel->reply }, stream);
129 Q_ASSERT(QSocketAbstraction::socketState(channel->socket) == QAbstractSocket::ConnectedState);
130 h2Connection = QHttp2Connection::createDirectConnection(channel->socket, h2Config);
132 connect(h2Connection, &QHttp2Connection::receivedGOAWAY,
this,
133 &QHttp2ProtocolHandler::handleGOAWAY);
134 connect(h2Connection, &QHttp2Connection::errorOccurred,
this,
136 connect(h2Connection, &QHttp2Connection::newIncomingStream,
this,
137 [
this](QHttp2Stream *stream){
141 if (!h2Connection->isGoingAway())
144 connect(h2Connection, &QHttp2Connection::connectionClosed,
this,
150 return h2Connection && h2Connection->isGoingAway();
162 h2Connection->handleConnectionClosure();
167 QPointer<QHttp2Stream> stream = streamIDs.take(uploadData);
168 if (stream && stream->isActive())
169 stream->sendRST_STREAM(
CANCEL);
182 Q_ASSERT(h2Connection);
183 h2Connection->handleReadyRead();
193 auto &requests = m_channel->h2RequestsToSend;
194 for (
auto it = requests.begin(), endIt = requests.end(); it != endIt;) {
195 const auto &pair = *it;
196 if (pair.first.isPreConnect()) {
197 m_connection->preConnectFinished();
198 emit pair.second->finished();
199 it = requests.erase(it);
200 if (requests.empty()) {
212 if (requests.empty())
215 m_channel->state = QHttpNetworkConnectionChannel::WritingState;
219 for (
auto it = requests.begin(), end = requests.end(); it != end;) {
222 QUrl promiseKey = urlkey_from_request(httpPair.first);
223 if (h2Connection->promisedStream(promiseKey) !=
nullptr) {
225 initReplyFromPushPromise(httpPair, promiseKey);
226 it = requests.erase(it);
230 QHttp2Stream *stream = createNewStream(httpPair);
233 if (httpPair.second->isFinished()) {
234 it = requests.erase(it);
240 QHttpNetworkRequest &request = requestReplyPairs[stream].first;
241 if (!sendHEADERS(stream, request)) {
242 finishStreamWithError(stream, QNetworkReply::UnknownNetworkError,
243 "failed to send HEADERS frame(s)"_L1);
244 it = requests.erase(it);
247 if (request.uploadByteDevice()) {
248 if (!sendDATA(stream, httpPair.second)) {
249 finishStreamWithError(stream, QNetworkReply::UnknownNetworkError,
250 "failed to send DATA frame(s)"_L1);
251 it = requests.erase(it);
255 it = requests.erase(it);
258 m_channel->state = QHttpNetworkConnectionChannel::IdleState;
264
265
266
267
268
269
270
273 QHttp2Stream *stream = streamIDs.take(reply);
275 stream->sendRST_STREAM(stream->isUploadingDATA() ? Http2::CANCEL : Http2::HTTP2_NO_ERROR);
276 clearStreamState(stream);
277 stream->deleteLater();
285 using namespace HPack;
287 bool useProxy =
false;
288#ifndef QT_NO_NETWORKPROXY
289 useProxy = m_connection->d_func()->networkProxy.type() != QNetworkProxy::NoProxy;
291 if (request.withCredentials()) {
292 m_connection->d_func()->createAuthorization(m_socket, request);
293 request.d->needResendWithCredentials =
false;
295 const auto headers = build_headers(request, h2Connection->maxHeaderListSize(), useProxy);
299 bool mustUploadData = request.uploadByteDevice();
300 return stream->sendHEADERS(headers, !mustUploadData);
306 QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
307 Q_ASSERT(replyPrivate);
308 QHttpNetworkRequest &request = replyPrivate->request;
309 Q_ASSERT(request.uploadByteDevice());
311 bool startedSending = stream->sendDATA(request.uploadByteDevice(),
true);
312 return startedSending && !stream->wasReset();
317 QHttp2Stream *stream = qobject_cast<QHttp2Stream *>(sender());
319 auto &requestPair = requestReplyPairs[stream];
320 auto *httpReply = requestPair.second;
321 auto &httpRequest = requestPair.first;
325 auto *httpReplyPrivate = httpReply->d_func();
333 for (
const auto &pair : headers) {
334 const auto &name = pair.name;
335 const auto value = QByteArrayView(pair.value);
341 if (name ==
":status") {
343 if (
int status = value.toInt(&ok); ok && status >= 0 && status <= 999) {
345 httpReply->setStatusCode(statusCode);
346 m_channel->lastStatus = statusCode;
348 finishStreamWithError(stream, QNetworkReply::ProtocolInvalidOperationError,
349 "invalid :status value"_L1);
352 }
else if (name ==
"content-length") {
354 const qlonglong length = value.toLongLong(&ok);
356 httpReply->setContentLength(length);
358 const auto binder = name ==
"set-cookie" ? QByteArrayView(
"\n") : QByteArrayView(
", ");
359 httpReply->appendHeaderField(name, QByteArray(pair.value).replace(
'\0', binder));
365 if (statusCode == 100 || (102 <= statusCode && statusCode <= 199)) {
366 httpReplyPrivate->clearHttpLayerInformation();
370 if (QHttpNetworkReply::isHttpRedirect(statusCode) && httpRequest.isFollowRedirects()) {
373 if (result.errorCode != QNetworkReply::NoError) {
374 auto errorString = m_connection->d_func()->errorDetail(result.errorCode, m_socket);
375 finishStreamWithError(stream, result.errorCode, errorString);
376 stream->sendRST_STREAM(INTERNAL_ERROR);
380 if (result.redirectUrl.isValid())
381 httpReply->setRedirectUrl(result.redirectUrl);
384 if (httpReplyPrivate->isCompressed() && httpRequest.d->autoDecompress)
385 httpReplyPrivate->removeAutoDecompressHeader();
387 if (QHttpNetworkReply::isHttpRedirect(statusCode)) {
393 if (
auto *byteDevice = httpRequest.uploadByteDevice()) {
395 httpReplyPrivate->totallyUploadedData = 0;
399 QMetaObject::invokeMethod(httpReply, &QHttpNetworkReply::headerChanged, Qt::QueuedConnection);
401 finishStream(stream, Qt::QueuedConnection);
406 QHttp2Stream *stream = qobject_cast<QHttp2Stream *>(sender());
407 auto &httpPair = requestReplyPairs[stream];
408 auto *httpReply = httpPair.second;
411 Q_ASSERT(!stream->isPromisedStream());
413 if (!data.isEmpty() && !httpPair.first.d->needResendWithCredentials) {
414 auto *replyPrivate = httpReply->d_func();
416 replyPrivate->totalProgress += data.size();
418 replyPrivate->responseData.append(data);
420 if (replyPrivate->shouldEmitSignals()) {
421 QMetaObject::invokeMethod(httpReply, &QHttpNetworkReply::readyRead,
422 Qt::QueuedConnection);
423 QMetaObject::invokeMethod(httpReply, &QHttpNetworkReply::dataReadProgress,
424 Qt::QueuedConnection, replyPrivate->totalProgress,
425 replyPrivate->bodyLength);
428 stream->clearDownloadBuffer();
430 finishStream(stream, Qt::QueuedConnection);
438 auto &requestPair = requestReplyPairs[stream];
439 auto *httpReply = requestPair.second;
440 auto *httpReplyPrivate = httpReply->d_func();
441 auto &httpRequest = requestPair.first;
443 Q_ASSERT(httpReply && (httpReply->statusCode() == 401 || httpReply->statusCode() == 407));
445 const auto handleAuth = [&,
this](QByteArrayView authField,
bool isProxy) ->
bool {
447 const QByteArrayView auth = authField.trimmed();
448 if (auth.startsWith(
"Negotiate") || auth.startsWith(
"NTLM")) {
452 emit httpReply->headerChanged();
453 emit httpReply->readyRead();
454 const QNetworkReply::NetworkError error = isProxy
455 ? QNetworkReply::ProxyAuthenticationRequiredError
456 : QNetworkReply::AuthenticationRequiredError;
457 finishStreamWithError(stream, error,
458 m_connection->d_func()->errorDetail(error, m_socket));
463 const bool authenticateHandled = m_connection->d_func()->handleAuthenticateChallenge(
464 m_socket, httpReply, isProxy, resend);
465 if (authenticateHandled) {
467 httpReply->d_func()->eraseData();
470 httpRequest.d->needResendWithCredentials =
true;
471 m_channel->h2RequestsToSend.insert(httpRequest.priority(), requestPair);
472 httpReply->d_func()->clearHeaders();
474 if (
auto *byteDevice = httpRequest.uploadByteDevice()) {
476 httpReplyPrivate->totallyUploadedData = 0;
490 emit httpReply->headerChanged();
491 emit httpReply->readyRead();
492 QNetworkReply::NetworkError error = httpReply->statusCode() == 401
493 ? QNetworkReply::AuthenticationRequiredError
494 : QNetworkReply::ProxyAuthenticationRequiredError;
495 finishStreamWithError(stream, QNetworkReply::AuthenticationRequiredError,
496 m_connection->d_func()->errorDetail(error, m_socket));
506 switch (httpReply->statusCode()) {
508 authOk = handleAuth(httpReply->headerField(
"www-authenticate"),
false);
511 authOk = handleAuth(httpReply->headerField(
"proxy-authenticate"),
true);
517 stream->sendRST_STREAM(CANCEL);
518 clearStreamState(stream);
519 stream->deleteLater();
526 if (stream->state() != QHttp2Stream::State::Closed)
527 stream->sendRST_STREAM(CANCEL);
529 auto &pair = requestReplyPairs[stream];
530 auto *httpReply = pair.second;
532 int statusCode = httpReply->statusCode();
533 if (statusCode == 401 || statusCode == 407) {
537 handleAuthorization(stream);
541 httpReply->disconnect(
this);
543 if (!pair.first.d->needResendWithCredentials) {
544 if (connectionType == Qt::DirectConnection)
545 emit httpReply->finished();
547 QMetaObject::invokeMethod(httpReply, &QHttpNetworkReply::finished, connectionType);
551 clearStreamState(stream);
552 qCDebug(QT_HTTP2) <<
"stream" << stream->streamID() <<
"closed";
558 if (!httpReply || !tryRemoveReply(httpReply)) {
559 requestReplyPairs.remove(stream);
560 stream->deleteLater();
566 qCDebug(QT_HTTP2) <<
"GOAWAY received, error code:" << errorCode <<
"last stream ID:"
576 m_channel->emitFinishedWithError(QNetworkReply::ProtocolUnknownError,
577 "GOAWAY received, cannot start a request");
578 m_channel->h2RequestsToSend.clear();
587 QNetworkReply::NetworkError error = QNetworkReply::NoError;
589 qt_error(errorCode, error, message);
590 finishStreamWithError(stream, error, message);
594 QNetworkReply::NetworkError error,
const QString &message)
596 stream->sendRST_STREAM(CANCEL);
597 const HttpMessagePair &pair = requestReplyPairs.value(stream);
598 if (
auto *httpReply = pair.second) {
599 httpReply->disconnect(
this);
602 httpReply->d_func()->setError(error, message);
603 emit httpReply->finishedWithError(error, message);
606 clearStreamState(stream);
607 stream->deleteLater();
608 qCWarning(QT_HTTP2) <<
"stream" << stream->streamID() <<
"finished with error:" << message;
612
613
614
615
616
620 QUrl streamKey = urlkey_from_request(message.first);
621 if (
auto promisedStream = h2Connection->promisedStream(streamKey)) {
622 Q_ASSERT(promisedStream->state() != QHttp2Stream::State::Closed);
623 return promisedStream;
626 QH2Expected<QHttp2Stream *, QHttp2Connection::CreateStreamError>
627 streamResult = h2Connection->createStream();
628 if (!streamResult.ok()) {
629 if (streamResult.error()
630 == QHttp2Connection::CreateStreamError::MaxConcurrentStreamsReached) {
635 qCDebug(QT_HTTP2) <<
"failed to create new stream:" << streamResult.error();
636 auto *reply = message.second;
637 const char *cstr =
"Failed to initialize HTTP/2 stream with errorcode: %1";
638 const QString errorString = QCoreApplication::translate(
"QHttp", cstr)
639 .arg(QDebug::toString(streamResult.error()));
640 reply->d_func()->setError(QNetworkReply::ProtocolFailure, errorString);
641 emit reply->finishedWithError(QNetworkReply::ProtocolFailure, errorString);
644 QHttp2Stream *stream = streamResult.unwrap();
647 if (
auto *src = message.first.uploadByteDevice()) {
648 connect(src, &QObject::destroyed,
this, &QHttp2ProtocolHandler::_q_uploadDataDestroyed);
649 streamIDs.insert(src, stream);
653 auto *reply = message.second;
654 QMetaObject::invokeMethod(reply, &QHttpNetworkReply::requestSent, Qt::QueuedConnection);
656 connectStream(message, stream);
662 auto *reply = message.second;
663 auto *replyPrivate = reply->d_func();
664 replyPrivate->connection = m_connection;
665 replyPrivate->connectionChannel = m_channel;
667 reply->setHttp2WasUsed(
true);
668 QPointer<QHttp2Stream> &oldStream = streamIDs[reply];
670 disconnect(oldStream,
nullptr,
this,
nullptr);
671 clearStreamState(oldStream);
674 requestReplyPairs.emplace(stream, message);
676 QObject::connect(stream, &QHttp2Stream::headersReceived,
this,
677 &QHttp2ProtocolHandler::handleHeadersReceived);
678 QObject::connect(stream, &QHttp2Stream::dataReceived,
this,
679 &QHttp2ProtocolHandler::handleDataReceived);
680 QObject::connect(stream, &QHttp2Stream::errorOccurred,
this,
681 [
this, stream](Http2Error errorCode,
const QString &errorString) {
683 <<
"stream" << stream->streamID() <<
"error:" << errorString;
687 if (
const auto lastId = h2Connection->lastGoAwayStreamID();
688 errorCode == HTTP2_NO_ERROR && lastId
689 && stream->streamID() > *lastId) {
690 finishStreamWithError(
691 stream, QNetworkReply::ContentReSendError,
692 QCoreApplication::translate(
694 "Server stopped accepting new streams before this "
695 "stream was established"));
697 finishStreamWithError(stream, errorCode);
701 QObject::connect(stream, &QHttp2Stream::stateChanged,
this, [
this](QHttp2Stream::State state) {
702 if (state == QHttp2Stream::State::Closed) {
704 if (!m_channel->h2RequestsToSend.empty()) {
705 QMetaObject::invokeMethod(
this, &QHttp2ProtocolHandler::sendRequest,
706 Qt::QueuedConnection);
714 auto it = requestReplyPairs.find(stream);
715 if (it == requestReplyPairs.end())
718 if (
auto *reply = it->second)
719 streamIDs.remove(reply);
720 if (
auto *uploadDevice = it->first.uploadByteDevice())
721 streamIDs.remove(uploadDevice);
723 requestReplyPairs.erase(it);
727 const QUrl &cacheKey)
729 QHttp2Stream *promise = h2Connection->promisedStream(cacheKey);
731 Q_ASSERT(message.second);
732 message.second->setHttp2WasUsed(
true);
734 qCDebug(QT_HTTP2) <<
"found cached/promised response on stream" << promise->streamID();
736 const bool replyFinished = promise->state() == QHttp2Stream::State::Closed;
738 connectStream(message, promise);
743 QByteDataBuffer downloadBuffer = promise->takeDownloadBuffer();
744 if (
const auto &headers = promise->receivedHeaders(); !headers.empty())
745 emit promise->headersReceived(headers, replyFinished && downloadBuffer.isEmpty());
747 if (!downloadBuffer.isEmpty()) {
748 for (qsizetype i = 0; i < downloadBuffer.bufferCount(); ++i) {
749 const bool streamEnded = replyFinished && i == downloadBuffer.bufferCount() - 1;
750 emit promise->dataReceived(downloadBuffer[i], streamEnded);
757 Q_ASSERT(!message.isNull());
759 qCCritical(QT_HTTP2) <<
"connection error:" << message;
761 const auto error = qt_error(errorCode);
762 m_channel->emitFinishedWithError(error, message);
763 m_channel->h2RequestsToSend.clear();
775#include "moc_qhttp2protocolhandler_p.cpp"
bool isGoingAway() const noexcept
QHttp2ProtocolHandler(QHttpNetworkConnectionChannel *channel)
Q_INVOKABLE void handleConnectionClosure()
Q_INVOKABLE void _q_receiveReply() override
Q_INVOKABLE bool sendRequest() override
void _q_readyRead() override
bool tryRemoveReply(QHttpNetworkReply *reply) override
static ParseRedirectResult parseRedirectResponse(QHttpNetworkReply *reply)
Combined button and popup list for selecting options.
std::pair< QHttpNetworkRequest, QHttpNetworkReply * > HttpMessagePair