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
qnetworkreplyhttpimpl.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//#define QNETWORKACCESSHTTPBACKEND_DEBUG
6
12#include "qnetworkreply.h"
14#include "qnetworkcookie.h"
16#include "QtCore/qdatetime.h"
17#include "QtCore/qelapsedtimer.h"
18#include "QtNetwork/qsslconfiguration.h"
20#include "qhsts_p.h"
21#include "qthread.h"
22#include "QtCore/qcoreapplication.h"
23
24#include <QtCore/private/qthread_p.h>
25#include <QtCore/private/qtools_p.h>
26
28
30
31#include <string.h> // for strchr
32
33QT_BEGIN_NAMESPACE
34
35using namespace Qt::StringLiterals;
36using namespace QtMiscUtils;
37using namespace std::chrono_literals;
38
39class QNetworkProxy;
40
41static inline QByteArray rangeName() { return "Range"_ba; }
42static inline QByteArray cacheControlName() { return "Cache-Control"_ba; }
43static constexpr QByteArrayView bytesEqualPrefix() noexcept { return "bytes="; }
44
45// ### merge with nextField in cookiejar.cpp
46static QHash<QByteArray, QByteArray> parseHttpOptionHeader(QByteArrayView header)
47{
48 // The HTTP header is of the form:
49 // header = #1(directives)
50 // directives = token | value-directive
51 // value-directive = token "=" (token | quoted-string)
52 QHash<QByteArray, QByteArray> result;
53
54 qsizetype pos = 0;
55 while (true) {
56 // skip spaces
57 pos = nextNonWhitespace(header, pos);
58 if (pos == header.size())
59 return result; // end of parsing
60
61 // pos points to a non-whitespace
62 const qsizetype comma = header.indexOf(',', pos);
63 const qsizetype equal = header.indexOf('=', pos);
64 if (comma == pos || equal == pos)
65 // huh? Broken header.
66 return result;
67
68 // The key name is delimited by either a comma, an equal sign or the end
69 // of the header, whichever comes first
70 qsizetype end = comma;
71 if (end == -1)
72 end = header.size();
73 if (equal != -1 && end > equal)
74 end = equal; // equal sign comes before comma/end
75 const auto key = header.sliced(pos, end - pos).trimmed();
76 pos = end + 1;
77
78 if (size_t(equal) < size_t(comma)) {
79 // case: token "=" (token | quoted-string)
80 // skip spaces
81 pos = nextNonWhitespace(header, pos);
82 if (pos == header.size())
83 // huh? Broken header
84 return result;
85
86 QByteArray value;
87 value.reserve(header.size() - pos);
88 if (header.at(pos) == '"') {
89 // case: quoted-string
90 // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
91 // qdtext = <any TEXT except <">>
92 // quoted-pair = "\" CHAR
93 ++pos;
94 while (pos < header.size()) {
95 char c = header.at(pos);
96 if (c == '"') {
97 // end of quoted text
98 break;
99 } else if (c == '\\') {
100 ++pos;
101 if (pos >= header.size())
102 // broken header
103 return result;
104 c = header.at(pos);
105 }
106
107 value += c;
108 ++pos;
109 }
110 } else {
111 const auto isSeparator = [](char c) {
112 static const char separators[] = "()<>@,;:\\\"/[]?={}";
113 return isLWS(c) || strchr(separators, c) != nullptr;
114 };
115
116 // case: token
117 while (pos < header.size()) {
118 char c = header.at(pos);
119 if (isSeparator(c))
120 break;
121 value += c;
122 ++pos;
123 }
124 }
125
126 result.insert(key.toByteArray().toLower(), value);
127
128 // find the comma now:
129 if (qsizetype comma = header.indexOf(',', pos); comma == -1)
130 return result; // end of parsing
131 else
132 pos = comma + 1;
133 } else {
134 // case: token
135 // key is already set
136 result.insert(key.toByteArray().toLower(), QByteArray());
137 }
138 }
139}
140
141// If the user specified CustomOperation we try to remap the operation to a known
142// operation. This is useful because we treat the operations differently,
143// ie for caching or redirection
144static auto remapCustom(QNetworkAccessManager::Operation operation, const QNetworkRequest &req)
145{
146 if (operation == QNetworkAccessManager::CustomOperation) {
147 const QByteArray customVerb = req.attribute(QNetworkRequest::CustomVerbAttribute)
148 .toByteArray();
149 if (customVerb.compare("get", Qt::CaseInsensitive) == 0)
150 return QNetworkAccessManager::GetOperation;
151 if (customVerb.compare("head", Qt::CaseInsensitive) == 0)
152 return QNetworkAccessManager::HeadOperation;
153 if (customVerb.compare("delete", Qt::CaseInsensitive) == 0)
154 return QNetworkAccessManager::DeleteOperation;
155 if (customVerb.compare("put", Qt::CaseInsensitive) == 0)
156 return QNetworkAccessManager::PutOperation;
157 if (customVerb.compare("post", Qt::CaseInsensitive) == 0)
158 return QNetworkAccessManager::PostOperation;
159 }
160 return operation;
161}
162
163QNetworkReplyHttpImpl::QNetworkReplyHttpImpl(QNetworkAccessManager* const manager,
164 const QNetworkRequest& request,
165 QNetworkAccessManager::Operation& operation,
166 QIODevice* outgoingData)
167 : QNetworkReply(*new QNetworkReplyHttpImplPrivate, manager)
168{
169 Q_D(QNetworkReplyHttpImpl);
170 Q_ASSERT(manager);
171 d->manager = manager;
172 d->managerPrivate = manager->d_func();
173 d->request = request;
174 d->originalRequest = request;
175 d->operation = remapCustom(operation, request);
176 d->outgoingData = outgoingData;
177 d->url = request.url();
178#ifndef QT_NO_SSL
179 if (request.url().scheme() == "https"_L1)
180 d->sslConfiguration.reset(new QSslConfiguration(request.sslConfiguration()));
181#endif
182
183 QObjectPrivate::connect(this, &QNetworkReplyHttpImpl::redirectAllowed, d,
184 &QNetworkReplyHttpImplPrivate::followRedirect, Qt::QueuedConnection);
185
186 // FIXME Later maybe set to Unbuffered, especially if it is zerocopy or from cache?
187 QIODevice::open(QIODevice::ReadOnly);
188
189
190 // Internal code that does a HTTP reply for the synchronous Ajax
191 // in Qt WebKit.
192 QVariant synchronousHttpAttribute = request.attribute(
193 static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute));
194 if (synchronousHttpAttribute.isValid()) {
195 d->synchronous = synchronousHttpAttribute.toBool();
196 if (d->synchronous && outgoingData) {
197 // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
198 // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
199 d->outgoingDataBuffer = std::make_shared<QRingBuffer>();
200 qint64 previousDataSize = 0;
201 do {
202 previousDataSize = d->outgoingDataBuffer->size();
203 d->outgoingDataBuffer->append(d->outgoingData->readAll());
204 } while (d->outgoingDataBuffer->size() != previousDataSize);
205 d->_q_startOperation();
206 return;
207 }
208 }
209
210
211 if (outgoingData) {
212 // there is data to be uploaded, e.g. HTTP POST.
213
214 if (!d->outgoingData->isSequential()) {
215 // fixed size non-sequential (random-access)
216 // just start the operation
217 QMetaObject::invokeMethod(this, "_q_startOperation", Qt::QueuedConnection);
218 // FIXME make direct call?
219 } else {
220 bool bufferingDisallowed =
221 request.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
222 false).toBool();
223
224 if (bufferingDisallowed) {
225 // if a valid content-length header for the request was supplied, we can disable buffering
226 // if not, we will buffer anyway
227
228 const auto sizeOpt = QNetworkHeadersPrivate::toInt(
229 request.headers().value(QHttpHeaders::WellKnownHeader::ContentLength));
230 if (sizeOpt) {
231 QMetaObject::invokeMethod(this, "_q_startOperation", Qt::QueuedConnection);
232 // FIXME make direct call?
233 } else {
234 d->state = d->Buffering;
235 QMetaObject::invokeMethod(this, "_q_bufferOutgoingData", Qt::QueuedConnection);
236 }
237 } else {
238 // _q_startOperation will be called when the buffering has finished.
239 d->state = d->Buffering;
240 QMetaObject::invokeMethod(this, "_q_bufferOutgoingData", Qt::QueuedConnection);
241 }
242 }
243 } else {
244 // No outgoing data (POST, ..)
245 d->_q_startOperation();
246 }
247}
248
250{
251 // This will do nothing if the request was already finished or aborted
252 emit abortHttpRequest();
253}
254
256{
257 Q_D(QNetworkReplyHttpImpl);
258
259 if (d->state == QNetworkReplyPrivate::Aborted ||
260 d->state == QNetworkReplyPrivate::Finished)
261 return;
262
263 // According to the documentation close only stops the download
264 // by closing we can ignore the download part and continue uploading.
265 QNetworkReply::close();
266
267 // call finished which will emit signals
268 // FIXME shouldn't this be emitted Queued?
269 d->error(OperationCanceledError, tr("Operation canceled"));
270 d->finished();
271}
272
274{
275 abortImpl(QNetworkReply::OperationCanceledError);
276}
277
278void QNetworkReplyHttpImpl::abortImpl(QNetworkReply::NetworkError error)
279{
280 Q_D(QNetworkReplyHttpImpl);
281 // FIXME
282 if (d->state == QNetworkReplyPrivate::Finished || d->state == QNetworkReplyPrivate::Aborted)
283 return;
284
285 QNetworkReply::close();
286
287 if (d->state != QNetworkReplyPrivate::Finished) {
288 // call finished which will emit signals
289 // FIXME shouldn't this be emitted Queued?
290 d->error(error,
291 error == TimeoutError ? tr("Operation timed out") : tr("Operation canceled"));
292 d->finished();
293 }
294
295 d->state = QNetworkReplyPrivate::Aborted;
296
297 emit abortHttpRequest();
298}
299
301{
302 Q_D(const QNetworkReplyHttpImpl);
303
304 // if we load from cache device
305 if (d->cacheLoadDevice) {
306 return QNetworkReply::bytesAvailable() + d->cacheLoadDevice->bytesAvailable();
307 }
308
309 // zerocopy buffer
310 if (d->downloadZerocopyBuffer) {
311 return QNetworkReply::bytesAvailable() + d->downloadBufferCurrentSize - d->downloadBufferReadPosition;
312 }
313
314 if (d->decompressHelper.isValid()) {
315 if (d->decompressHelper.isCountingBytes())
316 return QNetworkReply::bytesAvailable() + d->decompressHelper.uncompressedSize();
317 if (d->decompressHelper.hasData())
318 return QNetworkReply::bytesAvailable() + 1;
319 }
320
321 // normal buffer
322 return QNetworkReply::bytesAvailable();
323}
324
326{
327 // FIXME In the cache of a cached load or the zero-copy buffer we could actually be non-sequential.
328 // FIXME however this requires us to implement stuff like seek() too.
329 return true;
330}
331
333{
334 // FIXME At some point, this could return a proper value, e.g. if we're non-sequential.
335 return QNetworkReply::size();
336}
337
338qint64 QNetworkReplyHttpImpl::readData(char* data, qint64 maxlen)
339{
340 Q_D(QNetworkReplyHttpImpl);
341
342 // cacheload device
343 if (d->cacheLoadDevice) {
344 // FIXME bytesdownloaded, position etc?
345
346 qint64 ret = d->cacheLoadDevice->read(data, maxlen);
347 return ret;
348 }
349
350 // zerocopy buffer
351 if (d->downloadZerocopyBuffer) {
352 // FIXME bytesdownloaded, position etc?
353
354 qint64 howMuch = qMin(maxlen, (d->downloadBufferCurrentSize - d->downloadBufferReadPosition));
355 memcpy(data, d->downloadZerocopyBuffer + d->downloadBufferReadPosition, howMuch);
356 d->downloadBufferReadPosition += howMuch;
357 return howMuch;
358
359 }
360
361 if (d->decompressHelper.isValid() && (d->decompressHelper.hasData() || !isFinished())) {
362 if (maxlen == 0 || !d->decompressHelper.hasData())
363 return 0;
364 const qint64 bytesRead = d->decompressHelper.read(data, maxlen);
365 if (!d->decompressHelper.isValid()) {
366 d->error(QNetworkReplyImpl::NetworkError::UnknownContentError,
367 QCoreApplication::translate("QHttp", "Decompression failed: %1")
368 .arg(d->decompressHelper.errorString()));
369 d->decompressHelper.clear();
370 return -1;
371 }
372 if (d->cacheSaveDevice) {
373 // Need to write to the cache now that we have the data
374 d->cacheSaveDevice->write(data, bytesRead);
375 // ... and if we've read everything then the cache can be closed.
376 if (isFinished() && !d->decompressHelper.hasData())
377 d->completeCacheSave();
378 }
379 // In case of buffer size restriction we need to emit that it has been emptied
380 qint64 wasBuffered = d->bytesBuffered;
381 d->bytesBuffered = 0;
382 if (readBufferSize())
383 emit readBufferFreed(wasBuffered);
384 return bytesRead;
385 }
386
387 // normal buffer
388 if (d->state == d->Finished || d->state == d->Aborted)
389 return -1;
390
391 qint64 wasBuffered = d->bytesBuffered;
392 d->bytesBuffered = 0;
393 if (readBufferSize())
394 emit readBufferFreed(wasBuffered);
395 return 0;
396}
397
399{
400 QNetworkReply::setReadBufferSize(size);
401 emit readBufferSizeChanged(size);
402 return;
403}
404
406{
407 Q_D(const QNetworkReplyHttpImpl);
408
409 if (QNetworkReply::canReadLine())
410 return true;
411
412 if (d->cacheLoadDevice)
413 return d->cacheLoadDevice->canReadLine();
414
415 if (d->downloadZerocopyBuffer)
416 return memchr(d->downloadZerocopyBuffer + d->downloadBufferReadPosition, '\n', d->downloadBufferCurrentSize - d->downloadBufferReadPosition);
417
418 return false;
419}
420
421#ifndef QT_NO_SSL
422void QNetworkReplyHttpImpl::ignoreSslErrors()
423{
424 Q_D(QNetworkReplyHttpImpl);
425 Q_ASSERT(d->managerPrivate);
426
427 if (d->managerPrivate->stsEnabled && d->managerPrivate->stsCache.isKnownHost(url())) {
428 // We cannot ignore any Security Transport-related errors for this host.
429 return;
430 }
431
432 d->pendingIgnoreAllSslErrors = true;
433}
434
435void QNetworkReplyHttpImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
436{
437 Q_D(QNetworkReplyHttpImpl);
438 Q_ASSERT(d->managerPrivate);
439
440 if (d->managerPrivate->stsEnabled && d->managerPrivate->stsCache.isKnownHost(url())) {
441 // We cannot ignore any Security Transport-related errors for this host.
442 return;
443 }
444
445 // the pending list is set if QNetworkReply::ignoreSslErrors(const QList<QSslError> &errors)
446 // is called before QNetworkAccessManager::get() (or post(), etc.)
447 d->pendingIgnoreSslErrorsList = errors;
448}
449
450void QNetworkReplyHttpImpl::setSslConfigurationImplementation(const QSslConfiguration &newconfig)
451{
452 // Setting a SSL configuration on a reply is not supported. The user needs to set
453 // her/his QSslConfiguration on the QNetworkRequest.
454 Q_UNUSED(newconfig);
455}
456
457void QNetworkReplyHttpImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
458{
459 Q_D(const QNetworkReplyHttpImpl);
460 if (d->sslConfiguration)
461 configuration = *d->sslConfiguration;
462 else
463 configuration = request().sslConfiguration();
464}
465#endif
466
469 , manager(nullptr)
470 , managerPrivate(nullptr)
471 , synchronous(false)
472 , state(Idle)
473 , statusCode(0)
475 , uploadDeviceChoking(false)
476 , outgoingData(nullptr)
477 , bytesUploaded(-1)
478 , cacheLoadDevice(nullptr)
479 , loadingFromCache(false)
480 , cacheSaveDevice(nullptr)
481 , cacheEnabled(false)
482 , resumeOffset(0)
483 , bytesDownloaded(0)
484 , bytesBuffered(0)
485 , transferTimeout(nullptr)
488 , downloadZerocopyBuffer(nullptr)
491 #ifndef QT_NO_SSL
493 #endif
494
495{
496}
497
499{
500 if (cacheSaveDevice)
501 managerPrivate->networkCache->remove(url);
502}
503
504/*
505 For a given httpRequest
506 1) If AlwaysNetwork, return
507 2) If we have a cache entry for this url populate headers so the server can return 304
508 3) Calculate if response_is_fresh and if so send the cache and set loadedFromCache to true
509 */
510bool QNetworkReplyHttpImplPrivate::loadFromCacheIfAllowed(QHttpNetworkRequest &httpRequest)
511{
512 QNetworkRequest::CacheLoadControl CacheLoadControlAttribute =
513 (QNetworkRequest::CacheLoadControl)request.attribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork).toInt();
514
515 auto requestHeaders = request.headers();
516 if (CacheLoadControlAttribute == QNetworkRequest::AlwaysNetwork) {
517 // If the request does not already specify preferred cache-control
518 // force reload from the network and tell any caching proxy servers to reload too
519 if (!requestHeaders.contains(QHttpHeaders::WellKnownHeader::CacheControl)) {
520 const auto noCache = "no-cache"_ba;
521 httpRequest.setHeaderField(cacheControlName(), noCache);
522 httpRequest.setHeaderField("Pragma"_ba, noCache);
523 }
524 return false;
525 }
526
527 // The disk cache API does not currently support partial content retrieval.
528 // That is why we don't use the disk cache for any such requests.
529 if (requestHeaders.contains(QHttpHeaders::WellKnownHeader::Range))
530 return false;
531
532 QAbstractNetworkCache *nc = managerPrivate->networkCache;
533 if (!nc)
534 return false; // no local cache
535
536 QNetworkCacheMetaData metaData = nc->metaData(httpRequest.url());
537 if (!metaData.isValid())
538 return false; // not in cache
539
540 if (!metaData.saveToDisk())
541 return false;
542
543 QHttpHeaders cacheHeaders = metaData.headers();
544
545 const auto sizeOpt = QNetworkHeadersPrivate::toInt(
546 cacheHeaders.value(QHttpHeaders::WellKnownHeader::ContentLength));
547 if (sizeOpt) {
548 std::unique_ptr<QIODevice> data(nc->data(httpRequest.url()));
549 if (!data || data->size() < sizeOpt.value())
550 return false; // The data is smaller than the content-length specified
551 }
552
553 auto value = cacheHeaders.value(QHttpHeaders::WellKnownHeader::ETag);
554 if (!value.empty())
555 httpRequest.setHeaderField("If-None-Match"_ba, value.toByteArray());
556
557 QDateTime lastModified = metaData.lastModified();
558 if (lastModified.isValid())
559 httpRequest.setHeaderField("If-Modified-Since"_ba, QNetworkHeadersPrivate::toHttpDate(lastModified));
560
561 value = cacheHeaders.value(QHttpHeaders::WellKnownHeader::CacheControl);
562 if (!value.empty()) {
563 QHash<QByteArray, QByteArray> cacheControl = parseHttpOptionHeader(value);
564 if (cacheControl.contains("no-cache"_ba))
565 return false;
566 }
567
568 QDateTime currentDateTime = QDateTime::currentDateTimeUtc();
569 QDateTime expirationDate = metaData.expirationDate();
570
571 bool response_is_fresh;
572 if (!expirationDate.isValid()) {
573 /*
574 * age_value
575 * is the value of Age: header received by the cache with
576 * this response.
577 * date_value
578 * is the value of the origin server's Date: header
579 * request_time
580 * is the (local) time when the cache made the request
581 * that resulted in this cached response
582 * response_time
583 * is the (local) time when the cache received the
584 * response
585 * now
586 * is the current (local) time
587 */
588 const auto ageOpt = QNetworkHeadersPrivate::toInt(
589 cacheHeaders.value(QHttpHeaders::WellKnownHeader::Age));
590 const qint64 age_value = ageOpt.value_or(0);
591
592 QDateTime dateHeader;
593 qint64 date_value = 0;
594 value = cacheHeaders.value(QHttpHeaders::WellKnownHeader::Date);
595 if (!value.empty()) {
596 dateHeader = QNetworkHeadersPrivate::fromHttpDate(value);
597 date_value = dateHeader.toSecsSinceEpoch();
598 }
599
600 qint64 now = currentDateTime.toSecsSinceEpoch();
601 qint64 request_time = now;
602 qint64 response_time = now;
603
604 // Algorithm from RFC 2616 section 13.2.3
605 qint64 apparent_age = qMax<qint64>(0, response_time - date_value);
606 qint64 corrected_received_age = qMax(apparent_age, age_value);
607 qint64 response_delay = response_time - request_time;
608 qint64 corrected_initial_age = corrected_received_age + response_delay;
609 qint64 resident_time = now - response_time;
610 qint64 current_age = corrected_initial_age + resident_time;
611
612 qint64 freshness_lifetime = 0;
613
614 // RFC 2616 13.2.4 Expiration Calculations
615 if (lastModified.isValid() && dateHeader.isValid()) {
616 qint64 diff = lastModified.secsTo(dateHeader);
617 freshness_lifetime = diff / 10;
618 const auto warningHeader = "Warning"_ba;
619 if (httpRequest.headerField(warningHeader).isEmpty()) {
620 QDateTime dt = currentDateTime.addSecs(current_age);
621 if (currentDateTime.daysTo(dt) > 1)
622 httpRequest.setHeaderField(warningHeader, "113"_ba);
623 }
624 }
625
626 // the cache-saving code below sets the freshness_lifetime with (dateHeader - last_modified) / 10
627 // if "last-modified" is present, or to Expires otherwise
628 response_is_fresh = (freshness_lifetime > current_age);
629 } else {
630 // expiration date was calculated earlier (e.g. when storing object to the cache)
631 response_is_fresh = currentDateTime.secsTo(expirationDate) >= 0;
632 }
633
634 if (!response_is_fresh)
635 return false;
636
637#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
638 qDebug() << "response_is_fresh" << CacheLoadControlAttribute;
639#endif
640 return sendCacheContents(metaData);
641}
642
643QHttpNetworkRequest::Priority QNetworkReplyHttpImplPrivate::convert(QNetworkRequest::Priority prio)
644{
645 switch (prio) {
646 case QNetworkRequest::LowPriority:
647 return QHttpNetworkRequest::LowPriority;
648 case QNetworkRequest::HighPriority:
649 return QHttpNetworkRequest::HighPriority;
650 case QNetworkRequest::NormalPriority:
651 return QHttpNetworkRequest::NormalPriority;
652 }
653 Q_UNREACHABLE_RETURN(QHttpNetworkRequest::NormalPriority);
654}
655
656void QNetworkReplyHttpImplPrivate::maybeDropUploadDevice(const QNetworkRequest &newHttpRequest)
657{
658 // Check for 0-length upload device. Following RFC9110, we are discouraged
659 // from sending "content-length: 0" for methods where a content-length would
660 // not normally be expected. E.g. get, connect, head, delete
661 // https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-5
662 auto contentLength0Allowed = [&]{
663 switch (operation) {
664 case QNetworkAccessManager::CustomOperation: {
665 const QByteArray customVerb = newHttpRequest.attribute(QNetworkRequest::CustomVerbAttribute)
666 .toByteArray();
667 if (customVerb.compare("connect", Qt::CaseInsensitive) != 0)
668 return true; // Trust user => content-length 0 is presumably okay!
669 // else:
670 [[fallthrough]];
671 }
672 case QNetworkAccessManager::HeadOperation:
673 case QNetworkAccessManager::GetOperation:
674 case QNetworkAccessManager::DeleteOperation:
675 // no content-length 0
676 return false;
677 case QNetworkAccessManager::PutOperation:
678 case QNetworkAccessManager::PostOperation:
679 case QNetworkAccessManager::UnknownOperation:
680 // yes content-length 0
681 return true;
682 }
683 Q_UNREACHABLE_RETURN(false);
684 };
685
686 const auto hasEmptyOutgoingPayload = [&]() {
687 if (!outgoingData)
688 return false;
689 if (outgoingDataBuffer)
690 return outgoingDataBuffer->isEmpty();
691 return outgoingData->size() == 0;
692 };
693 if (Q_UNLIKELY(hasEmptyOutgoingPayload()) && !contentLength0Allowed()) {
694 outgoingData = nullptr;
695 outgoingDataBuffer.reset();
696 }
697}
698
699void QNetworkReplyHttpImplPrivate::postRequest(const QNetworkRequest &newHttpRequest)
700{
701 Q_Q(QNetworkReplyHttpImpl);
702
703 QThread *thread = nullptr;
704 if (synchronous) {
705 // A synchronous HTTP request uses its own thread
706 thread = new QThread();
707 thread->setObjectName(QStringLiteral("Qt HTTP synchronous thread"));
708 QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
709 thread->start();
710 } else {
711 // We use the manager-global thread.
712 // At some point we could switch to having multiple threads if it makes sense.
713 thread = managerPrivate->createThread();
714 }
715
716 QUrl url = newHttpRequest.url();
717 httpRequest.setUrl(url);
718 httpRequest.setRedirectCount(newHttpRequest.maximumRedirectsAllowed());
719
720 QString scheme = url.scheme();
721 bool ssl = (scheme == "https"_L1 || scheme == "preconnect-https"_L1);
722 q->setAttribute(QNetworkRequest::ConnectionEncryptedAttribute, ssl);
723 httpRequest.setSsl(ssl);
724
725 bool preConnect = (scheme == "preconnect-http"_L1 || scheme == "preconnect-https"_L1);
726 httpRequest.setPreConnect(preConnect);
727
728#ifndef QT_NO_NETWORKPROXY
729 QNetworkProxy transparentProxy, cacheProxy;
730
731 // FIXME the proxy stuff should be done in the HTTP thread
732 const auto proxies = managerPrivate->queryProxy(QNetworkProxyQuery(newHttpRequest.url()));
733 for (const QNetworkProxy &p : proxies) {
734 // use the first proxy that works
735 // for non-encrypted connections, any transparent or HTTP proxy
736 // for encrypted, only transparent proxies
737 if (!ssl
738 && (p.capabilities() & QNetworkProxy::CachingCapability)
739 && (p.type() == QNetworkProxy::HttpProxy ||
740 p.type() == QNetworkProxy::HttpCachingProxy)) {
741 cacheProxy = p;
742 transparentProxy = QNetworkProxy::NoProxy;
743 break;
744 }
745 if (p.isTransparentProxy()) {
746 transparentProxy = p;
747 cacheProxy = QNetworkProxy::NoProxy;
748 break;
749 }
750 }
751
752 // check if at least one of the proxies
753 if (transparentProxy.type() == QNetworkProxy::DefaultProxy &&
754 cacheProxy.type() == QNetworkProxy::DefaultProxy) {
755 // unsuitable proxies
756 QMetaObject::invokeMethod(q, "_q_error", synchronous ? Qt::DirectConnection : Qt::QueuedConnection,
757 Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ProxyNotFoundError),
758 Q_ARG(QString, QNetworkReplyHttpImpl::tr("No suitable proxy found")));
759 QMetaObject::invokeMethod(q, "_q_finished", synchronous ? Qt::DirectConnection : Qt::QueuedConnection);
760 return;
761 }
762#endif
763
764 auto redirectPolicy = QNetworkRequest::NoLessSafeRedirectPolicy;
765 const QVariant value = newHttpRequest.attribute(QNetworkRequest::RedirectPolicyAttribute);
766 if (value.isValid())
767 redirectPolicy = qvariant_cast<QNetworkRequest::RedirectPolicy>(value);
768
769 httpRequest.setRedirectPolicy(redirectPolicy);
770
771 // If, for some reason, it turns out we won't use the upload device we drop
772 // it in the following call:
773 maybeDropUploadDevice(newHttpRequest);
774
775 httpRequest.setPriority(convert(newHttpRequest.priority()));
776 loadingFromCache = false;
777
778 switch (operation) {
779 case QNetworkAccessManager::GetOperation:
780 httpRequest.setOperation(QHttpNetworkRequest::Get);
781 // If the request has a body, createUploadByteDevice() and don't use caching
782 if (outgoingData) {
784 createUploadByteDevice();
785 } else if (loadFromCacheIfAllowed(httpRequest)) {
786 return; // no need to send the request! :)
787 }
788 break;
789
790 case QNetworkAccessManager::HeadOperation:
791 httpRequest.setOperation(QHttpNetworkRequest::Head);
792 if (loadFromCacheIfAllowed(httpRequest))
793 return; // no need to send the request! :)
794 break;
795
796 case QNetworkAccessManager::PostOperation:
798 httpRequest.setOperation(QHttpNetworkRequest::Post);
799 createUploadByteDevice();
800 break;
801
802 case QNetworkAccessManager::PutOperation:
804 httpRequest.setOperation(QHttpNetworkRequest::Put);
805 createUploadByteDevice();
806 break;
807
808 case QNetworkAccessManager::DeleteOperation:
810 httpRequest.setOperation(QHttpNetworkRequest::Delete);
811 createUploadByteDevice();
812 break;
813
814 case QNetworkAccessManager::CustomOperation:
815 invalidateCache(); // for safety reasons, we don't know what the operation does
816 httpRequest.setOperation(QHttpNetworkRequest::Custom);
817 createUploadByteDevice();
818 httpRequest.setCustomVerb(newHttpRequest.attribute(
819 QNetworkRequest::CustomVerbAttribute).toByteArray());
820 break;
821
822 default:
823 break; // can't happen
824 }
825
826 QHttpHeaders newRequestHeaders = newHttpRequest.headers();
827 if (resumeOffset != 0) {
828 if (newRequestHeaders.contains(QHttpHeaders::WellKnownHeader::Range)) {
829 // Need to adjust resume offset for user specified range
830
831 // We've already verified that requestRange starts with "bytes=", see canResume.
832 const auto rangeHeader = newRequestHeaders.value(QHttpHeaders::WellKnownHeader::Range);
833 const auto requestRange = QByteArrayView(rangeHeader).mid(bytesEqualPrefix().size());
834
835 newRequestHeaders.removeAll(QHttpHeaders::WellKnownHeader::Range);
836
837 int index = requestRange.indexOf('-');
838
839 quint64 requestStartOffset = requestRange.left(index).toULongLong();
840 quint64 requestEndOffset = requestRange.mid(index + 1).toULongLong();
841
842 // In case an end offset is not given it is skipped from the request range
843 QByteArray newRange = bytesEqualPrefix() + QByteArray::number(resumeOffset + requestStartOffset) +
844 '-' + (requestEndOffset ? QByteArray::number(requestEndOffset) : QByteArray());
845
846 httpRequest.setHeaderField(rangeName(), newRange);
847 } else {
848 httpRequest.setHeaderField(rangeName(), bytesEqualPrefix() + QByteArray::number(resumeOffset) + '-');
849 }
850 }
851
852 for (int i = 0; i < newRequestHeaders.size(); i++) {
853 const auto name = newRequestHeaders.nameAt(i);
854 const auto value = newRequestHeaders.valueAt(i);
855 httpRequest.setHeaderField(QByteArray(name.data(), name.size()), value.toByteArray());
856 }
857
858 if (newHttpRequest.attribute(QNetworkRequest::HttpPipeliningAllowedAttribute).toBool())
859 httpRequest.setPipeliningAllowed(true);
860
861 if (auto allowed = request.attribute(QNetworkRequest::Http2AllowedAttribute);
862 allowed.isValid() && allowed.canConvert<bool>()) {
863 httpRequest.setHTTP2Allowed(allowed.value<bool>());
864 }
865 auto h2cAttribute = request.attribute(QNetworkRequest::Http2CleartextAllowedAttribute);
866 // ### Qt7: Stop checking the environment variable
867 if (h2cAttribute.toBool()
868 || (!h2cAttribute.isValid() && qEnvironmentVariableIsSet("QT_NETWORK_H2C_ALLOWED"))) {
869 httpRequest.setH2cAllowed(true);
870 }
871
872 if (request.attribute(QNetworkRequest::Http2DirectAttribute).toBool()) {
873 // Intentionally mutually exclusive - cannot be both direct and 'allowed'
874 httpRequest.setHTTP2Direct(true);
875 httpRequest.setHTTP2Allowed(false);
876 }
877
878 if (static_cast<QNetworkRequest::LoadControl>
879 (newHttpRequest.attribute(QNetworkRequest::AuthenticationReuseAttribute,
880 QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Manual)
881 httpRequest.setWithCredentials(false);
882
883 if (request.attribute(QNetworkRequest::EmitAllUploadProgressSignalsAttribute).toBool())
884 emitAllUploadProgressSignals = true;
885
886 httpRequest.setPeerVerifyName(newHttpRequest.peerVerifyName());
887
888 if (scheme.startsWith(("unix"_L1))) {
889 if (QVariant path = newHttpRequest.attribute(QNetworkRequest::FullLocalServerNameAttribute);
890 path.isValid() && path.canConvert<QString>()) {
891 httpRequest.setFullLocalServerName(path.toString());
892 }
893 }
894
895 // Create the HTTP thread delegate
897 // Propagate Http/2 settings:
898 delegate->http2Parameters = request.http2Configuration();
899 delegate->http1Parameters = request.http1Configuration();
900 delegate->tcpKeepAliveParameters.idleTimeBeforeProbes = request.tcpKeepAliveIdleTimeBeforeProbes();
901 delegate->tcpKeepAliveParameters.intervalBetweenProbes = request.tcpKeepAliveIntervalBetweenProbes();
902 delegate->tcpKeepAliveParameters.probeCount = request.tcpKeepAliveProbeCount();
903
904 if (request.attribute(QNetworkRequest::ConnectionCacheExpiryTimeoutSecondsAttribute).isValid())
905 delegate->connectionCacheExpiryTimeoutSeconds = request.attribute(QNetworkRequest::ConnectionCacheExpiryTimeoutSecondsAttribute).toInt();
906
907 // For the synchronous HTTP, this is the normal way the delegate gets deleted
908 // For the asynchronous HTTP this is a safety measure, the delegate deletes itself when HTTP is finished
909 QMetaObject::Connection threadFinishedConnection =
910 QObject::connect(thread, SIGNAL(finished()), delegate, SLOT(deleteLater()));
911
912 // QTBUG-88063: When 'delegate' is deleted the connection will be added to 'thread''s orphaned
913 // connections list. This orphaned list will be cleaned up next time 'thread' emits a signal,
914 // unfortunately that's the finished signal. It leads to a soft-leak so we do this to disconnect
915 // it on deletion so that it cleans up the orphan immediately.
916 QObject::connect(delegate, &QObject::destroyed,
917 delegate, [threadFinishedConnection] () mutable {
918 if (bool(threadFinishedConnection))
919 QObject::disconnect(threadFinishedConnection);
920 });
921
922 // Set the properties it needs
923 delegate->httpRequest = httpRequest;
924#ifndef QT_NO_NETWORKPROXY
925 delegate->cacheProxy = cacheProxy;
926 delegate->transparentProxy = transparentProxy;
927#endif
928 delegate->ssl = ssl;
929#ifndef QT_NO_SSL
930 if (ssl)
931 delegate->incomingSslConfiguration.reset(new QSslConfiguration(newHttpRequest.sslConfiguration()));
932#endif
933
934 // Do we use synchronous HTTP?
935 delegate->synchronous = synchronous;
936
937 // The authentication manager is used to avoid the BlockingQueuedConnection communication
938 // from HTTP thread to user thread in some cases.
939 delegate->authenticationManager = managerPrivate->authenticationManager;
940
941 if (!synchronous) {
942 // Tell our zerocopy policy to the delegate
943 QVariant downloadBufferMaximumSizeAttribute = newHttpRequest.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
944 if (downloadBufferMaximumSizeAttribute.isValid()) {
945 delegate->downloadBufferMaximumSize = downloadBufferMaximumSizeAttribute.toLongLong();
946 } else {
947 // If there is no MaximumDownloadBufferSizeAttribute set (which is for the majority
948 // of QNetworkRequest) then we can assume we'll do it anyway for small HTTP replies.
949 // This helps with performance and memory fragmentation.
950 delegate->downloadBufferMaximumSize = 128*1024;
951 }
952
953
954 // These atomic integers are used for signal compression
955 delegate->pendingDownloadData = pendingDownloadDataEmissions;
956 delegate->pendingDownloadProgress = pendingDownloadProgressEmissions;
957
958 // Connect the signals of the delegate to us
959 QObject::connect(delegate, SIGNAL(downloadData(QByteArray)),
960 q, SLOT(replyDownloadData(QByteArray)),
961 Qt::QueuedConnection);
962 QObject::connect(delegate, SIGNAL(downloadFinished()),
963 q, SLOT(replyFinished()),
964 Qt::QueuedConnection);
965 QObject::connect(delegate, &QHttpThreadDelegate::socketStartedConnecting,
966 q, &QNetworkReply::socketStartedConnecting, Qt::QueuedConnection);
967 QObject::connect(delegate, &QHttpThreadDelegate::requestSent,
968 q, &QNetworkReply::requestSent, Qt::QueuedConnection);
969 connect(delegate, &QHttpThreadDelegate::downloadMetaData, this,
970 &QNetworkReplyHttpImplPrivate::replyDownloadMetaData, Qt::QueuedConnection);
971 QObject::connect(delegate, SIGNAL(downloadProgress(qint64,qint64)),
972 q, SLOT(replyDownloadProgressSlot(qint64,qint64)),
973 Qt::QueuedConnection);
974 QObject::connect(delegate, SIGNAL(error(QNetworkReply::NetworkError,QString)),
975 q, SLOT(httpError(QNetworkReply::NetworkError,QString)),
976 Qt::QueuedConnection);
977 QObject::connect(delegate, SIGNAL(redirected(QUrl,int,int)),
978 q, SLOT(onRedirected(QUrl,int,int)),
979 Qt::QueuedConnection);
980
981#ifndef QT_NO_SSL
982 QObject::connect(delegate, SIGNAL(sslConfigurationChanged(QSslConfiguration)),
983 q, SLOT(replySslConfigurationChanged(QSslConfiguration)),
984 Qt::QueuedConnection);
985#endif
986 // Those need to report back, therefore BlockingQueuedConnection
987 QObject::connect(delegate, SIGNAL(authenticationRequired(QHttpNetworkRequest,QAuthenticator*)),
988 q, SLOT(httpAuthenticationRequired(QHttpNetworkRequest,QAuthenticator*)),
989 Qt::BlockingQueuedConnection);
990#ifndef QT_NO_NETWORKPROXY
991 QObject::connect(delegate, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
992 q, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
993 Qt::BlockingQueuedConnection);
994#endif
995#ifndef QT_NO_SSL
996 QObject::connect(delegate, SIGNAL(encrypted()), q, SLOT(replyEncrypted()),
997 Qt::BlockingQueuedConnection);
998 QObject::connect(delegate, SIGNAL(sslErrors(QList<QSslError>,bool*,QList<QSslError>*)),
999 q, SLOT(replySslErrors(QList<QSslError>,bool*,QList<QSslError>*)),
1000 Qt::BlockingQueuedConnection);
1001 QObject::connect(delegate, SIGNAL(preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator*)),
1002 q, SLOT(replyPreSharedKeyAuthenticationRequiredSlot(QSslPreSharedKeyAuthenticator*)),
1003 Qt::BlockingQueuedConnection);
1004#endif
1005 // This signal we will use to start the request. A delegate serves exactly one
1006 // request, so it must not start again when a later request (a redirect) is posted.
1007 QObject::connect(q, &QNetworkReplyHttpImpl::startHttpRequest,
1008 delegate, &QHttpThreadDelegate::startRequest, Qt::SingleShotConnection);
1009 QObject::connect(q, &QNetworkReplyHttpImpl::abortHttpRequest,
1010 delegate, &QHttpThreadDelegate::abortRequest);
1011
1012 // To throttle the connection.
1013 QObject::connect(q, SIGNAL(readBufferSizeChanged(qint64)), delegate, SLOT(readBufferSizeChanged(qint64)));
1014 QObject::connect(q, SIGNAL(readBufferFreed(qint64)), delegate, SLOT(readBufferFreed(qint64)));
1015
1016 if (uploadByteDevice) {
1017 QNonContiguousByteDeviceThreadForwardImpl *forwardUploadDevice =
1018 new QNonContiguousByteDeviceThreadForwardImpl(uploadByteDevice->atEnd(), uploadByteDevice->size());
1019 forwardUploadDevice->setParent(delegate); // needed to make sure it is moved on moveToThread()
1020 delegate->httpRequest.setUploadByteDevice(forwardUploadDevice);
1021
1022 // If the device in the user thread claims it has more data, keep the flow to HTTP thread going
1023 QObject::connect(uploadByteDevice.get(), SIGNAL(readyRead()),
1024 q, SLOT(uploadByteDeviceReadyReadSlot()),
1025 Qt::QueuedConnection);
1026
1027 // From user thread to http thread:
1028 QObject::connect(q, SIGNAL(haveUploadData(qint64,QByteArray,bool,qint64)),
1029 forwardUploadDevice, SLOT(haveDataSlot(qint64,QByteArray,bool,qint64)), Qt::QueuedConnection);
1030 QObject::connect(uploadByteDevice.get(), SIGNAL(readyRead()),
1031 forwardUploadDevice, SIGNAL(readyRead()),
1032 Qt::QueuedConnection);
1033
1034 // From http thread to user thread:
1035 QObject::connect(forwardUploadDevice, SIGNAL(wantData(qint64)),
1036 q, SLOT(wantUploadDataSlot(qint64)));
1037 QObject::connect(forwardUploadDevice,SIGNAL(processedData(qint64,qint64)),
1038 q, SLOT(sentUploadDataSlot(qint64,qint64)));
1039 QObject::connect(forwardUploadDevice, SIGNAL(resetData(bool*)),
1040 q, SLOT(resetUploadDataSlot(bool*)),
1041 Qt::BlockingQueuedConnection); // this is the only one with BlockingQueued!
1042 }
1043 } else if (synchronous) {
1044 QObject::connect(q, SIGNAL(startHttpRequestSynchronously()), delegate, SLOT(startRequestSynchronously()), Qt::BlockingQueuedConnection);
1045
1046 if (uploadByteDevice) {
1047 // For the synchronous HTTP use case the use thread (this one here) is blocked
1048 // so we cannot use the asynchronous upload architecture.
1049 // We therefore won't use the QNonContiguousByteDeviceThreadForwardImpl but directly
1050 // use the uploadByteDevice provided to us by the QNetworkReplyImpl.
1051 // The code that is in start() makes sure it is safe to use from a thread
1052 // since it only wraps a QRingBuffer
1053 delegate->httpRequest.setUploadByteDevice(uploadByteDevice.get());
1054 }
1055 }
1056
1057
1058 // Move the delegate to the http thread
1059 delegate->moveToThread(thread);
1060 // This call automatically moves the uploadDevice too for the asynchronous case.
1061
1062 // Prepare timers for progress notifications
1063 downloadProgressSignalChoke.start();
1064 uploadProgressSignalChoke.invalidate();
1065
1066 // Send an signal to the delegate so it starts working in the other thread
1067 if (synchronous) {
1068 emit q->startHttpRequestSynchronously(); // This one is BlockingQueuedConnection, so it will return when all work is done
1069
1070 replyDownloadMetaData
1071 (delegate->incomingHeaders,
1072 delegate->incomingStatusCode,
1073 delegate->incomingReasonPhrase,
1074 delegate->isPipeliningUsed,
1075 QSharedPointer<char>(),
1076 delegate->incomingContentLength,
1077 delegate->removedContentLength,
1078 delegate->isHttp2Used,
1079 delegate->isCompressed);
1080 replyDownloadData(delegate->synchronousDownloadData);
1081
1082 if (delegate->incomingErrorCode != QNetworkReply::NoError)
1083 httpError(delegate->incomingErrorCode, delegate->incomingErrorDetail);
1084
1085 thread->quit();
1086 thread->wait(QDeadlineTimer(5000));
1087 if (thread->isFinished())
1088 delete thread;
1089 else
1090 QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
1091
1092 finished();
1093 } else {
1094 emit q->startHttpRequest(); // Signal to the HTTP thread and go back to user.
1095 }
1096}
1097
1099{
1100 QAbstractNetworkCache *nc = managerPrivate->networkCache;
1101 if (nc)
1102 nc->remove(httpRequest.url());
1103}
1104
1106{
1107 Q_Q(QNetworkReplyHttpImpl);
1108
1109 // The disk cache does not support partial content, so don't even try to
1110 // save any such content into the cache.
1111 if (q->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 206) {
1112 cacheEnabled = false;
1113 return;
1114 }
1115
1116 // save the meta data
1117 QNetworkCacheMetaData metaData;
1118 metaData.setUrl(url);
1119 metaData = fetchCacheMetaData(metaData);
1120
1121 // save the redirect request also in the cache
1122 QVariant redirectionTarget = q->attribute(QNetworkRequest::RedirectionTargetAttribute);
1123 if (redirectionTarget.isValid()) {
1124 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
1125 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
1126 metaData.setAttributes(attributes);
1127 }
1128
1129 cacheSaveDevice = managerPrivate->networkCache->prepare(metaData);
1130
1131 if (cacheSaveDevice)
1132 q->connect(cacheSaveDevice, SIGNAL(aboutToClose()), SLOT(_q_cacheSaveDeviceAboutToClose()));
1133
1134 if (!cacheSaveDevice || !cacheSaveDevice->isOpen()) {
1135 if (Q_UNLIKELY(cacheSaveDevice && !cacheSaveDevice->isOpen()))
1136 qCritical("QNetworkReplyImpl: network cache returned a device that is not open -- "
1137 "class %s probably needs to be fixed",
1138 managerPrivate->networkCache->metaObject()->className());
1139
1140 managerPrivate->networkCache->remove(url);
1141 cacheSaveDevice = nullptr;
1142 cacheEnabled = false;
1143 }
1144}
1145
1147{
1148 Q_Q(QNetworkReplyHttpImpl);
1149
1150 // If we're closed just ignore this data
1151 if (!q->isOpen())
1152 return;
1153
1154 // cache this, we need it later and it's invalidated when dealing with compressed data
1155 auto dataSize = d.size();
1156
1159
1160 if (decompressHelper.isValid()) {
1161 qint64 uncompressedBefore = -1;
1162 if (decompressHelper.isCountingBytes())
1163 uncompressedBefore = decompressHelper.uncompressedSize();
1164
1165 decompressHelper.feed(std::move(d));
1166
1167 if (!decompressHelper.isValid()) {
1168 error(QNetworkReplyImpl::NetworkError::UnknownContentError,
1169 QCoreApplication::translate("QHttp", "Decompression failed: %1")
1170 .arg(decompressHelper.errorString()));
1171 decompressHelper.clear();
1172 return;
1173 }
1174
1176 if (decompressHelper.isCountingBytes())
1177 bytesDownloaded += (decompressHelper.uncompressedSize() - uncompressedBefore);
1179 }
1180
1181 if (synchronous) {
1182 d = QByteArray();
1183 const qsizetype increments = 16 * 1024;
1184 qint64 bytesRead = 0;
1185 while (decompressHelper.hasData()) {
1186 quint64 nextSize = quint64(d.size()) + quint64(increments);
1187 if (nextSize > quint64(std::numeric_limits<QByteArray::size_type>::max())) {
1188 error(QNetworkReplyImpl::NetworkError::UnknownContentError,
1189 QCoreApplication::translate("QHttp",
1190 "Data downloaded is too large to store"));
1191 decompressHelper.clear();
1192 return;
1193 }
1194 d.resize(nextSize);
1195 bytesRead += decompressHelper.read(d.data() + bytesRead, increments);
1196 if (!decompressHelper.isValid()) {
1197 error(QNetworkReplyImpl::NetworkError::UnknownContentError,
1198 QCoreApplication::translate("QHttp", "Decompression failed: %1")
1199 .arg(decompressHelper.errorString()));
1200 decompressHelper.clear();
1201 return;
1202 }
1203 }
1204 d.resize(bytesRead);
1205 // we're synchronous so we're not calling this function again; reset the decompressHelper
1206 decompressHelper.clear();
1207 }
1208 }
1209
1210 // This is going to look a little strange. When downloading data while a
1211 // HTTP redirect is happening (and enabled), we write the redirect
1212 // response to the cache. However, we do not append it to our internal
1213 // buffer as that will contain the response data only for the final
1214 // response
1215 // Note: For compressed data this is done in readData()
1216 if (cacheSaveDevice && !decompressHelper.isValid()) {
1217 cacheSaveDevice->write(d);
1218 }
1219
1220 // if decompressHelper is valid then we have compressed data, and this is handled above
1221 if (!decompressHelper.isValid() && !isHttpRedirectResponse()) {
1222 buffer.append(d);
1223 bytesDownloaded += dataSize;
1225 }
1226 bytesBuffered += dataSize;
1227
1228 int pendingSignals = pendingDownloadDataEmissions->fetchAndSubAcquire(1) - 1;
1229 if (pendingSignals > 0) {
1230 // Some more signal emissions to this slot are pending.
1231 // Instead of writing the downstream data, we wait
1232 // and do it in the next call we get
1233 // (signal comppression)
1234 return;
1235 }
1236
1238 return;
1239
1240 // This can occur when downloading compressed data as some of the data may be the content
1241 // encoding's header. Don't emit anything for this.
1242 if (lastReadyReadEmittedSize == bytesDownloaded) {
1243 if (readBufferMaxSize)
1244 emit q->readBufferFreed(dataSize);
1245 return;
1246 }
1247 lastReadyReadEmittedSize = bytesDownloaded;
1248
1249 const auto totalSizeOpt = QNetworkHeadersPrivate::toInt(
1250 headers().value(QHttpHeaders::WellKnownHeader::ContentLength));
1251
1252 emit q->readyRead();
1253 // emit readyRead before downloadProgress in case this will cause events to be
1254 // processed and we get into a recursive call (as in QProgressDialog).
1255 if (downloadProgressSignalChoke.isValid() &&
1256 downloadProgressSignalChoke.elapsed() >= progressSignalInterval
1257 && (!decompressHelper.isValid() || decompressHelper.isCountingBytes())) {
1258 downloadProgressSignalChoke.start();
1259 emit q->downloadProgress(bytesDownloaded, totalSizeOpt.value_or(-1));
1260 }
1261}
1262
1264{
1265 // We are already loading from cache, we still however
1266 // got this signal because it was posted already
1267 if (loadingFromCache)
1268 return;
1269
1270 finished();
1271}
1272
1273QNetworkAccessManager::Operation QNetworkReplyHttpImplPrivate::getRedirectOperation(QNetworkAccessManager::Operation currentOp, int httpStatus)
1274{
1275 // HTTP status code can be used to decide if we can redirect with a GET
1276 // operation or not. See http://www.ietf.org/rfc/rfc2616.txt [Sec 10.3] for
1277 // more details
1278
1279 // We MUST keep using the verb that was used originally when being redirected with 307 or 308.
1280 if (httpStatus == 307 || httpStatus == 308)
1281 return currentOp;
1282
1283 switch (currentOp) {
1284 case QNetworkAccessManager::HeadOperation:
1285 return QNetworkAccessManager::HeadOperation;
1286 default:
1287 break;
1288 }
1289 // Use GET for everything else.
1290 return QNetworkAccessManager::GetOperation;
1291}
1292
1294{
1295 return httpRequest.isFollowRedirects() && QHttpNetworkReply::isHttpRedirect(statusCode);
1296}
1297
1298QNetworkRequest QNetworkReplyHttpImplPrivate::createRedirectRequest(const QNetworkRequest &originalRequest,
1299 const QUrl &url,
1300 int maxRedirectsRemaining)
1301{
1302 QNetworkRequest newRequest(originalRequest);
1303 newRequest.setUrl(url);
1304 newRequest.setMaximumRedirectsAllowed(maxRedirectsRemaining);
1305
1306 return newRequest;
1307}
1308
1309void QNetworkReplyHttpImplPrivate::onRedirected(const QUrl &redirectUrl, int httpStatus, int maxRedirectsRemaining)
1310{
1311 Q_Q(QNetworkReplyHttpImpl);
1312 Q_ASSERT(manager);
1313 Q_ASSERT(managerPrivate);
1314
1315 if (isFinished)
1316 return;
1317
1318 const QString schemeBefore(url.scheme());
1319 if (httpRequest.isFollowRedirects()) // update the reply's url as it could've changed
1320 url = redirectUrl;
1321
1322 const bool wasLocalSocket = schemeBefore.startsWith("unix"_L1);
1323 if (!wasLocalSocket && managerPrivate->stsEnabled && managerPrivate->stsCache.isKnownHost(url)) {
1324 // RFC6797, 8.3:
1325 // The UA MUST replace the URI scheme with "https" [RFC2818],
1326 // and if the URI contains an explicit port component of "80",
1327 // then the UA MUST convert the port component to be "443", or
1328 // if the URI contains an explicit port component that is not
1329 // equal to "80", the port component value MUST be preserved;
1330 // otherwise, if the URI does not contain an explicit port
1331 // component, the UA MUST NOT add one.
1332 url.setScheme("https"_L1);
1333 if (url.port() == 80)
1334 url.setPort(443);
1335 }
1336
1337 // Just to be on the safe side for local sockets, any changes to the scheme
1338 // are considered less safe
1339 const bool changingLocalScheme = wasLocalSocket && url.scheme() != schemeBefore;
1340 const bool isLessSafe = changingLocalScheme
1341 || (schemeBefore == "https"_L1 && url.scheme() == "http"_L1);
1342 if (httpRequest.redirectPolicy() == QNetworkRequest::NoLessSafeRedirectPolicy && isLessSafe) {
1343 error(QNetworkReply::InsecureRedirectError,
1344 QCoreApplication::translate("QHttp", "Insecure redirect"));
1345 return;
1346 }
1347
1348 // If the original operation was a GET with a body and the status code is
1349 // 308 then keep the message body. The body must still be present though:
1350 // a previous redirect (e.g. 301/302/303) has already dropped it, and once
1351 // dropped it cannot be restored, so the headers must be dropped too to keep
1352 // them in sync (QTBUG-133976).
1353 const bool getOperationKeepsBody = (operation == QNetworkAccessManager::GetOperation)
1354 && httpStatus == 308
1355 && (outgoingData || outgoingDataBuffer);
1356
1357 redirectRequest = createRedirectRequest(originalRequest, url, maxRedirectsRemaining);
1358 operation = getRedirectOperation(operation, httpStatus);
1359
1360 // Clear stale headers, the relevant ones get set again later
1361 httpRequest.clearHeaders();
1362 auto newHeaders = redirectRequest.headers();
1363 if ((operation == QNetworkAccessManager::GetOperation
1364 || operation == QNetworkAccessManager::HeadOperation) && !getOperationKeepsBody) {
1365 // possibly changed from not-GET/HEAD to GET/HEAD, make sure to get rid of upload device
1366 uploadByteDevice.reset();
1367 uploadByteDevicePosition = 0;
1368 if (outgoingData) {
1369 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q,
1370 SLOT(_q_bufferOutgoingData()));
1371 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q,
1372 SLOT(_q_bufferOutgoingDataFinished()));
1373 }
1374 outgoingData = nullptr;
1375 outgoingDataBuffer.reset();
1376 // We need to explicitly unset these headers so they're not reapplied to the httpRequest
1377 newHeaders.removeAll(QHttpHeaders::WellKnownHeader::ContentLength);
1378 newHeaders.removeAll(QHttpHeaders::WellKnownHeader::ContentType);
1379 }
1380
1381 if (const QNetworkCookieJar *const cookieJar = manager->cookieJar()) {
1382 auto cookies = cookieJar->cookiesForUrl(url);
1383 if (!cookies.empty()) {
1384 auto cookieHeader = QNetworkHeadersPrivate::fromCookieList(cookies);
1385 newHeaders.replaceOrAppend(QHttpHeaders::WellKnownHeader::Cookie, cookieHeader);
1386 }
1387 }
1388
1389 redirectRequest.setHeaders(std::move(newHeaders));
1390
1391 if (httpRequest.redirectPolicy() != QNetworkRequest::UserVerifiedRedirectPolicy)
1393
1394 emit q->redirected(url);
1395}
1396
1398{
1399 Q_Q(QNetworkReplyHttpImpl);
1400 Q_ASSERT(managerPrivate);
1401
1402 decompressHelper.clear();
1403 clearHeaders();
1404
1405 if (managerPrivate->thread)
1406 managerPrivate->thread->disconnect();
1407
1408 QMetaObject::invokeMethod(
1409 q,
1410 [this] {
1411 postRequest(redirectRequest);
1412 setupTransferTimeout();
1413 },
1414 Qt::QueuedConnection);
1415}
1416
1417static constexpr QLatin1StringView locationHeader() noexcept { return "location"_L1; }
1418
1420{
1421 Q_Q(QNetworkReplyHttpImpl);
1422 switch (statusCode) {
1423 case 301: // Moved Permanently
1424 case 302: // Found
1425 case 303: // See Other
1426 case 307: // Temporary Redirect
1427 case 308: // Permanent Redirect
1428 // What do we do about the caching of the HTML note?
1429 // The response to a 303 MUST NOT be cached, while the response to
1430 // all of the others is cacheable if the headers indicate it to be
1431 QByteArrayView header = q->headers().value(locationHeader());
1432 QUrl url = QUrl(QString::fromUtf8(header));
1433 if (!url.isValid())
1434 url = QUrl(QLatin1StringView(header));
1435 q->setAttribute(QNetworkRequest::RedirectionTargetAttribute, url);
1436 }
1437}
1438
1439void QNetworkReplyHttpImplPrivate::replyDownloadMetaData(const QHttpHeaders &hm,
1440 int sc, const QString &rp, bool pu,
1441 QSharedPointer<char> db,
1442 qint64 contentLength,
1443 qint64 removedContentLength,
1444 bool h2Used, bool isCompressed)
1445{
1446 Q_Q(QNetworkReplyHttpImpl);
1447 Q_UNUSED(contentLength);
1448
1449 statusCode = sc;
1450 reasonPhrase = rp;
1451
1452#ifndef QT_NO_SSL
1453 // We parse this header only if we're using secure transport:
1454 //
1455 // RFC6797, 8.1
1456 // If an HTTP response is received over insecure transport, the UA MUST
1457 // ignore any present STS header field(s).
1458 if (url.scheme() == "https"_L1 && managerPrivate->stsEnabled)
1459 managerPrivate->stsCache.updateFromHeaders(hm, url);
1460#endif
1461 // Download buffer
1462 if (!db.isNull()) {
1463 downloadBufferPointer = db;
1464 downloadZerocopyBuffer = downloadBufferPointer.data();
1465 downloadBufferCurrentSize = 0;
1466 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, QVariant::fromValue<QSharedPointer<char> > (downloadBufferPointer));
1467 }
1468
1469 q->setAttribute(QNetworkRequest::HttpPipeliningWasUsedAttribute, pu);
1470 q->setAttribute(QNetworkRequest::Http2WasUsedAttribute, h2Used);
1471
1472 // A user having manually defined which encodings they accept is, for
1473 // somwehat unknown (presumed legacy compatibility) reasons treated as
1474 // disabling our decompression:
1475 const bool autoDecompress = !request.headers().contains(QHttpHeaders::WellKnownHeader::AcceptEncoding);
1476 const bool shouldDecompress = isCompressed && autoDecompress;
1477 // reconstruct the HTTP header
1478 auto h = q->headers();
1479 for (qsizetype i = 0; i < hm.size(); ++i) {
1480 const auto key = hm.nameAt(i);
1481 const auto originValue = hm.valueAt(i);
1482
1483 // Reset any previous "location" header set in the reply. In case of
1484 // redirects, we don't want to 'append' multiple location header values,
1485 // rather we keep only the latest one
1486 if (key.compare(locationHeader(), Qt::CaseInsensitive) == 0)
1487 h.removeAll(key);
1488
1489 if (shouldDecompress && !decompressHelper.isValid()
1490 && key == QHttpHeaders::wellKnownHeaderName(QHttpHeaders::WellKnownHeader::ContentEncoding)) {
1491 if (!synchronous) // with synchronous all the data is expected to be handled at once
1492 decompressHelper.setCountingBytesEnabled(true);
1493
1494 if (!decompressHelper.setEncoding(originValue)) {
1495 error(QNetworkReplyImpl::NetworkError::UnknownContentError,
1496 QCoreApplication::translate("QHttp", "Failed to initialize decompression: %1")
1497 .arg(decompressHelper.errorString()));
1498 return;
1499 }
1500 decompressHelper.setDecompressedSafetyCheckThreshold(
1501 request.decompressedSafetyCheckThreshold());
1502 }
1503
1504 h.append(key, originValue);
1505 }
1506 q->setHeaders(std::move(h));
1507
1508 q->setAttribute(QNetworkRequest::HttpStatusCodeAttribute, statusCode);
1509 q->setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, reasonPhrase);
1510 if (removedContentLength != -1)
1511 q->setAttribute(QNetworkRequest::OriginalContentLengthAttribute, removedContentLength);
1512
1513 // is it a redirection?
1516
1517 if (statusCode >= 500 && statusCode < 600) {
1518 QAbstractNetworkCache *nc = managerPrivate->networkCache;
1519 if (nc) {
1520 QNetworkCacheMetaData metaData = nc->metaData(httpRequest.url());
1521 auto value = metaData.headers().value(QHttpHeaders::WellKnownHeader::CacheControl);
1522 bool mustReValidate = false;
1523 if (!value.empty()) {
1524 QHash<QByteArray, QByteArray> cacheControl = parseHttpOptionHeader(value);
1525 if (cacheControl.contains("must-revalidate"_ba))
1526 mustReValidate = true;
1527 }
1528 if (!mustReValidate && sendCacheContents(metaData))
1529 return;
1530 }
1531 }
1532
1533 if (statusCode == 304) {
1534#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
1535 qDebug() << "Received a 304 from" << request.url();
1536#endif
1537 QAbstractNetworkCache *nc = managerPrivate->networkCache;
1538 if (nc) {
1539 QNetworkCacheMetaData oldMetaData = nc->metaData(httpRequest.url());
1540 QNetworkCacheMetaData metaData = fetchCacheMetaData(oldMetaData);
1541 if (oldMetaData != metaData)
1542 nc->updateMetaData(metaData);
1543 if (sendCacheContents(metaData))
1544 return;
1545 }
1546 }
1547
1548
1549 if (statusCode != 304 && statusCode != 303) {
1550 if (!isCachingEnabled())
1552 }
1553
1555}
1556
1557void QNetworkReplyHttpImplPrivate::replyDownloadProgressSlot(qint64 bytesReceived, qint64 bytesTotal)
1558{
1559 Q_Q(QNetworkReplyHttpImpl);
1560
1561 // If we're closed just ignore this data
1562 if (!q->isOpen())
1563 return;
1564
1565 // we can be sure here that there is a download buffer
1566
1567 int pendingSignals = (int)pendingDownloadProgressEmissions->fetchAndAddAcquire(-1) - 1;
1568 if (pendingSignals > 0) {
1569 // Let's ignore this signal and look at the next one coming in
1570 // (signal comppression)
1571 return;
1572 }
1573
1574 if (!q->isOpen())
1575 return;
1576
1577 if (cacheEnabled && isCachingAllowed() && bytesReceived == bytesTotal) {
1578 // Write everything in one go if we use a download buffer. might be more performant.
1580 // need to check again if cache enabled and device exists
1582 cacheSaveDevice->write(downloadZerocopyBuffer, bytesTotal);
1583 // FIXME where is it closed?
1584 }
1585
1587 return;
1588
1589 bytesDownloaded = bytesReceived;
1591
1592 downloadBufferCurrentSize = bytesReceived;
1593
1594 // Only emit readyRead when actual data is there
1595 // emit readyRead before downloadProgress in case this will cause events to be
1596 // processed and we get into a recursive call (as in QProgressDialog).
1597 if (bytesDownloaded > 0)
1598 emit q->readyRead();
1599 if (downloadProgressSignalChoke.isValid() &&
1600 downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
1601 downloadProgressSignalChoke.start();
1602 emit q->downloadProgress(bytesDownloaded, bytesTotal);
1603 }
1604}
1605
1606void QNetworkReplyHttpImplPrivate::httpAuthenticationRequired(const QHttpNetworkRequest &request,
1607 QAuthenticator *auth)
1608{
1609 managerPrivate->authenticationRequired(auth, q_func(), synchronous, url, &urlForLastAuthentication, request.withCredentials());
1610}
1611
1612#ifndef QT_NO_NETWORKPROXY
1613void QNetworkReplyHttpImplPrivate::proxyAuthenticationRequired(const QNetworkProxy &proxy,
1614 QAuthenticator *authenticator)
1615{
1616 managerPrivate->proxyAuthenticationRequired(request.url(), proxy, synchronous, authenticator, &lastProxyAuthentication);
1617}
1618#endif
1619
1620void QNetworkReplyHttpImplPrivate::httpError(QNetworkReply::NetworkError errorCode,
1621 const QString &errorString)
1622{
1623#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
1624 qDebug() << "http error!" << errorCode << errorString;
1625#endif
1626
1627 // FIXME?
1628 error(errorCode, errorString);
1629}
1630
1631#ifndef QT_NO_SSL
1633{
1634 Q_Q(QNetworkReplyHttpImpl);
1635 emit q->encrypted();
1636}
1637
1639 const QList<QSslError> &list, bool *ignoreAll, QList<QSslError> *toBeIgnored)
1640{
1641 Q_Q(QNetworkReplyHttpImpl);
1642 emit q->sslErrors(list);
1643 // Check if the callback set any ignore and return this here to http thread
1645 *ignoreAll = true;
1646 if (!pendingIgnoreSslErrorsList.isEmpty())
1647 *toBeIgnored = pendingIgnoreSslErrorsList;
1648}
1649
1650void QNetworkReplyHttpImplPrivate::replySslConfigurationChanged(const QSslConfiguration &newSslConfiguration)
1651{
1652 // Receiving the used SSL configuration from the HTTP thread
1653 if (sslConfiguration)
1654 *sslConfiguration = newSslConfiguration;
1655 else
1656 sslConfiguration.reset(new QSslConfiguration(newSslConfiguration));
1657}
1658
1660{
1661 Q_Q(QNetworkReplyHttpImpl);
1662 emit q->preSharedKeyAuthenticationRequired(authenticator);
1663}
1664#endif
1665
1666// Coming from QNonContiguousByteDeviceThreadForwardImpl in HTTP thread
1668{
1669 *r = uploadByteDevice->reset();
1670 if (*r) {
1671 // reset our own position which is used for the inter-thread communication
1672 uploadByteDevicePosition = 0;
1673 }
1674}
1675
1676// Coming from QNonContiguousByteDeviceThreadForwardImpl in HTTP thread
1677void QNetworkReplyHttpImplPrivate::sentUploadDataSlot(qint64 pos, qint64 amount)
1678{
1679 if (!uploadByteDevice) // uploadByteDevice is no longer available
1680 return;
1681
1682 if (uploadByteDevicePosition + amount != pos) {
1683 // Sanity check, should not happen.
1684 error(QNetworkReply::UnknownNetworkError, QString());
1685 return;
1686 }
1687 uploadByteDevice->advanceReadPointer(amount);
1688 uploadByteDevicePosition += amount;
1689}
1690
1691// Coming from QNonContiguousByteDeviceThreadForwardImpl in HTTP thread
1693{
1694 Q_Q(QNetworkReplyHttpImpl);
1695
1696 if (!uploadByteDevice) // uploadByteDevice is no longer available
1697 return;
1698
1699 // call readPointer
1700 qint64 currentUploadDataLength = 0;
1701 char *data = const_cast<char*>(uploadByteDevice->readPointer(maxSize, currentUploadDataLength));
1702
1703 if (currentUploadDataLength == 0) {
1704 uploadDeviceChoking = true;
1705 // No bytes from upload byte device. There will be bytes later, it will emit readyRead()
1706 // and our uploadByteDeviceReadyReadSlot() is called.
1707 return;
1708 } else {
1709 uploadDeviceChoking = false;
1710 }
1711
1712 // Let's make a copy of this data
1713 QByteArray dataArray(data, currentUploadDataLength);
1714
1715 // Communicate back to HTTP thread
1716 emit q->haveUploadData(uploadByteDevicePosition, dataArray, uploadByteDevice->atEnd(), uploadByteDevice->size());
1717}
1718
1720{
1721 // Start the flow between this thread and the HTTP thread again by triggering a upload.
1722 // However only do this when we were choking before, else the state in
1723 // QNonContiguousByteDeviceThreadForwardImpl gets messed up.
1724 if (uploadDeviceChoking) {
1725 uploadDeviceChoking = false;
1726 wantUploadDataSlot(1024);
1727 }
1728}
1729
1730
1731/*
1732 A simple web page that can be used to test us: http://www.procata.com/cachetest/
1733 */
1734bool QNetworkReplyHttpImplPrivate::sendCacheContents(const QNetworkCacheMetaData &metaData)
1735{
1736 Q_Q(QNetworkReplyHttpImpl);
1737
1739 if (!metaData.isValid())
1740 return false;
1741
1742 QAbstractNetworkCache *nc = managerPrivate->networkCache;
1743 Q_ASSERT(nc);
1744 QIODevice *contents = nc->data(url);
1745 if (!contents) {
1746#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
1747 qDebug() << "Cannot send cache, the contents are 0" << url;
1748#endif
1749 return false;
1750 }
1751 contents->setParent(q);
1752
1753 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
1754 int status = attributes.value(QNetworkRequest::HttpStatusCodeAttribute).toInt();
1755 if (status < 100)
1756 status = 200; // fake it
1757
1758 statusCode = status;
1759
1760 q->setAttribute(QNetworkRequest::HttpStatusCodeAttribute, status);
1761 q->setAttribute(QNetworkRequest::HttpReasonPhraseAttribute, attributes.value(QNetworkRequest::HttpReasonPhraseAttribute));
1762 q->setAttribute(QNetworkRequest::SourceIsFromCacheAttribute, true);
1763
1764 QHttpHeaders cachedHeaders = metaData.headers();
1765 QHttpHeaders h = headers();
1766 QUrl redirectUrl;
1767 for (qsizetype i = 0; i < cachedHeaders.size(); ++i) {
1768 const auto name = cachedHeaders.nameAt(i);
1769 const auto value = cachedHeaders.valueAt(i);
1770
1771 if (httpRequest.isFollowRedirects()
1772 && !name.compare(locationHeader(), Qt::CaseInsensitive)) {
1773 redirectUrl = QUrl::fromEncoded(value);
1774 }
1775
1776 h.replaceOrAppend(name, value);
1777 }
1778 setHeaders(std::move(h));
1779
1781 checkForRedirect(status);
1782
1783 cacheLoadDevice = contents;
1784 q->connect(cacheLoadDevice, SIGNAL(readyRead()), SLOT(_q_cacheLoadReadyRead()));
1785 q->connect(cacheLoadDevice, SIGNAL(readChannelFinished()), SLOT(_q_cacheLoadReadyRead()));
1786
1787 // This needs to be emitted in the event loop because it can be reached at
1788 // the direct code path of qnam.get(...) before the user has a chance
1789 // to connect any signals.
1790 QMetaObject::invokeMethod(q, "_q_metaDataChanged", Qt::QueuedConnection);
1791 QMetaObject::invokeMethod(q, "_q_cacheLoadReadyRead", Qt::QueuedConnection);
1792
1793
1794#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
1795 qDebug() << "Successfully sent cache:" << url << contents->size() << "bytes";
1796#endif
1797
1798 // Do redirect processing
1799 if (httpRequest.isFollowRedirects() && QHttpNetworkReply::isHttpRedirect(status)) {
1800 QMetaObject::invokeMethod(q, "onRedirected", Qt::QueuedConnection,
1801 Q_ARG(QUrl, redirectUrl),
1802 Q_ARG(int, status),
1803 Q_ARG(int, httpRequest.redirectCount() - 1));
1804 }
1805
1806 // Set the following flag so we can ignore some signals from HTTP thread
1807 // that would still come
1808 loadingFromCache = true;
1809 return true;
1810}
1811
1812static auto caseInsensitiveCompare(QByteArrayView value)
1813{
1814 return [value](QByteArrayView element)
1815 {
1816 return value.compare(element, Qt::CaseInsensitive) == 0;
1817 };
1818}
1819
1820static bool isHopByHop(QByteArrayView header)
1821{
1822 constexpr QByteArrayView headers[] = { "connection",
1823 "keep-alive",
1824 "proxy-authenticate",
1825 "proxy-authorization",
1826 "te",
1827 "trailers",
1828 "transfer-encoding",
1829 "upgrade"};
1830 return std::any_of(std::begin(headers), std::end(headers), caseInsensitiveCompare(header));
1831}
1832
1833QNetworkCacheMetaData QNetworkReplyHttpImplPrivate::fetchCacheMetaData(const QNetworkCacheMetaData &oldMetaData) const
1834{
1835 Q_Q(const QNetworkReplyHttpImpl);
1836
1837 QNetworkCacheMetaData metaData = oldMetaData;
1838 QHttpHeaders cacheHeaders = metaData.headers();
1839
1840 const auto newHeaders = q->headers();
1841 for (qsizetype i = 0; i < newHeaders.size(); ++i) {
1842 const auto name = newHeaders.nameAt(i);
1843 const auto value = newHeaders.valueAt(i);
1844
1845 if (isHopByHop(name))
1846 continue;
1847
1848 if (name.compare("set-cookie", Qt::CaseInsensitive) == 0)
1849 continue;
1850
1851 // for 4.6.0, we were planning to not store the date header in the
1852 // cached resource; through that we planned to reduce the number
1853 // of writes to disk when using a QNetworkDiskCache (i.e. don't
1854 // write to disk when only the date changes).
1855 // However, without the date we cannot calculate the age of the page
1856 // anymore.
1857 //if (header == "date")
1858 //continue;
1859
1860 // Don't store Warning 1xx headers
1861 if (name.compare("warning", Qt::CaseInsensitive) == 0) {
1862 if (value.size() == 3
1863 && value[0] == '1'
1864 && isAsciiDigit(value[1])
1865 && isAsciiDigit(value[2]))
1866 continue;
1867 }
1868
1869 if (cacheHeaders.contains(name)) {
1870 // Match the behavior of Firefox and assume Cache-Control: "no-transform"
1871 constexpr QByteArrayView headers[]=
1872 {"content-encoding", "content-range", "content-type"};
1873 if (std::any_of(std::begin(headers), std::end(headers), caseInsensitiveCompare(name)))
1874 continue;
1875 }
1876
1877 // IIS has been known to send "Content-Length: 0" on 304 responses, so
1878 // ignore this too
1879 if (statusCode == 304 && name.compare("content-length", Qt::CaseInsensitive) == 0)
1880 continue;
1881
1882#if defined(QNETWORKACCESSHTTPBACKEND_DEBUG)
1883 QByteArrayView n = newHeaders.value(name);
1884 QByteArrayView o = cacheHeaders.value(name);
1885 if (n != o && name.compare("date", Qt::CaseInsensitive) != 0) {
1886 qDebug() << "replacing" << name;
1887 qDebug() << "new" << n;
1888 qDebug() << "old" << o;
1889 }
1890#endif
1891 cacheHeaders.replaceOrAppend(name, value);
1892 }
1893 metaData.setHeaders(cacheHeaders);
1894
1895 bool checkExpired = true;
1896
1897 QHash<QByteArray, QByteArray> cacheControl;
1898 auto value = cacheHeaders.value(QHttpHeaders::WellKnownHeader::CacheControl);
1899 if (!value.empty()) {
1900 cacheControl = parseHttpOptionHeader(value);
1901 QByteArray maxAge = cacheControl.value("max-age"_ba);
1902 if (!maxAge.isEmpty()) {
1903 checkExpired = false;
1904 QDateTime dt = QDateTime::currentDateTimeUtc();
1905 dt = dt.addSecs(maxAge.toInt());
1906 metaData.setExpirationDate(dt);
1907 }
1908 }
1909 if (checkExpired) {
1910 if (const auto value = cacheHeaders.value(
1911 QHttpHeaders::WellKnownHeader::Expires); !value.isEmpty()) {
1912 QDateTime expiredDateTime = QNetworkHeadersPrivate::fromHttpDate(value);
1913 metaData.setExpirationDate(expiredDateTime);
1914 }
1915 }
1916
1917 if (const auto value = cacheHeaders.value(
1918 QHttpHeaders::WellKnownHeader::LastModified); !value.isEmpty()) {
1919 metaData.setLastModified(QNetworkHeadersPrivate::fromHttpDate(value));
1920 }
1921
1922
1923 bool canDiskCache;
1924 // only cache GET replies by default, all other replies (POST, PUT, DELETE)
1925 // are not cacheable by default (according to RFC 2616 section 9)
1926 if (httpRequest.operation() == QHttpNetworkRequest::Get) {
1927
1928 canDiskCache = true;
1929 // HTTP/1.1. Check the Cache-Control header
1930 if (cacheControl.contains("no-store"_ba))
1931 canDiskCache = false;
1932
1933 // responses to POST might be cacheable
1934 } else if (httpRequest.operation() == QHttpNetworkRequest::Post) {
1935
1936 canDiskCache = false;
1937 // some pages contain "expires:" and "cache-control: no-cache" field,
1938 // so we only might cache POST requests if we get "cache-control: max-age ..."
1939 if (cacheControl.contains("max-age"_ba))
1940 canDiskCache = true;
1941
1942 // responses to PUT and DELETE are not cacheable
1943 } else {
1944 canDiskCache = false;
1945 }
1946
1947 metaData.setSaveToDisk(canDiskCache);
1948 QNetworkCacheMetaData::AttributesMap attributes;
1949 if (statusCode != 304) {
1950 // update the status code
1951 attributes.insert(QNetworkRequest::HttpStatusCodeAttribute, statusCode);
1952 attributes.insert(QNetworkRequest::HttpReasonPhraseAttribute, reasonPhrase);
1953 } else {
1954 // this is a redirection, keep the attributes intact
1955 attributes = oldMetaData.attributes();
1956 }
1957 metaData.setAttributes(attributes);
1958 return metaData;
1959}
1960
1962{
1963 Q_Q(const QNetworkReplyHttpImpl);
1964
1965 // Only GET operation supports resuming.
1966 if (operation != QNetworkAccessManager::GetOperation)
1967 return false;
1968
1969 const auto h = q->headers();
1970
1971 // Can only resume if server/resource supports Range header.
1972 const auto acceptRanges = h.value(QHttpHeaders::WellKnownHeader::AcceptRanges);
1973 if (acceptRanges.empty() || acceptRanges == "none")
1974 return false;
1975
1976 // We only support resuming for byte ranges.
1977 const auto range = h.value(QHttpHeaders::WellKnownHeader::Range);
1978 if (!range.empty()) {
1979 if (!range.startsWith(bytesEqualPrefix()))
1980 return false;
1981 }
1982
1983 // If we're using a download buffer then we don't support resuming/migration
1984 // right now. Too much trouble.
1986 return false;
1987
1988 return true;
1989}
1990
1992{
1993 resumeOffset = offset;
1994}
1995
1997{
1998 // Ensure this function is only being called once, and not at all if we were
1999 // cancelled
2000 if (state >= Working)
2001 return;
2002
2003 state = Working;
2004
2005 postRequest(request);
2006
2008 if (synchronous) {
2009 state = Finished;
2010 q_func()->setFinished(true);
2011 }
2012}
2013
2015{
2016 Q_Q(QNetworkReplyHttpImpl);
2017
2018 if (state != Working)
2019 return;
2020 if (!cacheLoadDevice || !q->isOpen() || !cacheLoadDevice->bytesAvailable())
2021 return;
2022
2023 // FIXME Optimize to use zerocopy download buffer if it is a QBuffer.
2024 // Needs to be done where sendCacheContents() (?) of HTTP is emitting
2025 // metaDataChanged ?
2026
2027 const auto totalSizeOpt = QNetworkHeadersPrivate::toInt(
2028 headers().value(QHttpHeaders::WellKnownHeader::ContentLength));
2029
2030 // emit readyRead before downloadProgress in case this will cause events to be
2031 // processed and we get into a recursive call (as in QProgressDialog).
2032
2033 if (!(isHttpRedirectResponse())) {
2034 // This readyRead() goes to the user. The user then may or may not read() anything.
2035 emit q->readyRead();
2036
2037 if (downloadProgressSignalChoke.isValid() &&
2038 downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
2039 downloadProgressSignalChoke.start();
2040 emit q->downloadProgress(bytesDownloaded, totalSizeOpt.value_or(-1));
2041 }
2042 }
2043
2044 // A signal we've emitted might be handled by a slot that aborts,
2045 // so we need to check for that and bail out if it's happened:
2046 if (!q->isOpen())
2047 return;
2048
2049 // If there are still bytes available in the cacheLoadDevice then the user did not read
2050 // in response to the readyRead() signal. This means we have to load from the cacheLoadDevice
2051 // and buffer that stuff. This is needed to be able to properly emit finished() later.
2052 while (cacheLoadDevice->bytesAvailable() && !isHttpRedirectResponse())
2053 buffer.append(cacheLoadDevice->readAll());
2054
2055 if (cacheLoadDevice->isSequential()) {
2056 // check if end and we can read the EOF -1
2057 char c;
2058 qint64 actualCount = cacheLoadDevice->read(&c, 1);
2059 if (actualCount < 0) {
2060 cacheLoadDevice->deleteLater();
2061 cacheLoadDevice = nullptr;
2062 QMetaObject::invokeMethod(q, "_q_finished", Qt::QueuedConnection);
2063 } else if (actualCount == 1) {
2064 // This is most probably not happening since most QIODevice returned something proper for bytesAvailable()
2065 // and had already been "emptied".
2066 cacheLoadDevice->ungetChar(c);
2067 }
2068 } else if ((!cacheLoadDevice->isSequential() && cacheLoadDevice->atEnd())) {
2069 // This codepath is in case the cache device is a QBuffer, e.g. from QNetworkDiskCache.
2070 cacheLoadDevice->deleteLater();
2071 cacheLoadDevice = nullptr;
2072 QMetaObject::invokeMethod(q, "_q_finished", Qt::QueuedConnection);
2073 }
2074}
2075
2076
2078{
2079 Q_Q(QNetworkReplyHttpImpl);
2080
2081 // make sure this is only called once, ever.
2082 //_q_bufferOutgoingData may call it or the readChannelFinished emission
2083 if (state != Buffering)
2084 return;
2085
2086 // disconnect signals
2087 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
2088 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
2089
2090 // finally, start the request
2091 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
2092}
2093
2095{
2096 // do not keep a dangling pointer to the device around (device
2097 // is closing because e.g. QAbstractNetworkCache::remove() was called).
2098 cacheSaveDevice = nullptr;
2099}
2100
2102{
2103 Q_Q(QNetworkReplyHttpImpl);
2104
2105 if (!outgoingDataBuffer) {
2106 // first call, create our buffer
2107 outgoingDataBuffer = std::make_shared<QRingBuffer>();
2108
2109 QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
2110 QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
2111 }
2112
2113 qint64 bytesBuffered = 0;
2114 qint64 bytesToBuffer = 0;
2115
2116 // read data into our buffer
2117 forever {
2118 bytesToBuffer = outgoingData->bytesAvailable();
2119 // unknown? just try 2 kB, this also ensures we always try to read the EOF
2120 if (bytesToBuffer <= 0)
2121 bytesToBuffer = 2*1024;
2122
2123 char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
2124 bytesBuffered = outgoingData->read(dst, bytesToBuffer);
2125
2126 if (bytesBuffered == -1) {
2127 // EOF has been reached.
2128 outgoingDataBuffer->chop(bytesToBuffer);
2129
2130 _q_bufferOutgoingDataFinished();
2131 break;
2132 } else if (bytesBuffered == 0) {
2133 // nothing read right now, just wait until we get called again
2134 outgoingDataBuffer->chop(bytesToBuffer);
2135
2136 break;
2137 } else {
2138 // don't break, try to read() again
2139 outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
2140 }
2141 }
2142}
2143
2145{
2146 Q_Q(QNetworkReplyHttpImpl);
2147 q->abortImpl(QNetworkReply::TimeoutError);
2148}
2149
2151{
2152 Q_Q(QNetworkReplyHttpImpl);
2153 if (!transferTimeout) {
2154 transferTimeout = new QTimer(q);
2155 QObject::connect(transferTimeout, SIGNAL(timeout()),
2156 q, SLOT(_q_transferTimedOut()),
2157 Qt::QueuedConnection);
2158 }
2159 transferTimeout->stop();
2160 if (request.transferTimeoutAsDuration() > 0ms) {
2161 transferTimeout->setSingleShot(true);
2162 transferTimeout->setInterval(request.transferTimeoutAsDuration());
2163 QMetaObject::invokeMethod(transferTimeout, "start",
2164 Qt::QueuedConnection);
2165
2166 }
2167}
2168
2169// need to have this function since the reply is a private member variable
2170// and the special backends need to access this.
2171void QNetworkReplyHttpImplPrivate::emitReplyUploadProgress(qint64 bytesSent, qint64 bytesTotal)
2172{
2173 Q_Q(QNetworkReplyHttpImpl);
2174 if (isFinished)
2175 return;
2176
2178
2179 if (!emitAllUploadProgressSignals) {
2180 //choke signal emissions, except the first and last signals which are unconditional
2181 if (uploadProgressSignalChoke.isValid()) {
2182 if (bytesSent != bytesTotal && uploadProgressSignalChoke.elapsed() < progressSignalInterval) {
2183 return;
2184 }
2185 }
2186 uploadProgressSignalChoke.start();
2187 }
2188 emit q->uploadProgress(bytesSent, bytesTotal);
2189}
2190
2192{
2193 Q_Q(QNetworkReplyHttpImpl);
2194
2195 if (outgoingDataBuffer)
2196 uploadByteDevice = QNonContiguousByteDeviceFactory::createShared(outgoingDataBuffer);
2197 else if (outgoingData) {
2198 uploadByteDevice = QNonContiguousByteDeviceFactory::createShared(outgoingData);
2199 } else {
2200 return nullptr;
2201 }
2202
2203 // We want signal emissions only for normal asynchronous uploads
2204 if (!synchronous)
2205 QObject::connect(uploadByteDevice.get(), SIGNAL(readProgress(qint64,qint64)),
2206 q, SLOT(emitReplyUploadProgress(qint64,qint64)));
2207
2208 return uploadByteDevice.get();
2209}
2210
2212{
2213 // This gets called queued, just forward to real call then
2214 finished();
2215}
2216
2218{
2219 Q_Q(QNetworkReplyHttpImpl);
2220 if (transferTimeout)
2221 transferTimeout->stop();
2222 if (state == Finished || state == Aborted)
2223 return;
2224
2225 const auto totalSizeOpt = QNetworkHeadersPrivate::toInt(
2226 headers().value(QHttpHeaders::WellKnownHeader::ContentLength));
2227 const qint64 totalSize = totalSizeOpt.value_or(-1);
2228
2229 // if we don't know the total size of or we received everything save the cache.
2230 // If the data is compressed then this is done in readData()
2231 if ((totalSize == -1 || bytesDownloaded == totalSize)
2232 && !decompressHelper.isValid()) {
2234 }
2235
2236 // We check for errorCode too as in case of SSL handshake failure, we still
2237 // get the HTTP redirect status code (301, 303 etc)
2238 if (isHttpRedirectResponse() && errorCode == QNetworkReply::NoError)
2239 return;
2240
2241 state = Finished;
2242 q->setFinished(true);
2243
2244 if (totalSize == -1) {
2245 emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
2246 } else {
2247 emit q->downloadProgress(bytesDownloaded, totalSize);
2248 }
2249
2250 if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
2251 emit q->uploadProgress(0, 0);
2252
2253 emit q->readChannelFinished();
2254 emit q->finished();
2255}
2256
2257void QNetworkReplyHttpImplPrivate::_q_error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
2258{
2259 this->error(code, errorMessage);
2260}
2261
2262
2263void QNetworkReplyHttpImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
2264{
2265 Q_Q(QNetworkReplyHttpImpl);
2266 // Can't set and emit multiple errors.
2267 if (errorCode != QNetworkReply::NoError) {
2268 // But somewhat unavoidable if we have cancelled the request:
2269 if (errorCode != QNetworkReply::OperationCanceledError
2270 && errorCode != QNetworkReply::TimeoutError) {
2271 qWarning("QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.");
2272 }
2273 return;
2274 }
2275
2276 errorCode = code;
2277 q->setErrorString(errorMessage);
2278
2279 // note: might not be a good idea, since users could decide to delete us
2280 // which would delete the backend too...
2281 // maybe we should protect the backend
2282 emit q->errorOccurred(code);
2283}
2284
2286{
2287 // FIXME merge this with replyDownloadMetaData(); ?
2288
2289 Q_Q(QNetworkReplyHttpImpl);
2290 // 1. do we have cookies?
2291 // 2. are we allowed to set them?
2292 Q_ASSERT(manager);
2293
2294 const auto cookiesOpt = QNetworkHeadersPrivate::toSetCookieList(
2295 headers().values(QHttpHeaders::WellKnownHeader::SetCookie));
2296 const auto cookies = cookiesOpt.value_or(QList<QNetworkCookie>());
2297 if (!cookies.empty()
2298 && request.attribute(QNetworkRequest::CookieSaveControlAttribute,
2299 QNetworkRequest::Automatic).toInt() == QNetworkRequest::Automatic) {
2300 QNetworkCookieJar *jar = manager->cookieJar();
2301 if (jar) {
2302 jar->setCookiesFromUrl(cookies, url);
2303 }
2304 }
2305 emit q->metaDataChanged();
2306}
2307
2309{
2310 // check if we can save and if we're allowed to
2311 if (!managerPrivate->networkCache
2312 || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool())
2313 return;
2314 cacheEnabled = true;
2315}
2316
2318{
2319 return (cacheEnabled && managerPrivate->networkCache != nullptr);
2320}
2321
2323{
2324 if (!enable && !cacheEnabled)
2325 return; // nothing to do
2326 if (enable && cacheEnabled)
2327 return; // nothing to do either!
2328
2329 if (enable) {
2330 if (Q_UNLIKELY(bytesDownloaded)) {
2331 qDebug() << "setCachingEnabled: " << bytesDownloaded << " bytesDownloaded";
2332 // refuse to enable in this case
2333 qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
2334 return;
2335 }
2336
2338 } else {
2339 // someone told us to turn on, then back off?
2340 // ok... but you should make up your mind
2341 qDebug("QNetworkReplyImpl: setCachingEnabled(true) called after setCachingEnabled(false)");
2342 managerPrivate->networkCache->remove(url);
2343 cacheSaveDevice = nullptr;
2344 cacheEnabled = false;
2345 }
2346}
2347
2349{
2350 return operation == QNetworkAccessManager::GetOperation || operation == QNetworkAccessManager::HeadOperation;
2351}
2352
2354{
2355 if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
2356 managerPrivate->networkCache->remove(url);
2357 } else if (cacheEnabled && cacheSaveDevice) {
2358 managerPrivate->networkCache->insert(cacheSaveDevice);
2359 }
2360 cacheSaveDevice = nullptr;
2361 cacheEnabled = false;
2362}
2363
2364QT_END_NAMESPACE
2365
2366#include "moc_qnetworkreplyhttpimpl_p.cpp"
The QNetworkCacheMetaData class provides cache information.
static QByteArray fromCookieList(const NetworkCookieList &cookies)
static QByteArray toHttpDate(const QDateTime &dt)
QNetworkCacheMetaData fetchCacheMetaData(const QNetworkCacheMetaData &metaData) const
void replySslConfigurationChanged(const QSslConfiguration &newSslConfiguration)
void onRedirected(const QUrl &redirectUrl, int httpStatus, int maxRedirectsRemainig)
QNetworkAccessManager::Operation getRedirectOperation(QNetworkAccessManager::Operation currentOp, int httpStatus)
void replyDownloadProgressSlot(qint64, qint64)
bool sendCacheContents(const QNetworkCacheMetaData &metaData)
void checkForRedirect(const int statusCode)
QNonContiguousByteDevice * createUploadByteDevice()
void emitReplyUploadProgress(qint64 bytesSent, qint64 bytesTotal)
void replySslErrors(const QList< QSslError > &, bool *, QList< QSslError > *)
void replyPreSharedKeyAuthenticationRequiredSlot(QSslPreSharedKeyAuthenticator *)
qint64 readData(char *, qint64) override
Reads up to maxSize bytes from the device into data, and returns the number of bytes read or -1 if an...
void setSslConfigurationImplementation(const QSslConfiguration &configuration) override
void abort() override
Aborts the operation immediately and closes any network connections still open.
void close() override
Closes this device for reading.
qint64 size() const override
For open random-access devices, this function returns the size of the device.
void abortImpl(QNetworkReply::NetworkError error)
void void void void void void void void void void void void void void void void void void void void void void void void void followRedirect()) protected void ignoreSslErrorsImplementation(const QList< QSslError > &errors) override
void sslConfigurationImplementation(QSslConfiguration &configuration) const override
qint64 bytesAvailable() const override
Returns the number of bytes that are available for reading.
bool isSequential() const override
\reimp
bool canReadLine() const override
Returns true if a complete line of data can be read from the device; otherwise returns false.
void setReadBufferSize(qint64 size) override
Sets the size of the read buffer to be size bytes.
\inmodule QtCore
The QSslPreSharedKeyAuthenticator class provides authentication data for pre shared keys (PSK) cipher...
static QByteArray cacheControlName()
static constexpr QLatin1StringView locationHeader() noexcept
static auto remapCustom(QNetworkAccessManager::Operation operation, const QNetworkRequest &req)
static auto caseInsensitiveCompare(QByteArrayView value)
static QByteArray rangeName()
static bool isHopByHop(QByteArrayView header)
static constexpr QByteArrayView bytesEqualPrefix() noexcept
static QHash< QByteArray, QByteArray > parseHttpOptionHeader(QByteArrayView header)