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
qhttpnetworkconnectionchannel.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2014 BlackBerry Limited. All rights reserved.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:critical reason:network-protocol
5
8#include "private/qnoncontiguousbytedevice_p.h"
9
10#include <qdebug.h>
11
12#include <private/qhttp2protocolhandler_p.h>
13#include <private/qhttpprotocolhandler_p.h>
14#include <private/http2protocol_p.h>
15#include <private/qsocketabstraction_p.h>
16
17#ifndef QT_NO_SSL
18# include <private/qsslsocket_p.h>
19# include <QtNetwork/qsslkey.h>
20# include <QtNetwork/qsslcipher.h>
21#endif
22
23#include <QtNetwork/private/qtnetworkglobal_p.h>
24
25#include <memory>
26#include <utility>
27
29
30// TODO: Put channel specific stuff here so it does not pollute qhttpnetworkconnection.cpp
31
32// Because in-flight when sending a request, the server might close our connection (because the persistent HTTP
33// connection times out)
34// We use 3 because we can get a _q_error 3 times depending on the timing:
35static const int reconnectAttemptsDefault = 3;
36static const char keepAliveIdleOption[] = "QT_QNAM_TCP_KEEPIDLE";
37static const char keepAliveIntervalOption[] = "QT_QNAM_TCP_KEEPINTVL";
38static const char keepAliveCountOption[] = "QT_QNAM_TCP_KEEPCNT";
39static const int TCP_KEEPIDLE_DEF = 60;
40static const int TCP_KEEPINTVL_DEF = 10;
41static const int TCP_KEEPCNT_DEF = 5;
42
44 : socket(nullptr)
45 , ssl(false)
46 , isInitialized(false)
48 , reply(nullptr)
49 , written(0)
50 , bytesTotal(0)
51 , resendCurrent(false)
52 , lastStatus(0)
53 , pendingEncrypt(false)
57 , protocolHandler(nullptr)
58#ifndef QT_NO_SSL
59 , ignoreAllSslErrors(false)
60#endif
63 , connection(nullptr)
64{
65 // Inlining this function in the header leads to compiler error on
66 // release-armv5, on at least timebox 9.2 and 10.1.
67}
68
70{
71#ifndef QT_NO_SSL
72 if (connection->d_func()->encrypt)
73 socket = new QSslSocket;
74#if QT_CONFIG(localserver)
75 else if (connection->d_func()->isLocalSocket)
76 socket = new QLocalSocket;
77#endif
78 else
79 socket = new QTcpSocket;
80#else
81 socket = new QTcpSocket;
82#endif
83#ifndef QT_NO_NETWORKPROXY
84 // Set by QNAM anyway, but let's be safe here
85 if (auto s = qobject_cast<QAbstractSocket *>(socket))
86 s->setProxy(QNetworkProxy::NoProxy);
87#endif
88
89 // After some back and forth in all the last years, this is now a DirectConnection because otherwise
90 // the state inside the *Socket classes gets messed up, also in conjunction with the socket notifiers
91 // which behave slightly differently on Windows vs Linux
92 QObject::connect(socket, &QIODevice::bytesWritten,
93 this, &QHttpNetworkConnectionChannel::_q_bytesWritten,
94 Qt::DirectConnection);
95 QObject::connect(socket, &QIODevice::readyRead,
96 this, &QHttpNetworkConnectionChannel::_q_readyRead,
97 Qt::DirectConnection);
98
99
100 QSocketAbstraction::visit([this](auto *socket){
101 using SocketType = std::remove_pointer_t<decltype(socket)>;
102 QObject::connect(socket, &SocketType::connected,
103 this, &QHttpNetworkConnectionChannel::_q_connected,
104 Qt::DirectConnection);
105
106 // The disconnected() and error() signals may already come
107 // while calling connectToHost().
108 // In case of a cached hostname or an IP this
109 // will then emit a signal to the user of QNetworkReply
110 // but cannot be caught because the user did not have a chance yet
111 // to connect to QNetworkReply's signals.
112 QObject::connect(socket, &SocketType::disconnected,
113 this, &QHttpNetworkConnectionChannel::_q_disconnected,
114 Qt::DirectConnection);
115 if constexpr (std::is_same_v<SocketType, QAbstractSocket>) {
116 QObject::connect(socket, &QAbstractSocket::errorOccurred,
117 this, &QHttpNetworkConnectionChannel::_q_error,
118 Qt::DirectConnection);
119#if QT_CONFIG(localserver)
120 } else if constexpr (std::is_same_v<SocketType, QLocalSocket>) {
121 auto convertAndForward = [this](QLocalSocket::LocalSocketError error) {
122 _q_error(static_cast<QAbstractSocket::SocketError>(error));
123 };
124 QObject::connect(socket, &SocketType::errorOccurred,
125 this, std::move(convertAndForward),
126 Qt::DirectConnection);
127#endif
128 }
129 }, socket);
130
131
132
133#ifndef QT_NO_NETWORKPROXY
134 if (auto *s = qobject_cast<QAbstractSocket *>(socket)) {
135 QObject::connect(s, &QAbstractSocket::proxyAuthenticationRequired,
136 this, &QHttpNetworkConnectionChannel::_q_proxyAuthenticationRequired,
137 Qt::DirectConnection);
138 }
139#endif
140
141#ifndef QT_NO_SSL
142 QSslSocket *sslSocket = qobject_cast<QSslSocket*>(socket);
143 if (sslSocket) {
144 // won't be a sslSocket if encrypt is false
145 QObject::connect(sslSocket, &QSslSocket::encrypted,
146 this, &QHttpNetworkConnectionChannel::_q_encrypted,
147 Qt::DirectConnection);
148 QObject::connect(sslSocket, &QSslSocket::sslErrors,
149 this, &QHttpNetworkConnectionChannel::_q_sslErrors,
150 Qt::DirectConnection);
151 QObject::connect(sslSocket, &QSslSocket::preSharedKeyAuthenticationRequired,
152 this, &QHttpNetworkConnectionChannel::_q_preSharedKeyAuthenticationRequired,
153 Qt::DirectConnection);
154 QObject::connect(sslSocket, &QSslSocket::encryptedBytesWritten,
155 this, &QHttpNetworkConnectionChannel::_q_encryptedBytesWritten,
156 Qt::DirectConnection);
157
158 // AXIVION DISABLE Qt-Security-QSslSocketIgnoreSslErrors: intentional behavior
160 sslSocket->ignoreSslErrors();
161
162 if (!ignoreSslErrorsList.isEmpty())
163 sslSocket->ignoreSslErrors(ignoreSslErrorsList);
164 // AXIVION ENABLE Qt-Security-QSslSocketIgnoreSslErrors
165
166 if (sslConfiguration && !sslConfiguration->isNull())
167 sslSocket->setSslConfiguration(*sslConfiguration);
168 } else {
169#endif // !QT_NO_SSL
170 if (connection->connectionType() != QHttpNetworkConnection::ConnectionTypeHTTP2)
171 protocolHandler.reset(new QHttpProtocolHandler(this));
172#ifndef QT_NO_SSL
173 }
174#endif
175
176#ifndef QT_NO_NETWORKPROXY
177 if (auto *s = qobject_cast<QAbstractSocket *>(socket);
178 s && proxy.type() != QNetworkProxy::NoProxy) {
179 s->setProxy(proxy);
180 }
181#endif
182 isInitialized = true;
183}
184
185
187{
188 if (state == QHttpNetworkConnectionChannel::ClosingState)
189 return;
190
191 if (!socket)
192 state = QHttpNetworkConnectionChannel::IdleState;
193 else if (QSocketAbstraction::socketState(socket) == QAbstractSocket::UnconnectedState)
194 state = QHttpNetworkConnectionChannel::IdleState;
195 else
196 state = QHttpNetworkConnectionChannel::ClosingState;
197
198 // pendingEncrypt must only be true in between connected and encrypted states
199 pendingEncrypt = false;
200
201 if (socket) {
202 // socket can be 0 since the host lookup is done from qhttpnetworkconnection.cpp while
203 // there is no socket yet.
204 socket->close();
205 }
206}
207
208
210{
211 if (!socket)
212 state = QHttpNetworkConnectionChannel::IdleState;
213 else if (QSocketAbstraction::socketState(socket) == QAbstractSocket::UnconnectedState)
214 state = QHttpNetworkConnectionChannel::IdleState;
215 else
216 state = QHttpNetworkConnectionChannel::ClosingState;
217
218 // pendingEncrypt must only be true in between connected and encrypted states
219 pendingEncrypt = false;
220
221 if (socket) {
222 // socket can be 0 since the host lookup is done from qhttpnetworkconnection.cpp while
223 // there is no socket yet.
224 auto callAbort = [](auto *s) {
225 s->abort();
226 };
227 QSocketAbstraction::visit(callAbort, socket);
228 }
229}
230
231
233{
236 return;
237 }
239 return;
240 Q_ASSERT(protocolHandler);
241 protocolHandler->sendRequest();
242}
243
244/*
245 * Invoke "protocolHandler->sendRequest" using a queued connection.
246 * It's used to return to the event loop before invoking sendRequest when
247 * there's a very real chance that the request could have been aborted
248 * (i.e. after having emitted 'encrypted').
249 */
251{
252 QMetaObject::invokeMethod(this, [this] {
253 if (reply)
254 sendRequest();
255 }, Qt::ConnectionType::QueuedConnection);
256}
257
258void QHttpNetworkConnectionChannel::_q_receiveReply()
259{
260 Q_ASSERT(protocolHandler);
263 return;
264 }
265 protocolHandler->_q_receiveReply();
266}
267
269{
270 Q_ASSERT(protocolHandler);
272 needInvokeReadyRead = true;
273 return;
274 }
275 protocolHandler->_q_readyRead();
276}
277
278// called when unexpectedly reading a -1 or when data is expected but socket is closed
280{
281 Q_ASSERT(reply);
282 if (reconnectAttempts <= 0 || !request.methodIsIdempotent()) {
283 // too many errors reading/receiving/parsing the status, close the socket and emit error
285 close();
286 reply->d_func()->setError(
287 QNetworkReply::RemoteHostClosedError,
288 connection->d_func()->errorDetail(QNetworkReply::RemoteHostClosedError, socket));
289 emit reply->finishedWithError(QNetworkReply::RemoteHostClosedError, reply->d_func()->errorString);
290 reply = nullptr;
291 if (protocolHandler)
292 protocolHandler->setReply(nullptr);
293 request = QHttpNetworkRequest();
294 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
295 } else {
297 reply->d_func()->clear();
298 reply->d_func()->connection = connection;
299 reply->d_func()->connectionChannel = this;
301 }
302}
303
305{
306 if (!isInitialized)
307 init();
308
309 QAbstractSocket::SocketState socketState = QSocketAbstraction::socketState(socket);
310
311 // resend this request after we receive the disconnected signal
312 // If !socket->isOpen() then we have already called close() on the socket, but there was still a
313 // pending connectToHost() for which we hadn't seen a connected() signal, yet. The connected()
314 // has now arrived (as indicated by socketState != ClosingState), but we cannot send anything on
315 // such a socket anymore.
316 if (socketState == QAbstractSocket::ClosingState ||
317 (socketState != QAbstractSocket::UnconnectedState && !socket->isOpen())) {
318 if (reply)
319 resendCurrent = true;
320 return false;
321 }
322
323 // already trying to connect?
324 if (socketState == QAbstractSocket::HostLookupState ||
325 socketState == QAbstractSocket::ConnectingState) {
326 return false;
327 }
328
329 // make sure that this socket is in a connected state, if not initiate
330 // connection to the host.
331 if (socketState != QAbstractSocket::ConnectedState) {
332 // connect to the host if not already connected.
333 state = QHttpNetworkConnectionChannel::ConnectingState;
335
336 // reset state
339 proxyCredentialsSent = false;
340 authenticator.detach();
341 QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(authenticator);
342 priv->hasFailed = false;
343 proxyAuthenticator.detach();
344 priv = QAuthenticatorPrivate::getPrivate(proxyAuthenticator);
345 priv->hasFailed = false;
346
347 // This workaround is needed since we use QAuthenticator for NTLM authentication. The "phase == Done"
348 // is the usual criteria for emitting authentication signals. The "phase" is set to "Done" when the
349 // last header for Authorization is generated by the QAuthenticator. Basic & Digest logic does not
350 // check the "phase" for generating the Authorization header. NTLM authentication is a two stage
351 // process & needs the "phase". To make sure the QAuthenticator uses the current username/password
352 // the phase is reset to Start.
353 priv = QAuthenticatorPrivate::getPrivate(authenticator);
354 if (priv && priv->phase == QAuthenticatorPrivate::Done)
355 priv->phase = QAuthenticatorPrivate::Start;
356 priv = QAuthenticatorPrivate::getPrivate(proxyAuthenticator);
357 if (priv && priv->phase == QAuthenticatorPrivate::Done)
358 priv->phase = QAuthenticatorPrivate::Start;
359
360 QString connectHost = connection->d_func()->hostName;
361 quint16 connectPort = connection->d_func()->port;
362
363 QHttpNetworkReply *potentialReply = connection->d_func()->predictNextRequestsReply();
364 if (potentialReply) {
365 QMetaObject::invokeMethod(potentialReply, "socketStartedConnecting", Qt::QueuedConnection);
366 } else if (!h2RequestsToSend.isEmpty()) {
367 QMetaObject::invokeMethod(std::as_const(h2RequestsToSend).first().second, "socketStartedConnecting", Qt::QueuedConnection);
368 }
369
370#ifndef QT_NO_NETWORKPROXY
371 // HTTPS always use transparent proxy.
372 if (connection->d_func()->networkProxy.type() != QNetworkProxy::NoProxy && !ssl) {
373 connectHost = connection->d_func()->networkProxy.hostName();
374 connectPort = connection->d_func()->networkProxy.port();
375 }
376 if (auto *abSocket = qobject_cast<QAbstractSocket *>(socket);
377 abSocket && abSocket->proxy().type() == QNetworkProxy::HttpProxy) {
378 // Make user-agent field available to HTTP proxy socket engine (QTBUG-17223)
379 QByteArray value;
380 // ensureConnection is called before any request has been assigned, but can also be
381 // called again if reconnecting
382 if (request.url().isEmpty()) {
383 if (connection->connectionType()
384 == QHttpNetworkConnection::ConnectionTypeHTTP2Direct
385 || (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
386 && !h2RequestsToSend.isEmpty())) {
387 value = std::as_const(h2RequestsToSend).first().first.headerField("user-agent");
388 } else {
389 value = connection->d_func()->predictNextRequest().headerField("user-agent");
390 }
391 } else {
392 value = request.headerField("user-agent");
393 }
394 if (!value.isEmpty()) {
395 QNetworkProxy proxy(abSocket->proxy());
396 auto h = proxy.headers();
397 h.replaceOrAppend(QHttpHeaders::WellKnownHeader::UserAgent, value);
398 proxy.setHeaders(std::move(h));
399 abSocket->setProxy(proxy);
400 }
401 }
402#endif
403 if (ssl) {
404#ifndef QT_NO_SSL
405 QSslSocket *sslSocket = qobject_cast<QSslSocket*>(socket);
406
407 // check whether we can re-use an existing SSL session
408 // (meaning another socket in this connection has already
409 // performed a full handshake)
410 if (auto ctx = connection->sslContext())
411 QSslSocketPrivate::checkSettingSslContext(sslSocket, std::move(ctx));
412
413 sslSocket->setPeerVerifyName(connection->d_func()->peerVerifyName);
414 sslSocket->connectToHostEncrypted(connectHost, connectPort, QIODevice::ReadWrite, networkLayerPreference);
415 // AXIVION DISABLE Qt-Security-QSslSocketIgnoreSslErrors: intentional behavior
417 sslSocket->ignoreSslErrors();
418 sslSocket->ignoreSslErrors(ignoreSslErrorsList);
419 // AXIVION ENABLE Qt-Security-QSslSocketIgnoreSslErrors
420
421 // limit the socket read buffer size. we will read everything into
422 // the QHttpNetworkReply anyway, so let's grow only that and not
423 // here and there.
424 sslSocket->setReadBufferSize(64*1024);
425#else
426 // Need to dequeue the request so that we can emit the error.
427 if (!reply)
428 connection->d_func()->dequeueRequest(socket);
429 connection->d_func()->emitReplyError(socket, reply, QNetworkReply::ProtocolUnknownError);
430#endif
431 } else {
432 // In case of no proxy we can use the Unbuffered QTcpSocket
433#ifndef QT_NO_NETWORKPROXY
434 if (connection->d_func()->networkProxy.type() == QNetworkProxy::NoProxy
435 && connection->cacheProxy().type() == QNetworkProxy::NoProxy
436 && connection->transparentProxy().type() == QNetworkProxy::NoProxy) {
437#endif
438 if (auto *s = qobject_cast<QAbstractSocket *>(socket)) {
439 s->connectToHost(connectHost, connectPort,
440 QIODevice::ReadWrite | QIODevice::Unbuffered,
441 networkLayerPreference);
442 // For an Unbuffered QTcpSocket, the read buffer size has a special meaning.
443 s->setReadBufferSize(1 * 1024);
444#if QT_CONFIG(localserver)
445 } else if (auto *s = qobject_cast<QLocalSocket *>(socket)) {
446 s->connectToServer(connectHost);
447#endif
448 }
449#ifndef QT_NO_NETWORKPROXY
450 } else {
451 auto *s = qobject_cast<QAbstractSocket *>(socket);
452 Q_ASSERT(s);
453 // limit the socket read buffer size. we will read everything into
454 // the QHttpNetworkReply anyway, so let's grow only that and not
455 // here and there.
456 s->connectToHost(connectHost, connectPort, QIODevice::ReadWrite, networkLayerPreference);
457 s->setReadBufferSize(64 * 1024);
458 }
459#endif
460 }
461 return false;
462 }
463
464 // This code path for ConnectedState
465 if (pendingEncrypt) {
466 // Let's only be really connected when we have received the encrypted() signal. Else the state machine seems to mess up
467 // and corrupt the things sent to the server.
468 return false;
469 }
470
471 return true;
472}
473
475{
476 Q_ASSERT(reply);
477
478 if (!reply) {
479 qWarning("QHttpNetworkConnectionChannel::allDone() called without reply. Please report at http://bugreports.qt.io/");
480 return;
481 }
482
483 // For clear text HTTP/2 we tried to upgrade from HTTP/1.1 to HTTP/2; for
484 // ConnectionTypeHTTP2Direct we can never be here in case of failure
485 // (after an attempt to read HTTP/1.1 as HTTP/2 frames) or we have a normal
486 // HTTP/2 response and thus can skip this test:
487 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
488 && !ssl && !switchedToHttp2) {
489 if (Http2::is_protocol_upgraded(*reply)) {
490 switchedToHttp2 = true;
491 protocolHandler->setReply(nullptr);
492
493 // As allDone() gets called from the protocol handler, it's not yet
494 // safe to delete it. There is no 'deleteLater', since
495 // QAbstractProtocolHandler is not a QObject. Instead delete it in
496 // a queued emission.
497
498 QMetaObject::invokeMethod(this, [oldHandler = std::move(protocolHandler)]() mutable {
499 oldHandler.reset();
500 }, Qt::QueuedConnection);
501
502 connection->fillHttp2Queue();
503 protocolHandler.reset(new QHttp2ProtocolHandler(this));
504 QHttp2ProtocolHandler *h2c = static_cast<QHttp2ProtocolHandler *>(protocolHandler.get());
505 QMetaObject::invokeMethod(h2c, "_q_receiveReply", Qt::QueuedConnection);
506 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
507 return;
508 } else {
509 // Ok, whatever happened, we do not try HTTP/2 anymore ...
510 connection->setConnectionType(QHttpNetworkConnection::ConnectionTypeHTTP);
511 connection->d_func()->activeChannelCount = connection->d_func()->channelCount;
512 }
513 }
514
515 // while handling 401 & 407, we might reset the status code, so save this.
516 bool emitFinished = reply->d_func()->shouldEmitSignals();
517 bool connectionCloseEnabled = reply->d_func()->isConnectionCloseEnabled();
519
521 // handleStatus() might have removed the reply because it already called connection->emitReplyError()
522
523 // queue the finished signal, this is required since we might send new requests from
524 // slot connected to it. The socket will not fire readyRead signal, if we are already
525 // in the slot connected to readyRead
526 if (reply && emitFinished)
527 QMetaObject::invokeMethod(reply, "finished", Qt::QueuedConnection);
528
529
530 // reset the reconnection attempts after we receive a complete reply.
531 // in case of failures, each channel will attempt two reconnects before emitting error.
533
534 // now the channel can be seen as free/idle again, all signal emissions for the reply have been done
535 if (state != QHttpNetworkConnectionChannel::ClosingState)
536 state = QHttpNetworkConnectionChannel::IdleState;
537
538 // if it does not need to be sent again we can set it to 0
539 // the previous code did not do that and we had problems with accidental re-sending of a
540 // finished request.
541 // Note that this may trigger a segfault at some other point. But then we can fix the underlying
542 // problem.
543 if (!resendCurrent) {
544 request = QHttpNetworkRequest();
545 reply = nullptr;
546 protocolHandler->setReply(nullptr);
547 }
548
549 // move next from pipeline to current request
550 if (!alreadyPipelinedRequests.isEmpty()) {
551 if (resendCurrent || connectionCloseEnabled || QSocketAbstraction::socketState(socket) != QAbstractSocket::ConnectedState) {
552 // move the pipelined ones back to the main queue
554 close();
555 } else {
556 // there were requests pipelined in and we can continue
557 HttpMessagePair messagePair = alreadyPipelinedRequests.takeFirst();
558
559 request = messagePair.first;
560 reply = messagePair.second;
561 protocolHandler->setReply(messagePair.second);
562 state = QHttpNetworkConnectionChannel::ReadingState;
563 resendCurrent = false;
564
565 written = 0; // message body, excluding the header, irrelevant here
566 bytesTotal = 0; // message body total, excluding the header, irrelevant here
567
568 // pipeline even more
569 connection->d_func()->fillPipeline(socket);
570
571 // continue reading
572 //_q_receiveReply();
573 // this was wrong, allDone gets called from that function anyway.
574 }
575 } else if (alreadyPipelinedRequests.isEmpty() && socket->bytesAvailable() > 0) {
576 // this is weird. we had nothing pipelined but still bytes available. better close it.
577 close();
578
579 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
580 } else if (alreadyPipelinedRequests.isEmpty()) {
581 if (connectionCloseEnabled)
582 if (QSocketAbstraction::socketState(socket) != QAbstractSocket::UnconnectedState)
583 close();
584 if (qobject_cast<QHttpNetworkConnection*>(connection))
585 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
586 }
587}
588
590{
591 Q_ASSERT(reply);
592 // detect HTTP Pipelining support
593 QByteArray serverHeaderField;
594 if (
595 // check for HTTP/1.1
596 (reply->majorVersion() == 1 && reply->minorVersion() == 1)
597 // check for not having connection close
598 && (!reply->d_func()->isConnectionCloseEnabled())
599 // check if it is still connected
600 && (QSocketAbstraction::socketState(socket) == QAbstractSocket::ConnectedState)
601 // check for broken servers in server reply header
602 // this is adapted from http://mxr.mozilla.org/firefox/ident?i=SupportsPipelining
603 && (serverHeaderField = reply->headerField("Server"), !serverHeaderField.contains("Microsoft-IIS/4."))
604 && (!serverHeaderField.contains("Microsoft-IIS/5."))
605 && (!serverHeaderField.contains("Netscape-Enterprise/3."))
606 // this is adpoted from the knowledge of the Nokia 7.x browser team (DEF143319)
607 && (!serverHeaderField.contains("WebLogic"))
608 && (!serverHeaderField.startsWith("Rocket")) // a Python Web Server, see Web2py.com
609 ) {
611 } else {
613 }
614}
615
616// called when the connection broke and we need to queue some pipelined requests again
618{
619 for (int i = 0; i < alreadyPipelinedRequests.size(); i++)
620 connection->d_func()->requeueRequest(alreadyPipelinedRequests.at(i));
621 alreadyPipelinedRequests.clear();
622
623 // only run when the QHttpNetworkConnection is not currently being destructed, e.g.
624 // this function is called from _q_disconnected which is called because
625 // of ~QHttpNetworkConnectionPrivate
626 if (qobject_cast<QHttpNetworkConnection*>(connection))
627 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
628}
629
631{
632 Q_ASSERT(socket);
633 Q_ASSERT(reply);
634
635 int statusCode = reply->statusCode();
636 bool resend = false;
637
638 switch (statusCode) {
639 case 301:
640 case 302:
641 case 303:
642 case 305:
643 case 307:
644 case 308: {
645 // Parse the response headers and get the "location" url
646 QUrl redirectUrl = connection->d_func()->parseRedirectResponse(socket, reply);
647 if (redirectUrl.isValid())
648 reply->setRedirectUrl(redirectUrl);
649
650 if ((statusCode == 307 || statusCode == 308) && !resetUploadData()) {
651 // Couldn't reset the upload data, which means it will be unable to POST the data -
652 // this would lead to a long wait until it eventually failed and then retried.
653 // Instead of doing that we fail here instead, resetUploadData will already have emitted
654 // a ContentReSendError, so we're done.
655 } else if (qobject_cast<QHttpNetworkConnection *>(connection)) {
656 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
657 }
658 break;
659 }
660 case 401: // auth required
661 case 407: // proxy auth required
662 if (connection->d_func()->handleAuthenticateChallenge(socket, reply, (statusCode == 407), resend)) {
663 if (resend) {
665 break;
666
667 reply->d_func()->eraseData();
668
669 if (alreadyPipelinedRequests.isEmpty()) {
670 // this does a re-send without closing the connection
671 resendCurrent = true;
672 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
673 } else {
674 // we had requests pipelined.. better close the connection in closeAndResendCurrentRequest
676 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
677 }
678 } else {
679 //authentication cancelled, close the channel.
680 close();
681 }
682 } else {
683 emit reply->headerChanged();
684 emit reply->readyRead();
685 QNetworkReply::NetworkError errorCode = (statusCode == 407)
686 ? QNetworkReply::ProxyAuthenticationRequiredError
687 : QNetworkReply::AuthenticationRequiredError;
688 reply->d_func()->setError(errorCode,
689 connection->d_func()->errorDetail(errorCode, socket));
690 emit reply->finishedWithError(errorCode, reply->d_func()->errorString);
691 }
692 break;
693 default:
694 if (qobject_cast<QHttpNetworkConnection*>(connection))
695 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
696 }
697}
698
700{
701 if (!reply) {
702 //this happens if server closes connection while QHttpNetworkConnectionPrivate::_q_startNextRequest is pending
703 return false;
704 }
705 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct
706 || switchedToHttp2) {
707 // The else branch doesn't make any sense for HTTP/2, since 1 channel is multiplexed into
708 // many streams. And having one stream fail to reset upload data should not completely close
709 // the channel. Handled in the http2 protocol handler.
710 } else if (QNonContiguousByteDevice *uploadByteDevice = request.uploadByteDevice()) {
711 if (!uploadByteDevice->reset()) {
712 connection->d_func()->emitReplyError(socket, reply, QNetworkReply::ContentReSendError);
713 return false;
714 }
715 written = 0;
716 }
717 return true;
718}
719
720#ifndef QT_NO_NETWORKPROXY
721
722void QHttpNetworkConnectionChannel::setProxy(const QNetworkProxy &networkProxy)
723{
724 if (auto *s = qobject_cast<QAbstractSocket *>(socket))
725 s->setProxy(networkProxy);
726
727 proxy = networkProxy;
728}
729
730#endif
731
732#ifndef QT_NO_SSL
733
735{
736 // AXIVION DISABLE Qt-Security-QSslSocketIgnoreSslErrors: intentional behavior
737 if (socket)
738 static_cast<QSslSocket *>(socket)->ignoreSslErrors();
739 // AXIVION ENABLE Qt-Security-QSslSocketIgnoreSslErrors
740
741 ignoreAllSslErrors = true;
742}
743
744
745void QHttpNetworkConnectionChannel::ignoreSslErrors(const QList<QSslError> &errors)
746{
747 // AXIVION DISABLE Qt-Security-QSslSocketIgnoreSslErrors: intentional behavior
748 if (socket)
749 static_cast<QSslSocket *>(socket)->ignoreSslErrors(errors);
750 // AXIVION ENABLE Qt-Security-QSslSocketIgnoreSslErrors
751
752 ignoreSslErrorsList = errors;
753}
754
755void QHttpNetworkConnectionChannel::setSslConfiguration(const QSslConfiguration &config)
756{
757 if (socket)
758 static_cast<QSslSocket *>(socket)->setSslConfiguration(config);
759
760 if (sslConfiguration)
761 *sslConfiguration = config;
762 else
763 sslConfiguration = QSslConfiguration(config);
764}
765
766#endif
767
769{
770 // this is only called for simple GET
771
772 QHttpNetworkRequest &request = pair.first;
773 QHttpNetworkReply *reply = pair.second;
774 reply->d_func()->clear();
775 reply->d_func()->connection = connection;
776 reply->d_func()->connectionChannel = this;
777 reply->d_func()->autoDecompress = request.d->autoDecompress;
778 reply->d_func()->pipeliningUsed = true;
779
780#ifndef QT_NO_NETWORKPROXY
781 pipeline.append(QHttpNetworkRequestPrivate::header(request,
782 (connection->d_func()->networkProxy.type() != QNetworkProxy::NoProxy)));
783#else
784 pipeline.append(QHttpNetworkRequestPrivate::header(request, false));
785#endif
786
787 alreadyPipelinedRequests.append(pair);
788
789 // pipelineFlush() needs to be called at some point afterwards
790}
791
793{
794 if (pipeline.isEmpty())
795 return;
796
797 // The goal of this is so that we have everything in one TCP packet.
798 // For the Unbuffered QTcpSocket this is manually needed, the buffered
799 // QTcpSocket does it automatically.
800 // Also, sometimes the OS does it for us (Nagle's algorithm) but that
801 // happens only sometimes.
802 socket->write(pipeline);
803 pipeline.clear();
804}
805
806
808{
810 close();
811 if (reply)
812 resendCurrent = true;
813 if (qobject_cast<QHttpNetworkConnection*>(connection))
814 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
815}
816
818{
820 if (reply)
821 resendCurrent = true;
822 if (qobject_cast<QHttpNetworkConnection*>(connection))
823 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
824}
825
827{
828 return (state & QHttpNetworkConnectionChannel::BusyState);
829}
830
832{
833 return (state & QHttpNetworkConnectionChannel::WritingState);
834}
835
837{
838 return (state & QHttpNetworkConnectionChannel::WaitingState);
839}
840
842{
843 return (state & QHttpNetworkConnectionChannel::ReadingState);
844}
845
847{
848 if (!protocolHandler)
849 return nullptr;
850 const auto type = connection->connectionType();
851 if (type == QHttpNetworkConnection::ConnectionTypeHTTP2Direct
852 || (type == QHttpNetworkConnection::ConnectionTypeHTTP2 && switchedToHttp2)) {
853 return static_cast<QHttp2ProtocolHandler *>(protocolHandler.get());
854 }
855 return nullptr;
856}
857
858/*!
859 \internal
860 Returns \c true if the channel has no session to send on: it is closing, its HTTP/2
861 session is going away, or that session has been dropped and not yet re-established.
862 Every site that resolves this restarts the request queue, so callers can bail out.
863*/
865{
866 // A closing socket will emit disconnected(), which restarts the request queue.
867 if (QSocketAbstraction::socketState(socket) == QAbstractSocket::ClosingState)
868 return true;
869 if (auto *h2 = h2ProtocolHandler())
870 return h2->isGoingAway();
871 // HTTP1 protocol handler is created early and never un-set so we can do this short test to see
872 // if HTTP2 is currently un-set and needs to be re-created:
873 return !protocolHandler;
874}
875
876/*!
877 \internal
878 Drops a going-away HTTP/2 session so the channel can connect again. Returns \c true
879 if one was dropped, meaning the request queue should be restarted.
880*/
882{
883 // Only an HTTP/2 session is dropped here. The HTTP/1 handler is created once and never
884 // recreated, so dropping it would leave protocolHandler null for the next sendRequest().
885 if (auto *h2 = h2ProtocolHandler(); !h2 || !h2->isGoingAway())
886 return false;
887 // We can be called from within the handler's own call chain, so destroy it in a queued
888 // call rather than under its own stack frame. Moving from the unique_ptr already
889 // clears the pending-reconnect state.
890 QMetaObject::invokeMethod(this, [oldHandler = std::move(protocolHandler)]() mutable {
891 oldHandler.reset();
892 }, Qt::QueuedConnection);
893 return true;
894}
895
897{
898 Q_UNUSED(bytes);
899 if (ssl) {
900 // In the SSL case we want to send data from encryptedBytesWritten signal since that one
901 // is the one going down to the actual network, not only into some SSL buffer.
902 return;
903 }
904
905 // bytes have been written to the socket. write even more of them :)
908 // otherwise we do nothing
909}
910
912{
913 if (state == QHttpNetworkConnectionChannel::ClosingState) {
914 state = QHttpNetworkConnectionChannel::IdleState;
916 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
917 return;
918 }
919
920 // read the available data before closing (also done in _q_error for other codepaths)
921 if ((isSocketWaiting() || isSocketReading()) && socket->bytesAvailable()) {
922 if (reply) {
923 state = QHttpNetworkConnectionChannel::ReadingState;
924 _q_receiveReply();
925 }
926 } else if (reply && reply->contentLength() == -1 && !reply->d_func()->isChunked()) {
927 // There was no content-length header and it's not chunked encoding,
928 // so this is a valid way to have the connection closed by the server
929 _q_receiveReply();
930 } else if (state == QHttpNetworkConnectionChannel::IdleState && resendCurrent) {
931 // re-sending request because the socket was in ClosingState
932 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
933 }
934 state = QHttpNetworkConnectionChannel::IdleState;
935 if (alreadyPipelinedRequests.size()) {
936 // If nothing was in a pipeline, no need in calling
937 // _q_startNextRequest (which it does):
939 }
940
941 // A going-away connection closed without us calling close(), so it was not handled by
942 // the ClosingState branch above. Done last, so the reads above still have the handler.
943 if (clearPendingReconnect())
944 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
945
946 pendingEncrypt = false;
947}
948
949
951{
952 // For the Happy Eyeballs we need to check if this is the first channel to connect.
953 if (connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::HostLookupPending || connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::IPv4or6) {
954 if (connection->d_func()->delayedConnectionTimer.isActive())
955 connection->d_func()->delayedConnectionTimer.stop();
956 if (networkLayerPreference == QAbstractSocket::IPv4Protocol)
957 connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv4;
958 else if (networkLayerPreference == QAbstractSocket::IPv6Protocol)
959 connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv6;
960 else {
961 if (absSocket->peerAddress().protocol() == QAbstractSocket::IPv4Protocol)
962 connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv4;
963 else
964 connection->d_func()->networkLayerState = QHttpNetworkConnectionPrivate::IPv6;
965 }
966 connection->d_func()->networkLayerDetected(networkLayerPreference);
967 if (connection->d_func()->activeChannelCount > 1 && !connection->d_func()->encrypt)
968 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
969 } else {
970 bool anyProtocol = networkLayerPreference == QAbstractSocket::AnyIPProtocol;
971 if (((connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::IPv4)
972 && (networkLayerPreference != QAbstractSocket::IPv4Protocol && !anyProtocol))
973 || ((connection->d_func()->networkLayerState == QHttpNetworkConnectionPrivate::IPv6)
974 && (networkLayerPreference != QAbstractSocket::IPv6Protocol && !anyProtocol))) {
975 close();
976 // This is the second connection so it has to be closed and we can schedule it for another request.
977 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
978 return;
979 }
980 //The connections networkLayerState had already been decided.
981 }
982
983 // improve performance since we get the request sent by the kernel ASAP
984 //absSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
985 // We have this commented out now. It did not have the effect we wanted. If we want to
986 // do this properly, Qt has to combine multiple HTTP requests into one buffer
987 // and send this to the kernel in one syscall and then the kernel immediately sends
988 // it as one TCP packet because of TCP_NODELAY.
989 // However, this code is currently not in Qt, so we rely on the kernel combining
990 // the requests into one TCP packet.
991
992 // not sure yet if it helps, but it makes sense
993 absSocket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
994
995 QTcpKeepAliveConfiguration keepAliveConfig = connection->tcpKeepAliveParameters();
996
997 auto getKeepAliveValue = [](int configValue,
998 const char* envName,
999 int defaultValue) {
1000 if (configValue > 0)
1001 return configValue;
1002 return static_cast<int>(qEnvironmentVariableIntegerValue(envName).value_or(defaultValue));
1003 };
1004
1005 int kaIdleOption = getKeepAliveValue(keepAliveConfig.idleTimeBeforeProbes.count(), keepAliveIdleOption, TCP_KEEPIDLE_DEF);
1006 int kaIntervalOption = getKeepAliveValue(keepAliveConfig.intervalBetweenProbes.count(), keepAliveIntervalOption, TCP_KEEPINTVL_DEF);
1007 int kaCountOption = getKeepAliveValue(keepAliveConfig.probeCount, keepAliveCountOption, TCP_KEEPCNT_DEF);
1008 absSocket->setSocketOption(QAbstractSocket::KeepAliveIdleOption, kaIdleOption);
1009 absSocket->setSocketOption(QAbstractSocket::KeepAliveIntervalOption, kaIntervalOption);
1010 absSocket->setSocketOption(QAbstractSocket::KeepAliveCountOption, kaCountOption);
1011
1013
1014 // ### FIXME: if the server closes the connection unexpectedly, we shouldn't send the same broken request again!
1015 //channels[i].reconnectAttempts = 2;
1016 if (ssl || pendingEncrypt) { // FIXME: Didn't work properly with pendingEncrypt only, we should refactor this into an EncrypingState
1017#ifndef QT_NO_SSL
1018 if (!connection->sslContext()) {
1019 // this socket is making the 1st handshake for this connection,
1020 // we need to set the SSL context so new sockets can reuse it
1021 if (auto socketSslContext = QSslSocketPrivate::sslContext(static_cast<QSslSocket*>(absSocket)))
1022 connection->setSslContext(std::move(socketSslContext));
1023 }
1024#endif
1025 } else if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
1026 state = QHttpNetworkConnectionChannel::IdleState;
1027 protocolHandler.reset(new QHttp2ProtocolHandler(this));
1028 if (h2RequestsToSend.size() > 0) {
1029 // In case our peer has sent us its settings (window size, max concurrent streams etc.)
1030 // let's give _q_receiveReply a chance to read them first ('invokeMethod', QueuedConnection).
1031 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
1032 }
1033 } else {
1034 state = QHttpNetworkConnectionChannel::IdleState;
1035 const bool tryProtocolUpgrade = connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2;
1036 if (tryProtocolUpgrade) {
1037 // For HTTP/1.1 it's already created and never reset.
1038 protocolHandler.reset(new QHttpProtocolHandler(this));
1039 }
1040 switchedToHttp2 = false;
1041
1042 if (!reply)
1043 connection->d_func()->dequeueRequest(absSocket);
1044
1045 if (reply) {
1046 if (tryProtocolUpgrade) {
1047 // Let's augment our request with some magic headers and try to
1048 // switch to HTTP/2.
1049 Http2::appendProtocolUpgradeHeaders(connection->http2Parameters(), &request);
1050 }
1052 }
1053 }
1054}
1055
1056#if QT_CONFIG(localserver)
1057void QHttpNetworkConnectionChannel::_q_connected_local_socket(QLocalSocket *localSocket)
1058{
1059 state = QHttpNetworkConnectionChannel::IdleState;
1060 if (!reply) // No reply object, try to dequeue a request (which is paired with a reply):
1061 connection->d_func()->dequeueRequest(localSocket);
1062 if (reply)
1063 sendRequest();
1064}
1065#endif
1066
1068{
1069 if (auto *s = qobject_cast<QAbstractSocket *>(socket))
1070 _q_connected_abstract_socket(s);
1071#if QT_CONFIG(localserver)
1072 else if (auto *s = qobject_cast<QLocalSocket *>(socket))
1073 _q_connected_local_socket(s);
1074#endif
1075}
1076
1077void QHttpNetworkConnectionChannel::_q_error(QAbstractSocket::SocketError socketError)
1078{
1079 if (!socket)
1080 return;
1081 QNetworkReply::NetworkError errorCode = QNetworkReply::UnknownNetworkError;
1082
1083 switch (socketError) {
1084 case QAbstractSocket::HostNotFoundError:
1085 errorCode = QNetworkReply::HostNotFoundError;
1086 break;
1087 case QAbstractSocket::ConnectionRefusedError:
1088 errorCode = QNetworkReply::ConnectionRefusedError;
1089#ifndef QT_NO_NETWORKPROXY
1090 if (connection->d_func()->networkProxy.type() != QNetworkProxy::NoProxy && !ssl)
1091 errorCode = QNetworkReply::ProxyConnectionRefusedError;
1092#endif
1093 break;
1094 case QAbstractSocket::RemoteHostClosedError:
1095 // This error for SSL comes twice in a row, first from SSL layer ("The TLS/SSL connection has been closed") then from TCP layer.
1096 // Depending on timing it can also come three times in a row (first time when we try to write into a closing QSslSocket).
1097 // The reconnectAttempts handling catches the cases where we can re-send the request.
1098 if (!reply && state == QHttpNetworkConnectionChannel::IdleState) {
1099 // Not actually an error, it is normal for Keep-Alive connections to close after some time if no request
1100 // is sent on them. No need to error the other replies below. Just bail out here.
1101 // The _q_disconnected will handle the possibly pipelined replies. HTTP/2 is special for now,
1102 // we do not resend, but must report errors if any request is in progress (note, while
1103 // not in its sendRequest(), protocol handler switches the channel to IdleState, thus
1104 // this check is under this condition in 'if'):
1105 if (auto *h2Handler = h2ProtocolHandler())
1106 h2Handler->handleConnectionClosure();
1107 return;
1108 } else if (state != QHttpNetworkConnectionChannel::IdleState && state != QHttpNetworkConnectionChannel::ReadingState) {
1109 // Try to reconnect/resend before sending an error.
1110 // While "Reading" the _q_disconnected() will handle this.
1111 // If we're using ssl then the protocolHandler is not initialized until
1112 // "encrypted" has been emitted, since retrying requires the protocolHandler (asserted)
1113 // we will not try if encryption is not done.
1114 if (!pendingEncrypt && reconnectAttempts-- > 0) {
1116 return;
1117 } else {
1118 errorCode = QNetworkReply::RemoteHostClosedError;
1119 }
1120 } else if (state == QHttpNetworkConnectionChannel::ReadingState) {
1121 if (!reply)
1122 break;
1123
1124 if (!reply->d_func()->expectContent()) {
1125 // No content expected, this is a valid way to have the connection closed by the server
1126 // We need to invoke this asynchronously to make sure the state() of the socket is on QAbstractSocket::UnconnectedState
1127 QMetaObject::invokeMethod(this, "_q_receiveReply", Qt::QueuedConnection);
1128 return;
1129 }
1130 if (reply->contentLength() == -1 && !reply->d_func()->isChunked()) {
1131 // There was no content-length header and it's not chunked encoding,
1132 // so this is a valid way to have the connection closed by the server
1133 // We need to invoke this asynchronously to make sure the state() of the socket is on QAbstractSocket::UnconnectedState
1134 QMetaObject::invokeMethod(this, "_q_receiveReply", Qt::QueuedConnection);
1135 return;
1136 }
1137 // ok, we got a disconnect even though we did not expect it
1138 // Try to read everything from the socket before we emit the error.
1139 if (socket->bytesAvailable()) {
1140 // Read everything from the socket into the reply buffer.
1141 // we can ignore the readbuffersize as the data is already
1142 // in memory and we will not receive more data on the socket.
1143 reply->setReadBufferSize(0);
1144 reply->setDownstreamLimited(false);
1145 _q_receiveReply();
1146 if (!reply) {
1147 // No more reply assigned after the previous call? Then it had been finished successfully.
1149 state = QHttpNetworkConnectionChannel::IdleState;
1150 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
1151 return;
1152 }
1153 }
1154
1155 errorCode = QNetworkReply::RemoteHostClosedError;
1156 } else {
1157 errorCode = QNetworkReply::RemoteHostClosedError;
1158 }
1159 break;
1160 case QAbstractSocket::SocketTimeoutError:
1161 // try to reconnect/resend before sending an error.
1162 if (state == QHttpNetworkConnectionChannel::WritingState && (reconnectAttempts-- > 0)) {
1164 return;
1165 }
1166 errorCode = QNetworkReply::TimeoutError;
1167 break;
1168 case QAbstractSocket::ProxyConnectionRefusedError:
1169 errorCode = QNetworkReply::ProxyConnectionRefusedError;
1170 break;
1171 case QAbstractSocket::ProxyAuthenticationRequiredError:
1172 errorCode = QNetworkReply::ProxyAuthenticationRequiredError;
1173 break;
1174 case QAbstractSocket::SslHandshakeFailedError:
1175 errorCode = QNetworkReply::SslHandshakeFailedError;
1176 break;
1177 case QAbstractSocket::ProxyConnectionClosedError:
1178 // try to reconnect/resend before sending an error.
1179 if (reconnectAttempts-- > 0) {
1181 return;
1182 }
1183 errorCode = QNetworkReply::ProxyConnectionClosedError;
1184 break;
1185 case QAbstractSocket::ProxyConnectionTimeoutError:
1186 // try to reconnect/resend before sending an error.
1187 if (reconnectAttempts-- > 0) {
1189 return;
1190 }
1191 errorCode = QNetworkReply::ProxyTimeoutError;
1192 break;
1193 default:
1194 // all other errors are treated as NetworkError
1195 errorCode = QNetworkReply::UnknownNetworkError;
1196 break;
1197 }
1198 QPointer<QHttpNetworkConnection> that = connection;
1199 QString errorString = connection->d_func()->errorDetail(errorCode, socket, socket->errorString());
1200
1201 // In the HostLookupPending state the channel should not emit the error.
1202 // This will instead be handled by the connection.
1203 if (!connection->d_func()->shouldEmitChannelError(socket))
1204 return;
1205
1206 // emit error for all waiting replies
1207 do {
1208 // First requeue the already pipelined requests for the current failed reply,
1209 // then dequeue pending requests so we can also mark them as finished with error
1210 if (reply)
1212 else
1213 connection->d_func()->dequeueRequest(socket);
1214
1215 if (reply) {
1216 reply->d_func()->setError(errorCode, errorString);
1217 emit reply->finishedWithError(errorCode, errorString);
1218 reply = nullptr;
1219 if (protocolHandler)
1220 protocolHandler->setReply(nullptr);
1221 }
1222 } while (!connection->d_func()->highPriorityQueue.isEmpty()
1223 || !connection->d_func()->lowPriorityQueue.isEmpty());
1224
1225 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
1226 || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
1227 const auto h2RequestsToSendCopy = std::exchange(h2RequestsToSend, {});
1228 for (const auto &httpMessagePair : h2RequestsToSendCopy) {
1229 // emit error for all replies
1230 QHttpNetworkReply *currentReply = httpMessagePair.second;
1231 currentReply->d_func()->setError(errorCode, errorString);
1232 Q_ASSERT(currentReply);
1233 emit currentReply->finishedWithError(errorCode, errorString);
1234 }
1235 }
1236
1237 // send the next request
1238 QMetaObject::invokeMethod(that, "_q_startNextRequest", Qt::QueuedConnection);
1239
1240 if (that) {
1241 //signal emission triggered event loop
1242 if (!socket)
1243 state = QHttpNetworkConnectionChannel::IdleState;
1244 else if (QSocketAbstraction::socketState(socket) == QAbstractSocket::UnconnectedState)
1245 state = QHttpNetworkConnectionChannel::IdleState;
1246 else
1247 state = QHttpNetworkConnectionChannel::ClosingState;
1248
1249 // pendingEncrypt must only be true in between connected and encrypted states
1250 pendingEncrypt = false;
1251 }
1252}
1253
1254#ifndef QT_NO_NETWORKPROXY
1255void QHttpNetworkConnectionChannel::_q_proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator* auth)
1256{
1257 if ((connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
1258 && (switchedToHttp2 || h2RequestsToSend.size() > 0))
1259 || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
1260 if (h2RequestsToSend.size() > 0)
1261 connection->d_func()->emitProxyAuthenticationRequired(this, proxy, auth);
1262 } else { // HTTP
1263 // Need to dequeue the request before we can emit the error.
1264 if (!reply)
1265 connection->d_func()->dequeueRequest(socket);
1266 if (reply)
1267 connection->d_func()->emitProxyAuthenticationRequired(this, proxy, auth);
1268 }
1269}
1270#endif
1271
1277
1278void QHttpNetworkConnectionChannel::emitFinishedWithError(QNetworkReply::NetworkError error,
1279 const char *message)
1280{
1281 emitFinishedWithError(error, QHttpNetworkConnectionChannel::tr(message));
1282}
1283
1284void QHttpNetworkConnectionChannel::emitFinishedWithError(QNetworkReply::NetworkError error,
1285 const QString &message)
1286{
1287 if (reply) {
1288 reply->d_func()->setError(error, message);
1289 emit reply->finishedWithError(error, message);
1290 }
1291 const auto h2RequestsToSendCopy = h2RequestsToSend;
1292 for (const auto &httpMessagePair : h2RequestsToSendCopy) {
1293 QHttpNetworkReply *currentReply = httpMessagePair.second;
1294 Q_ASSERT(currentReply);
1295 currentReply->d_func()->setError(error, message);
1296 emit currentReply->finishedWithError(error, message);
1297 }
1298}
1299
1300#ifndef QT_NO_SSL
1302{
1303 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
1304 Q_ASSERT(sslSocket);
1305
1306 if (!protocolHandler && connection->connectionType() != QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
1307 // ConnectionTypeHTTP2Direct does not rely on ALPN/NPN to negotiate HTTP/2,
1308 // after establishing a secure connection we immediately start sending
1309 // HTTP/2 frames.
1310 switch (sslSocket->sslConfiguration().nextProtocolNegotiationStatus()) {
1311 case QSslConfiguration::NextProtocolNegotiationNegotiated: {
1312 QByteArray nextProtocol = sslSocket->sslConfiguration().nextNegotiatedProtocol();
1313 if (nextProtocol == QSslConfiguration::NextProtocolHttp1_1) {
1314 // fall through to create a QHttpProtocolHandler
1315 } else if (nextProtocol == QSslConfiguration::ALPNProtocolHTTP2) {
1316 switchedToHttp2 = true;
1317 protocolHandler.reset(new QHttp2ProtocolHandler(this));
1318 connection->setConnectionType(QHttpNetworkConnection::ConnectionTypeHTTP2);
1319 break;
1320 } else {
1321 emitFinishedWithError(QNetworkReply::SslHandshakeFailedError,
1322 "detected unknown Next Protocol Negotiation protocol");
1323 break;
1324 }
1325 }
1326 Q_FALLTHROUGH();
1327 case QSslConfiguration::NextProtocolNegotiationUnsupported: // No agreement, try HTTP/1(.1)
1328 case QSslConfiguration::NextProtocolNegotiationNone: {
1329 protocolHandler.reset(new QHttpProtocolHandler(this));
1330
1331 QSslConfiguration newConfiguration = sslSocket->sslConfiguration();
1332 QList<QByteArray> protocols = newConfiguration.allowedNextProtocols();
1333 const int nProtocols = protocols.size();
1334 // Clear the protocol that we failed to negotiate, so we do not try
1335 // it again on other channels that our connection can create/open.
1336 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2)
1337 protocols.removeAll(QSslConfiguration::ALPNProtocolHTTP2);
1338
1339 if (nProtocols > protocols.size()) {
1340 newConfiguration.setAllowedNextProtocols(protocols);
1341 const int channelCount = connection->d_func()->channelCount;
1342 for (int i = 0; i < channelCount; ++i)
1343 connection->d_func()->channels[i].setSslConfiguration(newConfiguration);
1344 }
1345
1346 connection->setConnectionType(QHttpNetworkConnection::ConnectionTypeHTTP);
1347 // We use only one channel for HTTP/2, but normally six for
1348 // HTTP/1.1 - let's restore this number to the reserved number of
1349 // channels:
1350 if (connection->d_func()->activeChannelCount < connection->d_func()->channelCount) {
1351 connection->d_func()->activeChannelCount = connection->d_func()->channelCount;
1352 // re-queue requests from HTTP/2 queue to HTTP queue, if any
1354 }
1355 break;
1356 }
1357 default:
1358 emitFinishedWithError(QNetworkReply::SslHandshakeFailedError,
1359 "detected unknown Next Protocol Negotiation protocol");
1360 }
1361 } else if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
1362 || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
1363 // We have to reset QHttp2ProtocolHandler's state machine, it's a new
1364 // connection and the handler's state is unique per connection.
1365 protocolHandler.reset(new QHttp2ProtocolHandler(this));
1366 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2)
1367 switchedToHttp2 = true;
1368 }
1369
1370 if (!socket)
1371 return; // ### error
1372 state = QHttpNetworkConnectionChannel::IdleState;
1373 pendingEncrypt = false;
1374
1375 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2 ||
1376 connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct) {
1377 if (!h2RequestsToSend.isEmpty()) {
1378 // Similar to HTTP/1.1 counterpart below:
1379 const auto &pair = std::as_const(h2RequestsToSend).first();
1381 emit pair.second->encrypted();
1382
1383 // We don't send or handle any received data until any effects from
1384 // emitting encrypted() have been processed. This is necessary
1385 // because the user may have called abort(). We may also abort the
1386 // whole connection if the request has been aborted and there is
1387 // no more requests to send.
1388 QMetaObject::invokeMethod(this,
1389 &QHttpNetworkConnectionChannel::checkAndResumeCommunication,
1390 Qt::QueuedConnection);
1391
1392 // In case our peer has sent us its settings (window size, max concurrent streams etc.)
1393 // let's give _q_receiveReply a chance to read them first ('invokeMethod', QueuedConnection).
1394 }
1395 } else { // HTTP
1396 if (!reply)
1397 connection->d_func()->dequeueRequest(socket);
1398 if (reply) {
1399 reply->setHttp2WasUsed(false);
1400 Q_ASSERT(reply->d_func()->connectionChannel == this);
1401 emit reply->encrypted();
1402 }
1403 if (reply)
1405 }
1406 QMetaObject::invokeMethod(connection, "_q_startNextRequest", Qt::QueuedConnection);
1407}
1408
1409
1411{
1412 Q_ASSERT(connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2
1413 || connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP2Direct);
1414
1415 // Because HTTP/2 requires that we send a SETTINGS frame as the first thing we do, and respond
1416 // to a SETTINGS frame with an ACK, we need to delay any handling until we can ensure that any
1417 // effects from emitting encrypted() have been processed.
1418 // This function is called after encrypted() was emitted, so check for changes.
1419
1420 if (!reply && h2RequestsToSend.isEmpty())
1421 abort();
1425 if (needInvokeReceiveReply)
1426 _q_receiveReply();
1429}
1430
1432{
1433 const auto h2RequestsToSendCopy = std::exchange(h2RequestsToSend, {});
1434 for (const auto &httpMessagePair : h2RequestsToSendCopy)
1435 connection->d_func()->requeueRequest(httpMessagePair);
1436}
1437
1438void QHttpNetworkConnectionChannel::_q_sslErrors(const QList<QSslError> &errors)
1439{
1440 if (!socket)
1441 return;
1442 //QNetworkReply::NetworkError errorCode = QNetworkReply::ProtocolFailure;
1443 // Also pause the connection because socket notifiers may fire while an user
1444 // dialog is displaying
1445 connection->d_func()->pauseConnection();
1446 if (pendingEncrypt && !reply)
1447 connection->d_func()->dequeueRequest(socket);
1448 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP) {
1449 if (reply)
1450 emit reply->sslErrors(errors);
1451 }
1452#ifndef QT_NO_SSL
1453 else { // HTTP/2
1454 const auto h2RequestsToSendCopy = h2RequestsToSend;
1455 for (const auto &httpMessagePair : h2RequestsToSendCopy) {
1456 // emit SSL errors for all replies
1457 QHttpNetworkReply *currentReply = httpMessagePair.second;
1458 Q_ASSERT(currentReply);
1459 emit currentReply->sslErrors(errors);
1460 }
1461 }
1462#endif // QT_NO_SSL
1463 connection->d_func()->resumeConnection();
1464}
1465
1466void QHttpNetworkConnectionChannel::_q_preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *authenticator)
1467{
1468 connection->d_func()->pauseConnection();
1469
1470 if (pendingEncrypt && !reply)
1471 connection->d_func()->dequeueRequest(socket);
1472
1473 if (connection->connectionType() == QHttpNetworkConnection::ConnectionTypeHTTP) {
1474 if (reply)
1475 emit reply->preSharedKeyAuthenticationRequired(authenticator);
1476 } else {
1477 const auto h2RequestsToSendCopy = h2RequestsToSend;
1478 for (const auto &httpMessagePair : h2RequestsToSendCopy) {
1479 // emit SSL errors for all replies
1480 QHttpNetworkReply *currentReply = httpMessagePair.second;
1481 Q_ASSERT(currentReply);
1482 emit currentReply->preSharedKeyAuthenticationRequired(authenticator);
1483 }
1484 }
1485
1486 connection->d_func()->resumeConnection();
1487}
1488
1490{
1491 Q_UNUSED(bytes);
1492 // bytes have been written to the socket. write even more of them :)
1495 // otherwise we do nothing
1496}
1497
1498#endif
1499
1500void QHttpNetworkConnectionChannel::setConnection(QHttpNetworkConnection *c)
1501{
1502 // Inlining this function in the header leads to compiler error on
1503 // release-armv5, on at least timebox 9.2 and 10.1.
1504 connection = c;
1505}
1506
1507QT_END_NAMESPACE
1508
1509#include "moc_qhttpnetworkconnectionchannel_p.cpp"
void emitFinishedWithError(QNetworkReply::NetworkError error, const QString &message)
void setProxy(const QNetworkProxy &networkProxy)
void _q_preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator *)
void emitFinishedWithError(QNetworkReply::NetworkError error, const char *message)
void _q_sslErrors(const QList< QSslError > &errors)
void _q_connected_abstract_socket(QAbstractSocket *socket)
void ignoreSslErrors(const QList< QSslError > &errors)
void _q_error(QAbstractSocket::SocketError)
void _q_proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *auth)
QHttp2ProtocolHandler * h2ProtocolHandler() const noexcept
The QNetworkProxy class provides a network layer proxy.
Combined button and popup list for selecting options.
static const char keepAliveCountOption[]
static const int TCP_KEEPIDLE_DEF
static const int TCP_KEEPINTVL_DEF
static QT_BEGIN_NAMESPACE const int reconnectAttemptsDefault
static const int TCP_KEEPCNT_DEF
static const char keepAliveIntervalOption[]
static const char keepAliveIdleOption[]
std::pair< QHttpNetworkRequest, QHttpNetworkReply * > HttpMessagePair