Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qhttp2protocolhandler.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:network-protocol
4
5#include "access/http2/http2protocol_p.h"
6#include "access/qhttp2connection_p.h"
9
10#include "http2/http2frames_p.h"
11
12#include <private/qnoncontiguousbytedevice_p.h>
13#include <private/qsocketabstraction_p.h>
14
15#include <QtNetwork/qabstractsocket.h>
16
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>
23
24#include <qhttp2configuration.h>
25
26#ifndef QT_NO_NETWORKPROXY
27# include <QtNetwork/qnetworkproxy.h>
28#endif
29
30#include <qcoreapplication.h>
31
32#include <algorithm>
33#include <vector>
34#include <optional>
35
37
38using namespace Qt::StringLiterals;
39
40namespace
41{
42
43HPack::HttpHeader build_headers(const QHttpNetworkRequest &request, quint32 maxHeaderListSize,
44 bool useProxy)
45{
46 using namespace HPack;
47
48 HttpHeader header;
49 header.reserve(300);
50
51 // 1. Before anything - mandatory fields, if they do not fit into maxHeaderList -
52 // then stop immediately with error.
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());
58
59 HeaderSize size = header_size(header);
60 if (!size.first) // Ooops!
61 return HttpHeader();
62
63 if (size.second > maxHeaderListSize)
64 return HttpHeader(); // Bad, we cannot send this request ...
65
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);
72 if (!delta.first) // Overflow???
73 break;
74 if (std::numeric_limits<quint32>::max() - delta.second < size.second)
75 break;
76 size.second += delta.second;
77 if (size.second > maxHeaderListSize)
78 break;
79
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)) {
85 continue; // Those headers are not valid (section 3.2.1) - from QSpdyProtocolHandler
86 }
87 // TODO: verify with specs, which fields are valid to send ....
88 //
89 // Note: RFC 7450 8.1.2 (HTTP/2) states that header field names must be lower-cased
90 // prior to their encoding in HTTP/2
91 header.emplace_back(QByteArray{name.data(), name.size()}.toLower(),
92 QByteArray{value.data(), value.size()});
93 }
94
95 return header;
96}
97
98QUrl urlkey_from_request(const QHttpNetworkRequest &request)
99{
100 QUrl url;
101
102 url.setScheme(request.url().scheme());
103 url.setAuthority(request.url().authority(QUrl::FullyEncoded | QUrl::RemoveUserInfo));
104 url.setPath(QLatin1StringView(request.uri(false)));
105
106 return url;
107}
108
109} // Unnamed namespace
110
111// Since we anyway end up having this in every function definition:
112using namespace Http2;
113
114QHttp2ProtocolHandler::QHttp2ProtocolHandler(QHttpNetworkConnectionChannel *channel)
116{
117 const auto h2Config = m_connection->http2Parameters();
118
119 if (!channel->ssl
120 && m_connection->connectionType() != QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
121 h2Connection = QHttp2Connection::createUpgradedConnection(channel->socket, h2Config);
122 // Since we upgraded there is already one stream (the request was sent as http1)
123 // and we need to handle it:
124 QHttp2Stream *stream = h2Connection->getStream(1);
125 Q_ASSERT(stream);
126 Q_ASSERT(channel->reply);
127 connectStream({ channel->request, channel->reply }, stream);
128 } else {
129 Q_ASSERT(QSocketAbstraction::socketState(channel->socket) == QAbstractSocket::ConnectedState);
130 h2Connection = QHttp2Connection::createDirectConnection(channel->socket, h2Config);
131 }
132 connect(h2Connection, &QHttp2Connection::receivedGOAWAY, this,
133 &QHttp2ProtocolHandler::handleGOAWAY);
134 connect(h2Connection, &QHttp2Connection::errorOccurred, this,
135 &QHttp2ProtocolHandler::connectionError);
136 connect(h2Connection, &QHttp2Connection::newIncomingStream, this,
137 [this](QHttp2Stream *stream){
138 // Having our peer start streams doesn't make sense. We are
139 // doing regular http request-response.
140 stream->sendRST_STREAM(REFUSE_STREAM);
141 if (!h2Connection->isGoingAway())
142 h2Connection->close(Http2::PROTOCOL_ERROR);
143 });
144 connect(h2Connection, &QHttp2Connection::connectionClosed, this,
145 &QHttp2ProtocolHandler::closeSession);
146}
147
148bool QHttp2ProtocolHandler::isGoingAway() const noexcept
149{
150 return h2Connection && h2Connection->isGoingAway();
151}
152
154{
155 // The channel has just received RemoteHostClosedError and since it will
156 // not try (for HTTP/2) to re-connect, it's time to finish all replies
157 // with error.
158
159 // Maybe we still have some data to read and can successfully finish
160 // a stream/request?
161 _q_receiveReply();
162 h2Connection->handleConnectionClosure();
163}
164
165void QHttp2ProtocolHandler::_q_uploadDataDestroyed(QObject *uploadData)
166{
167 QPointer<QHttp2Stream> stream = streamIDs.take(uploadData);
168 if (stream && stream->isActive())
169 stream->sendRST_STREAM(CANCEL);
170}
171
173{
174 _q_receiveReply();
175}
176
178{
179 // not using QObject::connect because the QHttpNetworkConnectionChannel
180 // already handles the signals we care about, so we just call the slot
181 // directly.
182 Q_ASSERT(h2Connection);
183 h2Connection->handleReadyRead();
184}
185
187{
188 if (isGoingAway())
189 return false;
190
191 // Process 'fake' (created by QNetworkAccessManager::connectToHostEncrypted())
192 // requests first:
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()) {
201 // Normally, after a connection was established and H2
202 // was negotiated, we send a client preface. connectToHostEncrypted
203 // though is not meant to send any data, it's just a 'preconnect'.
204 // Thus we return early:
205 return true;
206 }
207 } else {
208 ++it;
209 }
210 }
211
212 if (requests.empty())
213 return true;
214
215 m_channel->state = QHttpNetworkConnectionChannel::WritingState;
216 // Check what was promised/pushed, maybe we do not have to send a request
217 // and have a response already?
218
219 for (auto it = requests.begin(), end = requests.end(); it != end;) {
220 HttpMessagePair &httpPair = *it;
221
222 QUrl promiseKey = urlkey_from_request(httpPair.first);
223 if (h2Connection->promisedStream(promiseKey) != nullptr) {
224 // There's a PUSH_PROMISE for this request, so we don't send one
225 initReplyFromPushPromise(httpPair, promiseKey);
226 it = requests.erase(it);
227 continue;
228 }
229
230 QHttp2Stream *stream = createNewStream(httpPair);
231 if (!stream) { // There was an issue creating the stream
232 // Check if it was unrecoverable, ie. the reply is errored out and finished:
233 if (httpPair.second->isFinished()) {
234 it = requests.erase(it);
235 }
236 // ... either way we stop looping:
237 break;
238 }
239
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);
245 continue;
246 }
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);
252 continue;
253 }
254 }
255 it = requests.erase(it);
256 }
257
258 m_channel->state = QHttpNetworkConnectionChannel::IdleState;
259
260 return true;
261}
262
263/*!
264 \internal
265 This gets called during destruction of \a reply, so do not call any functions
266 on \a reply. We check if there is a stream associated with the reply and,
267 if there is, we remove the request-reply pair associated with this stream,
268 delete the stream and return \c{true}. Otherwise nothing happens and we
269 return \c{false}.
270*/
271bool QHttp2ProtocolHandler::tryRemoveReply(QHttpNetworkReply *reply)
272{
273 QHttp2Stream *stream = streamIDs.take(reply);
274 if (stream) {
275 stream->sendRST_STREAM(stream->isUploadingDATA() ? Http2::CANCEL : Http2::HTTP2_NO_ERROR);
276 clearStreamState(stream);
277 stream->deleteLater();
278 return true;
279 }
280 return false;
281}
282
283bool QHttp2ProtocolHandler::sendHEADERS(QHttp2Stream *stream, QHttpNetworkRequest &request)
284{
285 using namespace HPack;
286
287 bool useProxy = false;
288#ifndef QT_NO_NETWORKPROXY
289 useProxy = m_connection->d_func()->networkProxy.type() != QNetworkProxy::NoProxy;
290#endif
291 if (request.withCredentials()) {
292 m_connection->d_func()->createAuthorization(m_socket, request);
293 request.d->needResendWithCredentials = false;
294 }
295 const auto headers = build_headers(request, h2Connection->maxHeaderListSize(), useProxy);
296 if (headers.empty()) // nothing fits into maxHeaderListSize
297 return false;
298
299 bool mustUploadData = request.uploadByteDevice();
300 return stream->sendHEADERS(headers, !mustUploadData);
301}
302
303bool QHttp2ProtocolHandler::sendDATA(QHttp2Stream *stream, QHttpNetworkReply *reply)
304{
305 Q_ASSERT(reply);
306 QHttpNetworkReplyPrivate *replyPrivate = reply->d_func();
307 Q_ASSERT(replyPrivate);
308 QHttpNetworkRequest &request = replyPrivate->request;
309 Q_ASSERT(request.uploadByteDevice());
310
311 bool startedSending = stream->sendDATA(request.uploadByteDevice(), true);
312 return startedSending && !stream->wasReset();
313}
314
315void QHttp2ProtocolHandler::handleHeadersReceived(const HPack::HttpHeader &headers, bool endStream)
316{
317 QHttp2Stream *stream = qobject_cast<QHttp2Stream *>(sender());
318 Q_ASSERT(stream);
319 auto &requestPair = requestReplyPairs[stream];
320 auto *httpReply = requestPair.second;
321 auto &httpRequest = requestPair.first;
322 if (!httpReply)
323 return;
324
325 auto *httpReplyPrivate = httpReply->d_func();
326
327 // For HTTP/1 'location' is handled (and redirect URL set) when a protocol
328 // handler emits channel->allDone(). Http/2 protocol handler never emits
329 // allDone, since we have many requests multiplexed in one channel at any
330 // moment and we are probably not done yet. So we extract url and set it
331 // here, if needed.
332 int statusCode = 0;
333 for (const auto &pair : headers) {
334 const auto &name = pair.name;
335 const auto value = QByteArrayView(pair.value);
336
337 // TODO: part of this code copies what SPDY protocol handler does when
338 // processing headers. Binary nature of HTTP/2 and SPDY saves us a lot
339 // of parsing and related errors/bugs, but it would be nice to have
340 // more detailed validation of headers.
341 if (name == ":status") {
342 bool ok = false;
343 if (int status = value.toInt(&ok); ok && status >= 0 && status <= 999) {
344 statusCode = status;
345 httpReply->setStatusCode(statusCode);
346 m_channel->lastStatus = statusCode; // Mostly useless for http/2, needed for auth
347 } else {
348 finishStreamWithError(stream, QNetworkReply::ProtocolInvalidOperationError,
349 "invalid :status value"_L1);
350 return;
351 }
352 } else if (name == "content-length") {
353 bool ok = false;
354 const qlonglong length = value.toLongLong(&ok);
355 if (ok)
356 httpReply->setContentLength(length);
357 } else {
358 const auto binder = name == "set-cookie" ? QByteArrayView("\n") : QByteArrayView(", ");
359 httpReply->appendHeaderField(name, QByteArray(pair.value).replace('\0', binder));
360 }
361 }
362
363 // Discard all informational (1xx) replies with the exception of 101.
364 // Also see RFC 9110 (Chapter 15.2)
365 if (statusCode == 100 || (102 <= statusCode && statusCode <= 199)) {
366 httpReplyPrivate->clearHttpLayerInformation();
367 return;
368 }
369
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);
377 return;
378 }
379
380 if (result.redirectUrl.isValid())
381 httpReply->setRedirectUrl(result.redirectUrl);
382 }
383
384 if (httpReplyPrivate->isCompressed() && httpRequest.d->autoDecompress)
385 httpReplyPrivate->removeAutoDecompressHeader();
386
387 if (QHttpNetworkReply::isHttpRedirect(statusCode)) {
388 // Note: This status code can trigger uploadByteDevice->reset() in
389 // QHttpNetworkConnectionChannel::handleStatus. Alas, we have no single
390 // request/reply, we multiplex several requests and thus we never simply
391 // call 'handleStatus'. If we have a byte-device - we try to reset it
392 // here, we don't (and can't) handle any error during reset operation.
393 if (auto *byteDevice = httpRequest.uploadByteDevice()) {
394 byteDevice->reset();
395 httpReplyPrivate->totallyUploadedData = 0;
396 }
397 }
398
399 QMetaObject::invokeMethod(httpReply, &QHttpNetworkReply::headerChanged, Qt::QueuedConnection);
400 if (endStream)
401 finishStream(stream, Qt::QueuedConnection);
402}
403
404void QHttp2ProtocolHandler::handleDataReceived(const QByteArray &data, bool endStream)
405{
406 QHttp2Stream *stream = qobject_cast<QHttp2Stream *>(sender());
407 auto &httpPair = requestReplyPairs[stream];
408 auto *httpReply = httpPair.second;
409 if (!httpReply)
410 return;
411 Q_ASSERT(!stream->isPromisedStream());
412
413 if (!data.isEmpty() && !httpPair.first.d->needResendWithCredentials) {
414 auto *replyPrivate = httpReply->d_func();
415
416 replyPrivate->totalProgress += data.size();
417
418 replyPrivate->responseData.append(data);
419
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);
426 }
427 }
428 stream->clearDownloadBuffer();
429 if (endStream)
430 finishStream(stream, Qt::QueuedConnection);
431}
432
433// After calling this function, either the request will be re-sent or
434// the reply will be finishedWithError! Do not emit finished() or similar on the
435// reply after this!
436void QHttp2ProtocolHandler::handleAuthorization(QHttp2Stream *stream)
437{
438 auto &requestPair = requestReplyPairs[stream];
439 auto *httpReply = requestPair.second;
440 auto *httpReplyPrivate = httpReply->d_func();
441 auto &httpRequest = requestPair.first;
442
443 Q_ASSERT(httpReply && (httpReply->statusCode() == 401 || httpReply->statusCode() == 407));
444
445 const auto handleAuth = [&, this](QByteArrayView authField, bool isProxy) -> bool {
446 Q_ASSERT(httpReply);
447 const QByteArrayView auth = authField.trimmed();
448 if (auth.startsWith("Negotiate") || auth.startsWith("NTLM")) {
449 // NTLM/Kerberos/Negotiate authentication is not supported with HTTP/2.
450 // Finish the stream with an error so QNetworkReply::finished is emitted.
451 // Falling back to HTTP/1.1 is a separate, larger effort (QTBUG-143926).
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));
459 return false;
460 }
461 // Somewhat mimics parts of QHttpNetworkConnectionChannel::handleStatus
462 bool resend = false;
463 const bool authenticateHandled = m_connection->d_func()->handleAuthenticateChallenge(
464 m_socket, httpReply, isProxy, resend);
465 if (authenticateHandled) {
466 if (resend) {
467 httpReply->d_func()->eraseData();
468 // Add the request back in queue, we'll retry later now that
469 // we've gotten some username/password set on it:
470 httpRequest.d->needResendWithCredentials = true;
471 m_channel->h2RequestsToSend.insert(httpRequest.priority(), requestPair);
472 httpReply->d_func()->clearHeaders();
473 // If we have data we were uploading we need to reset it:
474 if (auto *byteDevice = httpRequest.uploadByteDevice()) {
475 byteDevice->reset();
476 httpReplyPrivate->totallyUploadedData = 0;
477 }
478 // We automatically try to send new requests when the stream is
479 // closed, so we don't need to call sendRequest ourselves.
480 return true;
481 } // else: we're just not resending the request.
482 // @note In the http/1.x case we (at time of writing) call close()
483 // for the connectionChannel (which is a bit weird, we could surely
484 // reuse the open socket outside "connection:close"?), but in http2
485 // we only have one channel, so we won't close anything.
486 } else {
487 // No authentication header or authentication isn't supported, but
488 // we got a 401/407 so we cannot succeed. We need to emit signals
489 // for headers and data, and then finishWithError.
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));
497 }
498 return false;
499 };
500
501 // These statuses would in HTTP/1.1 be handled by
502 // QHttpNetworkConnectionChannel::handleStatus. But because h2 has
503 // multiple streams/requests in a single channel this structure does not
504 // map properly to that function.
505 bool authOk = true;
506 switch (httpReply->statusCode()) {
507 case 401:
508 authOk = handleAuth(httpReply->headerField("www-authenticate"), false);
509 break;
510 case 407:
511 authOk = handleAuth(httpReply->headerField("proxy-authenticate"), true);
512 break;
513 default:
514 Q_UNREACHABLE();
515 }
516 if (authOk) {
517 stream->sendRST_STREAM(CANCEL);
518 clearStreamState(stream);
519 stream->deleteLater();
520 } // else: errors handled inside handleAuth
521}
522
523// Called when we have received a frame with the END_STREAM flag set
524void QHttp2ProtocolHandler::finishStream(QHttp2Stream *stream, Qt::ConnectionType connectionType)
525{
526 if (stream->state() != QHttp2Stream::State::Closed)
527 stream->sendRST_STREAM(CANCEL);
528
529 auto &pair = requestReplyPairs[stream];
530 auto *httpReply = pair.second;
531 if (httpReply) {
532 int statusCode = httpReply->statusCode();
533 if (statusCode == 401 || statusCode == 407) {
534 // handleAuthorization will either re-send the request or
535 // finishWithError. In either case we don't want to emit finished
536 // here.
537 handleAuthorization(stream);
538 return;
539 }
540
541 httpReply->disconnect(this);
542
543 if (!pair.first.d->needResendWithCredentials) {
544 if (connectionType == Qt::DirectConnection)
545 emit httpReply->finished();
546 else
547 QMetaObject::invokeMethod(httpReply, &QHttpNetworkReply::finished, connectionType);
548 }
549 }
550
551 clearStreamState(stream);
552 qCDebug(QT_HTTP2) << "stream" << stream->streamID() << "closed";
553
554 // Detach the reply and tear down the stream via canonical path, so a
555 // later stray frame cannot fail an already-finished reply. tryRemoveReply()
556 // also clears the reply->stream map, its sendRST_STREAM() does nothing on a
557 // gracefully closed stream.
558 if (!httpReply || !tryRemoveReply(httpReply)) {
559 requestReplyPairs.remove(stream);
560 stream->deleteLater();
561 }
562}
563
564void QHttp2ProtocolHandler::handleGOAWAY(Http2Error errorCode, quint32 lastStreamID)
565{
566 qCDebug(QT_HTTP2) << "GOAWAY received, error code:" << errorCode << "last stream ID:"
567 << lastStreamID;
568
569 if (errorCode == HTTP2_NO_ERROR) {
570 // Graceful GOAWAY: the queued requests are sent on the next connection.
571 // *noop*
572 } else {
573 // Error GOAWAY: the queued requests were never processed, so a retry could still
574 // succeed, but something went wrong on this connection - report it to the user
575 // rather than silently trying again.
576 m_channel->emitFinishedWithError(QNetworkReply::ProtocolUnknownError,
577 "GOAWAY received, cannot start a request");
578 m_channel->h2RequestsToSend.clear();
579 }
580
581 // Active streams are not handled here: QHttp2Connection::handleGOAWAY() cancels the ones
582 // the peer will not process and we pick them up through QHttp2Stream::errorOccurred.
583}
584
585void QHttp2ProtocolHandler::finishStreamWithError(QHttp2Stream *stream, Http2Error errorCode)
586{
587 QNetworkReply::NetworkError error = QNetworkReply::NoError;
588 QString message;
589 qt_error(errorCode, error, message);
590 finishStreamWithError(stream, error, message);
591}
592
593void QHttp2ProtocolHandler::finishStreamWithError(QHttp2Stream *stream,
594 QNetworkReply::NetworkError error, const QString &message)
595{
596 stream->sendRST_STREAM(CANCEL);
597 const HttpMessagePair &pair = requestReplyPairs.value(stream);
598 if (auto *httpReply = pair.second) {
599 httpReply->disconnect(this);
600
601 // TODO: error message must be translated!!! (tr)
602 httpReply->d_func()->setError(error, message);
603 emit httpReply->finishedWithError(error, message);
604 }
605
606 clearStreamState(stream);
607 stream->deleteLater();
608 qCWarning(QT_HTTP2) << "stream" << stream->streamID() << "finished with error:" << message;
609}
610
611/*!
612 \internal
613
614 Creates a QHttp2Stream for the request, will return \nullptr if the stream
615 could not be created for some reason, and will finish the reply if required.
616*/
617QHttp2Stream *QHttp2ProtocolHandler::createNewStream(const HttpMessagePair &message,
618 bool uploadDone)
619{
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;
624 }
625
626 QH2Expected<QHttp2Stream *, QHttp2Connection::CreateStreamError>
627 streamResult = h2Connection->createStream();
628 if (!streamResult.ok()) {
629 if (streamResult.error()
630 == QHttp2Connection::CreateStreamError::MaxConcurrentStreamsReached) {
631 // We have to wait for a stream to be closed before we can create a new one, so
632 // we just return nullptr, the caller should not remove it from the queue.
633 return nullptr;
634 }
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);
642 return nullptr;
643 }
644 QHttp2Stream *stream = streamResult.unwrap();
645
646 if (!uploadDone) {
647 if (auto *src = message.first.uploadByteDevice()) {
648 connect(src, &QObject::destroyed, this, &QHttp2ProtocolHandler::_q_uploadDataDestroyed);
649 streamIDs.insert(src, stream);
650 }
651 }
652
653 auto *reply = message.second;
654 QMetaObject::invokeMethod(reply, &QHttpNetworkReply::requestSent, Qt::QueuedConnection);
655
656 connectStream(message, stream);
657 return stream;
658}
659
660void QHttp2ProtocolHandler::connectStream(const HttpMessagePair &message, QHttp2Stream *stream)
661{
662 auto *reply = message.second;
663 auto *replyPrivate = reply->d_func();
664 replyPrivate->connection = m_connection;
665 replyPrivate->connectionChannel = m_channel;
666
667 reply->setHttp2WasUsed(true);
668 QPointer<QHttp2Stream> &oldStream = streamIDs[reply];
669 if (oldStream) {
670 disconnect(oldStream, nullptr, this, nullptr);
671 clearStreamState(oldStream);
672 }
673 oldStream = stream;
674 requestReplyPairs.emplace(stream, message);
675
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) {
682 qCWarning(QT_HTTP2)
683 << "stream" << stream->streamID() << "error:" << errorString;
684 // A graceful GOAWAY cancels exactly the streams the peer will not
685 // process, so those requests can still be sent on a new connection.
686 // An error GOAWAY, or any other failure, keeps its own error.
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(
693 "QHttp",
694 "Server stopped accepting new streams before this "
695 "stream was established"));
696 } else {
697 finishStreamWithError(stream, errorCode);
698 }
699 });
700
701 QObject::connect(stream, &QHttp2Stream::stateChanged, this, [this](QHttp2Stream::State state) {
702 if (state == QHttp2Stream::State::Closed) {
703 // Try to send more requests if we have any
704 if (!m_channel->h2RequestsToSend.empty()) {
705 QMetaObject::invokeMethod(this, &QHttp2ProtocolHandler::sendRequest,
706 Qt::QueuedConnection);
707 }
708 }
709 });
710}
711
712void QHttp2ProtocolHandler::clearStreamState(QHttp2Stream *stream)
713{
714 auto it = requestReplyPairs.find(stream);
715 if (it == requestReplyPairs.end())
716 return;
717
718 if (auto *reply = it->second)
719 streamIDs.remove(reply);
720 if (auto *uploadDevice = it->first.uploadByteDevice())
721 streamIDs.remove(uploadDevice);
722
723 requestReplyPairs.erase(it);
724}
725
726void QHttp2ProtocolHandler::initReplyFromPushPromise(const HttpMessagePair &message,
727 const QUrl &cacheKey)
728{
729 QHttp2Stream *promise = h2Connection->promisedStream(cacheKey);
730 Q_ASSERT(promise);
731 Q_ASSERT(message.second);
732 message.second->setHttp2WasUsed(true);
733
734 qCDebug(QT_HTTP2) << "found cached/promised response on stream" << promise->streamID();
735
736 const bool replyFinished = promise->state() == QHttp2Stream::State::Closed;
737
738 connectStream(message, promise);
739
740 // Now that we have connect()ed, re-emit signals so that the reply
741 // can be processed as usual:
742
743 QByteDataBuffer downloadBuffer = promise->takeDownloadBuffer();
744 if (const auto &headers = promise->receivedHeaders(); !headers.empty())
745 emit promise->headersReceived(headers, replyFinished && downloadBuffer.isEmpty());
746
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);
751 }
752 }
753}
754
755void QHttp2ProtocolHandler::connectionError(Http2::Http2Error errorCode, const QString &message)
756{
757 Q_ASSERT(!message.isNull());
758
759 qCCritical(QT_HTTP2) << "connection error:" << message;
760
761 const auto error = qt_error(errorCode);
762 m_channel->emitFinishedWithError(error, message);
763 m_channel->h2RequestsToSend.clear();
764
765 closeSession();
766}
767
768void QHttp2ProtocolHandler::closeSession()
769{
770 m_channel->close();
771}
772
773QT_END_NAMESPACE
774
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
bool tryRemoveReply(QHttpNetworkReply *reply) override
static ParseRedirectResult parseRedirectResponse(QHttpNetworkReply *reply)
Combined button and popup list for selecting options.
std::pair< QHttpNetworkRequest, QHttpNetworkReply * > HttpMessagePair