1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qnetworkreplyimpl_p.h"
43 #include "qnetworkaccessbackend_p.h"
44 #include "qnetworkcookie.h"
45 #include "qnetworkcookiejar.h"
46 #include "qabstractnetworkcache.h"
47 #include "QtCore/qcoreapplication.h"
48 #include "QtCore/qdatetime.h"
49 #include "QtNetwork/qsslconfiguration.h"
50 #include "QtNetwork/qnetworksession.h"
51 #include "qnetworkaccessmanager_p.h"
53 #include <QtCore/QCoreApplication>
55 Q_DECLARE_METATYPE(QSharedPointer<char>)
59 inline QNetworkReplyImplPrivate::QNetworkReplyImplPrivate()
60 : backend(0), outgoingData(0),
62 cacheEnabled(false), cacheSaveDevice(0),
63 notificationHandlingPaused(false),
64 bytesDownloaded(0), lastBytesDownloaded(-1), bytesUploaded(-1), preMigrationDownloaded(-1),
67 , downloadBufferReadPosition(0)
68 , downloadBufferCurrentSize(0)
69 , downloadBufferMaximumSize(0)
74 void QNetworkReplyImplPrivate::_q_startOperation()
76 Q_Q(QNetworkReplyImpl);
78 // ensure this function is only being called once
79 if (state == Working || state == Finished) {
80 qDebug("QNetworkReplyImpl::_q_startOperation was called more than once");
85 // note: if that method is called directly, it cannot happen that the backend is 0,
86 // because we just checked via a qobject_cast that we got a http backend (see
87 // QNetworkReplyImplPrivate::setup())
89 error(QNetworkReplyImpl::ProtocolUnknownError,
90 QCoreApplication::translate("QNetworkReply", "Protocol \"%1\" is unknown").arg(url.scheme())); // not really true!;
95 #ifndef QT_NO_BEARERMANAGEMENT
96 // Do not start background requests if they are not allowed by session policy
97 QSharedPointer<QNetworkSession> session(manager->d_func()->getNetworkSession());
98 QVariant isBackground = backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(false));
99 if (isBackground.toBool() && session && session->usagePolicies().testFlag(QNetworkSession::NoBackgroundTrafficPolicy)) {
100 error(QNetworkReply::BackgroundRequestNotAllowedError,
101 QCoreApplication::translate("QNetworkReply", "Background request not allowed."));
107 if (!backend->start()) {
108 #ifndef QT_NO_BEARERMANAGEMENT
109 // backend failed to start because the session state is not Connected.
110 // QNetworkAccessManager will call _q_startOperation again for us when the session
112 state = WaitingForSession;
115 QObject::connect(session.data(), SIGNAL(error(QNetworkSession::SessionError)),
116 q, SLOT(_q_networkSessionFailed()));
118 if (!session->isOpen()) {
119 session->setSessionProperty(QStringLiteral("ConnectInBackground"), isBackground);
123 qWarning("Backend is waiting for QNetworkSession to connect, but there is none!");
125 error(QNetworkReplyImpl::NetworkSessionFailedError,
126 QCoreApplication::translate("QNetworkReply", "Network session error."));
130 qWarning("Backend start failed");
132 error(QNetworkReplyImpl::UnknownNetworkError,
133 QCoreApplication::translate("QNetworkReply", "backend start error."));
139 #ifndef QT_NO_BEARERMANAGEMENT
141 //get notification of policy changes.
142 QObject::connect(session.data(), SIGNAL(usagePoliciesChanged(QNetworkSession::UsagePolicies)),
143 q, SLOT(_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies)));
147 // Start timer for progress notifications
148 downloadProgressSignalChoke.start();
150 if (backend && backend->isSynchronous()) {
152 q_func()->setFinished(true);
154 if (state != Finished) {
155 if (operation == QNetworkAccessManager::GetOperation)
156 pendingNotifications.append(NotifyDownstreamReadyWrite);
158 handleNotifications();
163 void QNetworkReplyImplPrivate::_q_copyReadyRead()
165 Q_Q(QNetworkReplyImpl);
166 if (state != Working)
168 if (!copyDevice || !q->isOpen())
171 // FIXME Optimize to use download buffer if it is a QBuffer.
172 // Needs to be done where sendCacheContents() (?) of HTTP is emitting
176 qint64 bytesToRead = nextDownstreamBlockSize();
177 if (bytesToRead == 0)
178 // we'll be called again, eventually
181 bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
183 byteData.resize(bytesToRead);
184 qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
185 if (bytesActuallyRead == -1) {
187 backendNotify(NotifyCopyFinished);
191 byteData.resize(bytesActuallyRead);
192 readBuffer.append(byteData);
194 if (!copyDevice->isSequential() && copyDevice->atEnd()) {
195 backendNotify(NotifyCopyFinished);
196 bytesDownloaded += bytesActuallyRead;
200 bytesDownloaded += bytesActuallyRead;
203 if (bytesDownloaded == lastBytesDownloaded) {
204 // we didn't read anything
208 lastBytesDownloaded = bytesDownloaded;
209 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
210 if (preMigrationDownloaded != Q_INT64_C(-1))
211 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
212 pauseNotificationHandling();
213 // emit readyRead before downloadProgress incase this will cause events to be
214 // processed and we get into a recursive call (as in QProgressDialog).
216 if (downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
217 downloadProgressSignalChoke.restart();
218 emit q->downloadProgress(bytesDownloaded,
219 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
221 resumeNotificationHandling();
224 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
229 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
231 Q_Q(QNetworkReplyImpl);
233 // make sure this is only called once, ever.
234 //_q_bufferOutgoingData may call it or the readChannelFinished emission
235 if (state != Buffering)
238 // disconnect signals
239 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
240 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
242 // finally, start the request
243 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
246 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
248 Q_Q(QNetworkReplyImpl);
250 if (!outgoingDataBuffer) {
251 // first call, create our buffer
252 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
254 QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
255 QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
258 qint64 bytesBuffered = 0;
259 qint64 bytesToBuffer = 0;
261 // read data into our buffer
263 bytesToBuffer = outgoingData->bytesAvailable();
264 // unknown? just try 2 kB, this also ensures we always try to read the EOF
265 if (bytesToBuffer <= 0)
266 bytesToBuffer = 2*1024;
268 char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
269 bytesBuffered = outgoingData->read(dst, bytesToBuffer);
271 if (bytesBuffered == -1) {
272 // EOF has been reached.
273 outgoingDataBuffer->chop(bytesToBuffer);
275 _q_bufferOutgoingDataFinished();
277 } else if (bytesBuffered == 0) {
278 // nothing read right now, just wait until we get called again
279 outgoingDataBuffer->chop(bytesToBuffer);
283 // don't break, try to read() again
284 outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
289 #ifndef QT_NO_BEARERMANAGEMENT
290 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
292 Q_Q(QNetworkReplyImpl);
294 if (manager.isNull())
297 QSharedPointer<QNetworkSession> session = manager->d_func()->getNetworkSession();
301 if (session->state() != QNetworkSession::Connected)
305 case QNetworkReplyImplPrivate::Buffering:
306 case QNetworkReplyImplPrivate::Working:
307 case QNetworkReplyImplPrivate::Reconnecting:
308 // Migrate existing downloads to new network connection.
311 case QNetworkReplyImplPrivate::WaitingForSession:
312 // Start waiting requests.
313 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
320 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
322 // Abort waiting and working replies.
323 if (state == WaitingForSession || state == Working) {
325 QSharedPointer<QNetworkSession> session(manager->d_func()->getNetworkSession());
328 errorStr = session->errorString();
330 errorStr = QCoreApplication::translate("QNetworkReply", "Network session error.");
331 error(QNetworkReplyImpl::NetworkSessionFailedError, errorStr);
336 void QNetworkReplyImplPrivate::_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies newPolicies)
338 if (backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute).toBool()) {
339 if (newPolicies & QNetworkSession::NoBackgroundTrafficPolicy) {
340 // Abort waiting and working replies.
341 if (state == WaitingForSession || state == Working) {
343 error(QNetworkReply::BackgroundRequestNotAllowedError,
344 QCoreApplication::translate("QNetworkReply", "Background request not allowed."));
347 // ### if backend->canResume(), then we could resume automatically, however no backend supports resuming
353 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
356 Q_Q(QNetworkReplyImpl);
363 q->QIODevice::open(QIODevice::ReadOnly);
364 // Internal code that does a HTTP reply for the synchronous Ajax
366 QVariant synchronousHttpAttribute = req.attribute(
367 static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute));
368 // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
369 // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
370 if (synchronousHttpAttribute.toBool() && outgoingData) {
371 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
372 qint64 previousDataSize = 0;
374 previousDataSize = outgoingDataBuffer->size();
375 outgoingDataBuffer->append(outgoingData->readAll());
376 } while (outgoingDataBuffer->size() != previousDataSize);
380 backend->setSynchronous(synchronousHttpAttribute.toBool());
383 if (outgoingData && backend && !backend->isSynchronous()) {
384 // there is data to be uploaded, e.g. HTTP POST.
386 if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) {
387 // backend does not need upload buffering or
388 // fixed size non-sequential
389 // just start the operation
390 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
392 bool bufferingDisallowed =
393 req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
396 if (bufferingDisallowed) {
397 // if a valid content-length header for the request was supplied, we can disable buffering
398 // if not, we will buffer anyway
399 if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) {
400 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
403 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
406 // _q_startOperation will be called when the buffering has finished.
408 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
412 // for HTTP, we want to send out the request as fast as possible to the network, without
413 // invoking methods in a QueuedConnection
415 if (backend && backend->isSynchronous()) {
418 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
421 if (backend && backend->isSynchronous())
424 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
429 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
431 Q_Q(QNetworkReplyImpl);
432 if (!pendingNotifications.contains(notification))
433 pendingNotifications.enqueue(notification);
435 if (pendingNotifications.size() == 1)
436 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
439 void QNetworkReplyImplPrivate::handleNotifications()
441 if (notificationHandlingPaused)
444 NotificationQueue current = pendingNotifications;
445 pendingNotifications.clear();
447 if (state != Working)
450 while (state == Working && !current.isEmpty()) {
451 InternalNotifications notification = current.dequeue();
452 switch (notification) {
453 case NotifyDownstreamReadyWrite:
457 backend->downstreamReadyWrite();
460 case NotifyCloseDownstreamChannel:
461 backend->closeDownstreamChannel();
464 case NotifyCopyFinished: {
465 QIODevice *dev = copyDevice;
467 backend->copyFinished(dev);
474 // Do not handle the notifications while we are emitting downloadProgress
476 void QNetworkReplyImplPrivate::pauseNotificationHandling()
478 notificationHandlingPaused = true;
481 // Resume notification handling
482 void QNetworkReplyImplPrivate::resumeNotificationHandling()
484 Q_Q(QNetworkReplyImpl);
485 notificationHandlingPaused = false;
486 if (pendingNotifications.size() >= 1)
487 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
490 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
494 return backend->networkCache();
497 void QNetworkReplyImplPrivate::createCache()
499 // check if we can save and if we're allowed to
501 || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool())
506 bool QNetworkReplyImplPrivate::isCachingEnabled() const
508 return (cacheEnabled && networkCache() != 0);
511 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
513 if (!enable && !cacheEnabled)
514 return; // nothing to do
515 if (enable && cacheEnabled)
516 return; // nothing to do either!
519 if (bytesDownloaded) {
520 // refuse to enable in this case
521 qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
527 // someone told us to turn on, then back off?
528 // ok... but you should make up your mind
529 qDebug("QNetworkReplyImpl: setCachingEnabled(true) called after setCachingEnabled(false) -- "
530 "backend %s probably needs to be fixed",
531 backend->metaObject()->className());
532 networkCache()->remove(url);
534 cacheEnabled = false;
538 void QNetworkReplyImplPrivate::completeCacheSave()
540 if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
541 networkCache()->remove(url);
542 } else if (cacheEnabled && cacheSaveDevice) {
543 networkCache()->insert(cacheSaveDevice);
546 cacheEnabled = false;
549 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
551 Q_Q(QNetworkReplyImpl);
552 bytesUploaded = bytesSent;
553 pauseNotificationHandling();
554 emit q->uploadProgress(bytesSent, bytesTotal);
555 resumeNotificationHandling();
559 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
561 enum { DesiredBufferSize = 32 * 1024 };
562 if (readBufferMaxSize == 0)
563 return DesiredBufferSize;
565 return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
568 void QNetworkReplyImplPrivate::initCacheSaveDevice()
570 Q_Q(QNetworkReplyImpl);
572 // The disk cache does not support partial content, so don't even try to
573 // save any such content into the cache.
574 if (q->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 206) {
575 cacheEnabled = false;
579 // save the meta data
580 QNetworkCacheMetaData metaData;
581 metaData.setUrl(url);
582 metaData = backend->fetchCacheMetaData(metaData);
584 // save the redirect request also in the cache
585 QVariant redirectionTarget = q->attribute(QNetworkRequest::RedirectionTargetAttribute);
586 if (redirectionTarget.isValid()) {
587 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
588 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
589 metaData.setAttributes(attributes);
592 cacheSaveDevice = networkCache()->prepare(metaData);
594 if (!cacheSaveDevice || (cacheSaveDevice && !cacheSaveDevice->isOpen())) {
595 if (cacheSaveDevice && !cacheSaveDevice->isOpen())
596 qCritical("QNetworkReplyImpl: network cache returned a device that is not open -- "
597 "class %s probably needs to be fixed",
598 networkCache()->metaObject()->className());
600 networkCache()->remove(url);
602 cacheEnabled = false;
606 // we received downstream data and send this to the cache
607 // and to our readBuffer (which in turn gets read by the user of QNetworkReply)
608 void QNetworkReplyImplPrivate::appendDownstreamData(QByteDataBuffer &data)
610 Q_Q(QNetworkReplyImpl);
614 if (cacheEnabled && !cacheSaveDevice) {
615 initCacheSaveDevice();
618 qint64 bytesWritten = 0;
619 for (int i = 0; i < data.bufferCount(); i++) {
620 QByteArray const &item = data[i];
623 cacheSaveDevice->write(item.constData(), item.size());
624 readBuffer.append(item);
626 bytesWritten += item.size();
630 bytesDownloaded += bytesWritten;
631 lastBytesDownloaded = bytesDownloaded;
633 appendDownstreamDataSignalEmissions();
636 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
638 Q_Q(QNetworkReplyImpl);
640 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
641 if (preMigrationDownloaded != Q_INT64_C(-1))
642 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
643 pauseNotificationHandling();
644 // important: At the point of this readyRead(), the data parameter list must be empty,
645 // else implicit sharing will trigger memcpy when the user is reading data!
647 // emit readyRead before downloadProgress incase this will cause events to be
648 // processed and we get into a recursive call (as in QProgressDialog).
649 if (downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
650 downloadProgressSignalChoke.restart();
651 emit q->downloadProgress(bytesDownloaded,
652 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
655 resumeNotificationHandling();
656 // do we still have room in the buffer?
657 if (nextDownstreamBlockSize() > 0)
658 backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
661 // this is used when it was fetched from the cache, right?
662 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
664 Q_Q(QNetworkReplyImpl);
668 // read until EOF from data
670 qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
671 "backend probly needs to be fixed");
676 q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
677 q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
683 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
690 qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
693 static void downloadBufferDeleter(char *ptr)
698 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
700 Q_Q(QNetworkReplyImpl);
702 if (!downloadBuffer) {
703 // We are requested to create it
704 // Check attribute() if allocating a buffer of that size can be allowed
705 QVariant bufferAllocationPolicy = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
706 if (bufferAllocationPolicy.isValid() && bufferAllocationPolicy.toLongLong() >= size) {
707 downloadBufferCurrentSize = 0;
708 downloadBufferMaximumSize = size;
709 downloadBuffer = new char[downloadBufferMaximumSize]; // throws if allocation fails
710 downloadBufferPointer = QSharedPointer<char>(downloadBuffer, downloadBufferDeleter);
712 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, QVariant::fromValue<QSharedPointer<char> > (downloadBufferPointer));
716 return downloadBuffer;
719 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
721 Q_Q(QNetworkReplyImpl);
723 downloadBufferPointer = sp;
724 downloadBuffer = downloadBufferPointer.data();
725 downloadBufferCurrentSize = 0;
726 downloadBufferMaximumSize = size;
727 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, QVariant::fromValue<QSharedPointer<char> > (downloadBufferPointer));
731 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
733 Q_Q(QNetworkReplyImpl);
737 if (cacheEnabled && !cacheSaveDevice)
738 initCacheSaveDevice();
740 if (cacheSaveDevice && bytesReceived == bytesTotal) {
741 // if (lastBytesDownloaded == -1)
742 // lastBytesDownloaded = 0;
743 // cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
745 // Write everything in one go if we use a download buffer. might be more performant.
746 cacheSaveDevice->write(downloadBuffer, bytesTotal);
749 bytesDownloaded = bytesReceived;
750 lastBytesDownloaded = bytesReceived;
752 downloadBufferCurrentSize = bytesReceived;
754 // Only emit readyRead when actual data is there
755 // emit readyRead before downloadProgress incase this will cause events to be
756 // processed and we get into a recursive call (as in QProgressDialog).
757 if (bytesDownloaded > 0)
759 if (downloadProgressSignalChoke.elapsed() >= progressSignalInterval) {
760 downloadProgressSignalChoke.restart();
761 emit q->downloadProgress(bytesDownloaded, bytesTotal);
765 void QNetworkReplyImplPrivate::finished()
767 Q_Q(QNetworkReplyImpl);
769 if (state == Finished || state == Aborted || state == WaitingForSession)
772 pauseNotificationHandling();
773 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
774 if (preMigrationDownloaded != Q_INT64_C(-1))
775 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
777 if (!manager.isNull()) {
778 #ifndef QT_NO_BEARERMANAGEMENT
779 QSharedPointer<QNetworkSession> session (manager->d_func()->getNetworkSession());
780 if (session && session->state() == QNetworkSession::Roaming &&
781 state == Working && errorCode != QNetworkReply::OperationCanceledError) {
782 // only content with a known size will fail with a temporary network failure error
783 if (!totalSize.isNull()) {
784 if (bytesDownloaded != totalSize) {
785 if (migrateBackend()) {
786 // either we are migrating or the request is finished/aborted
787 if (state == Reconnecting || state == WaitingForSession) {
788 resumeNotificationHandling();
789 return; // exit early if we are migrating.
792 error(QNetworkReply::TemporaryNetworkFailureError,
793 QNetworkReply::tr("Temporary network failure."));
800 resumeNotificationHandling();
803 q->setFinished(true);
805 pendingNotifications.clear();
807 pauseNotificationHandling();
808 if (totalSize.isNull() || totalSize == -1) {
809 emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
811 emit q->downloadProgress(bytesDownloaded, totalSize.toLongLong());
814 if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
815 emit q->uploadProgress(0, 0);
816 resumeNotificationHandling();
818 // if we don't know the total size of or we received everything save the cache
819 if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
822 // note: might not be a good idea, since users could decide to delete us
823 // which would delete the backend too...
824 // maybe we should protect the backend
825 pauseNotificationHandling();
826 emit q->readChannelFinished();
828 resumeNotificationHandling();
831 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
833 Q_Q(QNetworkReplyImpl);
834 // Can't set and emit multiple errors.
835 if (errorCode != QNetworkReply::NoError) {
836 qWarning( "QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.");
841 q->setErrorString(errorMessage);
843 // note: might not be a good idea, since users could decide to delete us
844 // which would delete the backend too...
845 // maybe we should protect the backend
849 void QNetworkReplyImplPrivate::metaDataChanged()
851 Q_Q(QNetworkReplyImpl);
852 // 1. do we have cookies?
853 // 2. are we allowed to set them?
854 if (cookedHeaders.contains(QNetworkRequest::SetCookieHeader) && !manager.isNull()
855 && (static_cast<QNetworkRequest::LoadControl>
856 (request.attribute(QNetworkRequest::CookieSaveControlAttribute,
857 QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic)) {
858 QList<QNetworkCookie> cookies =
859 qvariant_cast<QList<QNetworkCookie> >(cookedHeaders.value(QNetworkRequest::SetCookieHeader));
860 QNetworkCookieJar *jar = manager->cookieJar();
862 jar->setCookiesFromUrl(cookies, url);
864 emit q->metaDataChanged();
867 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
869 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
872 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
875 Q_Q(QNetworkReplyImpl);
876 emit q->sslErrors(errors);
882 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
883 : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
887 QNetworkReplyImpl::~QNetworkReplyImpl()
889 Q_D(QNetworkReplyImpl);
891 // This code removes the data from the cache if it was prematurely aborted.
892 // See QNetworkReplyImplPrivate::completeCacheSave(), we disable caching there after the cache
893 // save had been properly finished. So if it is still enabled it means we got deleted/aborted.
894 if (d->isCachingEnabled())
895 d->networkCache()->remove(url());
898 void QNetworkReplyImpl::abort()
900 Q_D(QNetworkReplyImpl);
901 if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
904 // stop both upload and download
906 disconnect(d->outgoingData, 0, this, 0);
908 disconnect(d->copyDevice, 0, this, 0);
910 QNetworkReply::close();
912 if (d->state != QNetworkReplyImplPrivate::Finished) {
913 // call finished which will emit signals
914 d->error(OperationCanceledError, tr("Operation canceled"));
915 if (d->state == QNetworkReplyImplPrivate::WaitingForSession)
916 d->state = QNetworkReplyImplPrivate::Working;
919 d->state = QNetworkReplyImplPrivate::Aborted;
921 // finished may access the backend
923 d->backend->deleteLater();
928 void QNetworkReplyImpl::close()
930 Q_D(QNetworkReplyImpl);
931 if (d->state == QNetworkReplyImplPrivate::Aborted ||
932 d->state == QNetworkReplyImplPrivate::Finished)
937 d->backend->closeDownstreamChannel();
939 disconnect(d->copyDevice, 0, this, 0);
941 QNetworkReply::close();
943 // call finished which will emit signals
944 d->error(OperationCanceledError, tr("Operation canceled"));
948 bool QNetworkReplyImpl::canReadLine () const
950 Q_D(const QNetworkReplyImpl);
951 return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
956 Returns the number of bytes available for reading with
957 QIODevice::read(). The number of bytes available may grow until
958 the finished() signal is emitted.
960 qint64 QNetworkReplyImpl::bytesAvailable() const
962 // Special case for the "zero copy" download buffer
963 Q_D(const QNetworkReplyImpl);
964 if (d->downloadBuffer) {
965 qint64 maxAvail = d->downloadBufferCurrentSize - d->downloadBufferReadPosition;
966 return QNetworkReply::bytesAvailable() + maxAvail;
969 return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
972 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
974 Q_D(QNetworkReplyImpl);
975 if (size > d->readBufferMaxSize &&
976 size > d->readBuffer.byteAmount())
977 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
979 QNetworkReply::setReadBufferSize(size);
982 d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
986 void QNetworkReplyImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
988 Q_D(const QNetworkReplyImpl);
990 d->backend->fetchSslConfiguration(configuration);
993 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
995 Q_D(QNetworkReplyImpl);
996 if (d->backend && !config.isNull())
997 d->backend->setSslConfiguration(config);
1000 void QNetworkReplyImpl::ignoreSslErrors()
1002 Q_D(QNetworkReplyImpl);
1004 d->backend->ignoreSslErrors();
1007 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
1009 Q_D(QNetworkReplyImpl);
1011 d->backend->ignoreSslErrors(errors);
1018 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
1020 Q_D(QNetworkReplyImpl);
1022 // Special case code if we have the "zero copy" download buffer
1023 if (d->downloadBuffer) {
1024 qint64 maxAvail = qMin<qint64>(d->downloadBufferCurrentSize - d->downloadBufferReadPosition, maxlen);
1026 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
1027 // FIXME what about "Aborted" state?
1028 memcpy(data, d->downloadBuffer + d->downloadBufferReadPosition, maxAvail);
1029 d->downloadBufferReadPosition += maxAvail;
1034 if (d->readBuffer.isEmpty())
1035 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
1036 // FIXME what about "Aborted" state?
1038 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
1040 // optimization for getChar()
1041 *data = d->readBuffer.getChar();
1045 maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
1046 return d->readBuffer.read(data, maxlen);
1050 \internal Reimplemented for internal purposes
1052 bool QNetworkReplyImpl::event(QEvent *e)
1054 if (e->type() == QEvent::NetworkReplyUpdated) {
1055 d_func()->handleNotifications();
1059 return QObject::event(e);
1063 Migrates the backend of the QNetworkReply to a new network connection if required. Returns
1064 true if the reply is migrated or it is not required; otherwise returns false.
1066 bool QNetworkReplyImplPrivate::migrateBackend()
1068 Q_Q(QNetworkReplyImpl);
1070 // Network reply is already finished or aborted, don't need to migrate.
1071 if (state == Finished || state == Aborted)
1074 // Request has outgoing data, not migrating.
1078 // Request is serviced from the cache, don't need to migrate.
1082 // Backend does not support resuming download.
1083 if (!backend->canResume())
1086 state = QNetworkReplyImplPrivate::Reconnecting;
1093 cookedHeaders.clear();
1096 preMigrationDownloaded = bytesDownloaded;
1098 backend = manager->d_func()->findBackend(operation, request);
1101 backend->setParent(q);
1102 backend->reply = this;
1103 backend->setResumeOffset(bytesDownloaded);
1107 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1109 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1110 #endif // QT_NO_HTTP
1115 #ifndef QT_NO_BEARERMANAGEMENT
1116 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1117 const QNetworkRequest &req,
1118 QNetworkAccessManager::Operation op)
1119 : QNetworkReply(parent)
1125 qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1127 QString msg = QCoreApplication::translate("QNetworkAccessManager",
1128 "Network access is disabled.");
1129 setError(UnknownNetworkError, msg);
1131 QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1132 Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1133 QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1136 QDisabledNetworkReply::~QDisabledNetworkReply()
1143 #include "moc_qnetworkreplyimpl_p.cpp"