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()->networkSession);
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."));
140 //get notification of policy changes.
141 QObject::connect(session.data(), SIGNAL(usagePoliciesChanged(QNetworkSession::UsagePolicies)),
142 q, SLOT(_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies)));
145 if (backend && backend->isSynchronous()) {
147 q_func()->setFinished(true);
149 if (state != Finished) {
150 if (operation == QNetworkAccessManager::GetOperation)
151 pendingNotifications.append(NotifyDownstreamReadyWrite);
153 handleNotifications();
158 void QNetworkReplyImplPrivate::_q_copyReadyRead()
160 Q_Q(QNetworkReplyImpl);
161 if (state != Working)
163 if (!copyDevice || !q->isOpen())
166 // FIXME Optimize to use download buffer if it is a QBuffer.
167 // Needs to be done where sendCacheContents() (?) of HTTP is emitting
171 qint64 bytesToRead = nextDownstreamBlockSize();
172 if (bytesToRead == 0)
173 // we'll be called again, eventually
176 bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
178 byteData.resize(bytesToRead);
179 qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
180 if (bytesActuallyRead == -1) {
182 backendNotify(NotifyCopyFinished);
186 byteData.resize(bytesActuallyRead);
187 readBuffer.append(byteData);
189 if (!copyDevice->isSequential() && copyDevice->atEnd()) {
190 backendNotify(NotifyCopyFinished);
191 bytesDownloaded += bytesActuallyRead;
195 bytesDownloaded += bytesActuallyRead;
198 if (bytesDownloaded == lastBytesDownloaded) {
199 // we didn't read anything
203 lastBytesDownloaded = bytesDownloaded;
204 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
205 if (preMigrationDownloaded != Q_INT64_C(-1))
206 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
207 pauseNotificationHandling();
208 // emit readyRead before downloadProgress incase this will cause events to be
209 // processed and we get into a recursive call (as in QProgressDialog).
211 emit q->downloadProgress(bytesDownloaded,
212 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
213 resumeNotificationHandling();
216 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
221 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
223 Q_Q(QNetworkReplyImpl);
225 // make sure this is only called once, ever.
226 //_q_bufferOutgoingData may call it or the readChannelFinished emission
227 if (state != Buffering)
230 // disconnect signals
231 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
232 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
234 // finally, start the request
235 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
238 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
240 Q_Q(QNetworkReplyImpl);
242 if (!outgoingDataBuffer) {
243 // first call, create our buffer
244 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
246 QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
247 QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
250 qint64 bytesBuffered = 0;
251 qint64 bytesToBuffer = 0;
253 // read data into our buffer
255 bytesToBuffer = outgoingData->bytesAvailable();
256 // unknown? just try 2 kB, this also ensures we always try to read the EOF
257 if (bytesToBuffer <= 0)
258 bytesToBuffer = 2*1024;
260 char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
261 bytesBuffered = outgoingData->read(dst, bytesToBuffer);
263 if (bytesBuffered == -1) {
264 // EOF has been reached.
265 outgoingDataBuffer->chop(bytesToBuffer);
267 _q_bufferOutgoingDataFinished();
269 } else if (bytesBuffered == 0) {
270 // nothing read right now, just wait until we get called again
271 outgoingDataBuffer->chop(bytesToBuffer);
275 // don't break, try to read() again
276 outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
281 #ifndef QT_NO_BEARERMANAGEMENT
282 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
284 Q_Q(QNetworkReplyImpl);
286 if (manager.isNull())
289 QNetworkSession *session = manager->d_func()->networkSession.data();
293 if (session->state() != QNetworkSession::Connected)
297 case QNetworkReplyImplPrivate::Buffering:
298 case QNetworkReplyImplPrivate::Working:
299 case QNetworkReplyImplPrivate::Reconnecting:
300 // Migrate existing downloads to new network connection.
303 case QNetworkReplyImplPrivate::WaitingForSession:
304 // Start waiting requests.
305 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
312 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
314 // Abort waiting and working replies.
315 if (state == WaitingForSession || state == Working) {
317 QSharedPointer<QNetworkSession> session(manager->d_func()->networkSession);
320 errorStr = session->errorString();
322 errorStr = QCoreApplication::translate("QNetworkReply", "Network session error.");
323 error(QNetworkReplyImpl::NetworkSessionFailedError, errorStr);
328 void QNetworkReplyImplPrivate::_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies newPolicies)
330 if (backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute).toBool()) {
331 if (newPolicies & QNetworkSession::NoBackgroundTrafficPolicy) {
332 // Abort waiting and working replies.
333 if (state == WaitingForSession || state == Working) {
335 error(QNetworkReply::BackgroundRequestNotAllowedError,
336 QCoreApplication::translate("QNetworkReply", "Background request not allowed."));
339 // ### if backend->canResume(), then we could resume automatically, however no backend supports resuming
345 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
348 Q_Q(QNetworkReplyImpl);
355 q->QIODevice::open(QIODevice::ReadOnly);
356 // Internal code that does a HTTP reply for the synchronous Ajax
358 QVariant synchronousHttpAttribute = req.attribute(
359 static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute));
360 // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
361 // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
362 if (synchronousHttpAttribute.toBool() && outgoingData) {
363 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
364 qint64 previousDataSize = 0;
366 previousDataSize = outgoingDataBuffer->size();
367 outgoingDataBuffer->append(outgoingData->readAll());
368 } while (outgoingDataBuffer->size() != previousDataSize);
372 backend->setSynchronous(synchronousHttpAttribute.toBool());
375 if (outgoingData && backend && !backend->isSynchronous()) {
376 // there is data to be uploaded, e.g. HTTP POST.
378 if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) {
379 // backend does not need upload buffering or
380 // fixed size non-sequential
381 // just start the operation
382 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
384 bool bufferingDisallowed =
385 req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
388 if (bufferingDisallowed) {
389 // if a valid content-length header for the request was supplied, we can disable buffering
390 // if not, we will buffer anyway
391 if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) {
392 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
395 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
398 // _q_startOperation will be called when the buffering has finished.
400 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
404 // for HTTP, we want to send out the request as fast as possible to the network, without
405 // invoking methods in a QueuedConnection
407 if (backend && backend->isSynchronous()) {
410 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
413 if (backend && backend->isSynchronous())
416 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
421 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
423 Q_Q(QNetworkReplyImpl);
424 if (!pendingNotifications.contains(notification))
425 pendingNotifications.enqueue(notification);
427 if (pendingNotifications.size() == 1)
428 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
431 void QNetworkReplyImplPrivate::handleNotifications()
433 if (notificationHandlingPaused)
436 NotificationQueue current = pendingNotifications;
437 pendingNotifications.clear();
439 if (state != Working)
442 while (state == Working && !current.isEmpty()) {
443 InternalNotifications notification = current.dequeue();
444 switch (notification) {
445 case NotifyDownstreamReadyWrite:
449 backend->downstreamReadyWrite();
452 case NotifyCloseDownstreamChannel:
453 backend->closeDownstreamChannel();
456 case NotifyCopyFinished: {
457 QIODevice *dev = copyDevice;
459 backend->copyFinished(dev);
466 // Do not handle the notifications while we are emitting downloadProgress
468 void QNetworkReplyImplPrivate::pauseNotificationHandling()
470 notificationHandlingPaused = true;
473 // Resume notification handling
474 void QNetworkReplyImplPrivate::resumeNotificationHandling()
476 Q_Q(QNetworkReplyImpl);
477 notificationHandlingPaused = false;
478 if (pendingNotifications.size() >= 1)
479 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
482 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
486 return backend->networkCache();
489 void QNetworkReplyImplPrivate::createCache()
491 // check if we can save and if we're allowed to
493 || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool())
498 bool QNetworkReplyImplPrivate::isCachingEnabled() const
500 return (cacheEnabled && networkCache() != 0);
503 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
505 if (!enable && !cacheEnabled)
506 return; // nothing to do
507 if (enable && cacheEnabled)
508 return; // nothing to do either!
511 if (bytesDownloaded) {
512 // refuse to enable in this case
513 qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
519 // someone told us to turn on, then back off?
520 // ok... but you should make up your mind
521 qDebug("QNetworkReplyImpl: setCachingEnabled(true) called after setCachingEnabled(false) -- "
522 "backend %s probably needs to be fixed",
523 backend->metaObject()->className());
524 networkCache()->remove(url);
526 cacheEnabled = false;
530 void QNetworkReplyImplPrivate::completeCacheSave()
532 if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
533 networkCache()->remove(url);
534 } else if (cacheEnabled && cacheSaveDevice) {
535 networkCache()->insert(cacheSaveDevice);
538 cacheEnabled = false;
541 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
543 Q_Q(QNetworkReplyImpl);
544 bytesUploaded = bytesSent;
545 pauseNotificationHandling();
546 emit q->uploadProgress(bytesSent, bytesTotal);
547 resumeNotificationHandling();
551 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
553 enum { DesiredBufferSize = 32 * 1024 };
554 if (readBufferMaxSize == 0)
555 return DesiredBufferSize;
557 return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
560 void QNetworkReplyImplPrivate::initCacheSaveDevice()
562 Q_Q(QNetworkReplyImpl);
564 // The disk cache does not support partial content, so don't even try to
565 // save any such content into the cache.
566 if (q->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 206) {
567 cacheEnabled = false;
571 // save the meta data
572 QNetworkCacheMetaData metaData;
573 metaData.setUrl(url);
574 metaData = backend->fetchCacheMetaData(metaData);
576 // save the redirect request also in the cache
577 QVariant redirectionTarget = q->attribute(QNetworkRequest::RedirectionTargetAttribute);
578 if (redirectionTarget.isValid()) {
579 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
580 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
581 metaData.setAttributes(attributes);
584 cacheSaveDevice = networkCache()->prepare(metaData);
586 if (!cacheSaveDevice || (cacheSaveDevice && !cacheSaveDevice->isOpen())) {
587 if (cacheSaveDevice && !cacheSaveDevice->isOpen())
588 qCritical("QNetworkReplyImpl: network cache returned a device that is not open -- "
589 "class %s probably needs to be fixed",
590 networkCache()->metaObject()->className());
592 networkCache()->remove(url);
594 cacheEnabled = false;
598 // we received downstream data and send this to the cache
599 // and to our readBuffer (which in turn gets read by the user of QNetworkReply)
600 void QNetworkReplyImplPrivate::appendDownstreamData(QByteDataBuffer &data)
602 Q_Q(QNetworkReplyImpl);
606 if (cacheEnabled && !cacheSaveDevice) {
607 initCacheSaveDevice();
610 qint64 bytesWritten = 0;
611 for (int i = 0; i < data.bufferCount(); i++) {
612 QByteArray const &item = data[i];
615 cacheSaveDevice->write(item.constData(), item.size());
616 readBuffer.append(item);
618 bytesWritten += item.size();
622 bytesDownloaded += bytesWritten;
623 lastBytesDownloaded = bytesDownloaded;
625 appendDownstreamDataSignalEmissions();
628 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
630 Q_Q(QNetworkReplyImpl);
632 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
633 if (preMigrationDownloaded != Q_INT64_C(-1))
634 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
635 pauseNotificationHandling();
636 // important: At the point of this readyRead(), the data parameter list must be empty,
637 // else implicit sharing will trigger memcpy when the user is reading data!
639 // emit readyRead before downloadProgress incase this will cause events to be
640 // processed and we get into a recursive call (as in QProgressDialog).
641 emit q->downloadProgress(bytesDownloaded,
642 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
644 resumeNotificationHandling();
645 // do we still have room in the buffer?
646 if (nextDownstreamBlockSize() > 0)
647 backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
650 // this is used when it was fetched from the cache, right?
651 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
653 Q_Q(QNetworkReplyImpl);
657 // read until EOF from data
659 qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
660 "backend probly needs to be fixed");
665 q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
666 q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
672 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
679 qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
682 static void downloadBufferDeleter(char *ptr)
687 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
689 Q_Q(QNetworkReplyImpl);
691 if (!downloadBuffer) {
692 // We are requested to create it
693 // Check attribute() if allocating a buffer of that size can be allowed
694 QVariant bufferAllocationPolicy = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
695 if (bufferAllocationPolicy.isValid() && bufferAllocationPolicy.toLongLong() >= size) {
696 downloadBufferCurrentSize = 0;
697 downloadBufferMaximumSize = size;
698 downloadBuffer = new char[downloadBufferMaximumSize]; // throws if allocation fails
699 downloadBufferPointer = QSharedPointer<char>(downloadBuffer, downloadBufferDeleter);
701 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, QVariant::fromValue<QSharedPointer<char> > (downloadBufferPointer));
705 return downloadBuffer;
708 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
710 Q_Q(QNetworkReplyImpl);
712 downloadBufferPointer = sp;
713 downloadBuffer = downloadBufferPointer.data();
714 downloadBufferCurrentSize = 0;
715 downloadBufferMaximumSize = size;
716 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, QVariant::fromValue<QSharedPointer<char> > (downloadBufferPointer));
720 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
722 Q_Q(QNetworkReplyImpl);
726 if (cacheEnabled && !cacheSaveDevice)
727 initCacheSaveDevice();
729 if (cacheSaveDevice && bytesReceived == bytesTotal) {
730 // if (lastBytesDownloaded == -1)
731 // lastBytesDownloaded = 0;
732 // cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
734 // Write everything in one go if we use a download buffer. might be more performant.
735 cacheSaveDevice->write(downloadBuffer, bytesTotal);
738 bytesDownloaded = bytesReceived;
739 lastBytesDownloaded = bytesReceived;
741 downloadBufferCurrentSize = bytesReceived;
743 // Only emit readyRead when actual data is there
744 // emit readyRead before downloadProgress incase this will cause events to be
745 // processed and we get into a recursive call (as in QProgressDialog).
746 if (bytesDownloaded > 0)
748 emit q->downloadProgress(bytesDownloaded, bytesTotal);
751 void QNetworkReplyImplPrivate::finished()
753 Q_Q(QNetworkReplyImpl);
755 if (state == Finished || state == Aborted || state == WaitingForSession)
758 pauseNotificationHandling();
759 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
760 if (preMigrationDownloaded != Q_INT64_C(-1))
761 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
763 if (!manager.isNull()) {
764 #ifndef QT_NO_BEARERMANAGEMENT
765 QNetworkSession *session = manager->d_func()->networkSession.data();
766 if (session && session->state() == QNetworkSession::Roaming &&
767 state == Working && errorCode != QNetworkReply::OperationCanceledError) {
768 // only content with a known size will fail with a temporary network failure error
769 if (!totalSize.isNull()) {
770 if (bytesDownloaded != totalSize) {
771 if (migrateBackend()) {
772 // either we are migrating or the request is finished/aborted
773 if (state == Reconnecting || state == WaitingForSession) {
774 resumeNotificationHandling();
775 return; // exit early if we are migrating.
778 error(QNetworkReply::TemporaryNetworkFailureError,
779 QNetworkReply::tr("Temporary network failure."));
786 resumeNotificationHandling();
789 q->setFinished(true);
791 pendingNotifications.clear();
793 pauseNotificationHandling();
794 if (totalSize.isNull() || totalSize == -1) {
795 emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
798 if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
799 emit q->uploadProgress(0, 0);
800 resumeNotificationHandling();
802 // if we don't know the total size of or we received everything save the cache
803 if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
806 // note: might not be a good idea, since users could decide to delete us
807 // which would delete the backend too...
808 // maybe we should protect the backend
809 pauseNotificationHandling();
810 emit q->readChannelFinished();
812 resumeNotificationHandling();
815 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
817 Q_Q(QNetworkReplyImpl);
818 // Can't set and emit multiple errors.
819 if (errorCode != QNetworkReply::NoError) {
820 qWarning( "QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.");
825 q->setErrorString(errorMessage);
827 // note: might not be a good idea, since users could decide to delete us
828 // which would delete the backend too...
829 // maybe we should protect the backend
833 void QNetworkReplyImplPrivate::metaDataChanged()
835 Q_Q(QNetworkReplyImpl);
836 // 1. do we have cookies?
837 // 2. are we allowed to set them?
838 if (cookedHeaders.contains(QNetworkRequest::SetCookieHeader) && !manager.isNull()
839 && (static_cast<QNetworkRequest::LoadControl>
840 (request.attribute(QNetworkRequest::CookieSaveControlAttribute,
841 QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic)) {
842 QList<QNetworkCookie> cookies =
843 qvariant_cast<QList<QNetworkCookie> >(cookedHeaders.value(QNetworkRequest::SetCookieHeader));
844 QNetworkCookieJar *jar = manager->cookieJar();
846 jar->setCookiesFromUrl(cookies, url);
848 emit q->metaDataChanged();
851 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
853 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
856 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
859 Q_Q(QNetworkReplyImpl);
860 emit q->sslErrors(errors);
866 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
867 : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
871 QNetworkReplyImpl::~QNetworkReplyImpl()
873 Q_D(QNetworkReplyImpl);
875 // This code removes the data from the cache if it was prematurely aborted.
876 // See QNetworkReplyImplPrivate::completeCacheSave(), we disable caching there after the cache
877 // save had been properly finished. So if it is still enabled it means we got deleted/aborted.
878 if (d->isCachingEnabled())
879 d->networkCache()->remove(url());
882 void QNetworkReplyImpl::abort()
884 Q_D(QNetworkReplyImpl);
885 if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
888 // stop both upload and download
890 disconnect(d->outgoingData, 0, this, 0);
892 disconnect(d->copyDevice, 0, this, 0);
894 QNetworkReply::close();
896 if (d->state != QNetworkReplyImplPrivate::Finished) {
897 // call finished which will emit signals
898 d->error(OperationCanceledError, tr("Operation canceled"));
899 if (d->state == QNetworkReplyImplPrivate::WaitingForSession)
900 d->state = QNetworkReplyImplPrivate::Working;
903 d->state = QNetworkReplyImplPrivate::Aborted;
905 // finished may access the backend
907 d->backend->deleteLater();
912 void QNetworkReplyImpl::close()
914 Q_D(QNetworkReplyImpl);
915 if (d->state == QNetworkReplyImplPrivate::Aborted ||
916 d->state == QNetworkReplyImplPrivate::Finished)
921 d->backend->closeDownstreamChannel();
923 disconnect(d->copyDevice, 0, this, 0);
925 QNetworkReply::close();
927 // call finished which will emit signals
928 d->error(OperationCanceledError, tr("Operation canceled"));
932 bool QNetworkReplyImpl::canReadLine () const
934 Q_D(const QNetworkReplyImpl);
935 return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
940 Returns the number of bytes available for reading with
941 QIODevice::read(). The number of bytes available may grow until
942 the finished() signal is emitted.
944 qint64 QNetworkReplyImpl::bytesAvailable() const
946 // Special case for the "zero copy" download buffer
947 Q_D(const QNetworkReplyImpl);
948 if (d->downloadBuffer) {
949 qint64 maxAvail = d->downloadBufferCurrentSize - d->downloadBufferReadPosition;
950 return QNetworkReply::bytesAvailable() + maxAvail;
953 return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
956 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
958 Q_D(QNetworkReplyImpl);
959 if (size > d->readBufferMaxSize &&
960 size > d->readBuffer.byteAmount())
961 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
963 QNetworkReply::setReadBufferSize(size);
966 d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
970 void QNetworkReplyImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
972 Q_D(const QNetworkReplyImpl);
974 d->backend->fetchSslConfiguration(configuration);
977 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
979 Q_D(QNetworkReplyImpl);
980 if (d->backend && !config.isNull())
981 d->backend->setSslConfiguration(config);
984 void QNetworkReplyImpl::ignoreSslErrors()
986 Q_D(QNetworkReplyImpl);
988 d->backend->ignoreSslErrors();
991 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
993 Q_D(QNetworkReplyImpl);
995 d->backend->ignoreSslErrors(errors);
1002 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
1004 Q_D(QNetworkReplyImpl);
1006 // Special case code if we have the "zero copy" download buffer
1007 if (d->downloadBuffer) {
1008 qint64 maxAvail = qMin<qint64>(d->downloadBufferCurrentSize - d->downloadBufferReadPosition, maxlen);
1010 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
1011 // FIXME what about "Aborted" state?
1012 memcpy(data, d->downloadBuffer + d->downloadBufferReadPosition, maxAvail);
1013 d->downloadBufferReadPosition += maxAvail;
1018 if (d->readBuffer.isEmpty())
1019 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
1020 // FIXME what about "Aborted" state?
1022 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
1024 // optimization for getChar()
1025 *data = d->readBuffer.getChar();
1029 maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
1030 return d->readBuffer.read(data, maxlen);
1034 \internal Reimplemented for internal purposes
1036 bool QNetworkReplyImpl::event(QEvent *e)
1038 if (e->type() == QEvent::NetworkReplyUpdated) {
1039 d_func()->handleNotifications();
1043 return QObject::event(e);
1047 Migrates the backend of the QNetworkReply to a new network connection if required. Returns
1048 true if the reply is migrated or it is not required; otherwise returns false.
1050 bool QNetworkReplyImplPrivate::migrateBackend()
1052 Q_Q(QNetworkReplyImpl);
1054 // Network reply is already finished or aborted, don't need to migrate.
1055 if (state == Finished || state == Aborted)
1058 // Request has outgoing data, not migrating.
1062 // Request is serviced from the cache, don't need to migrate.
1066 // Backend does not support resuming download.
1067 if (!backend->canResume())
1070 state = QNetworkReplyImplPrivate::Reconnecting;
1077 cookedHeaders.clear();
1080 preMigrationDownloaded = bytesDownloaded;
1082 backend = manager->d_func()->findBackend(operation, request);
1085 backend->setParent(q);
1086 backend->reply = this;
1087 backend->setResumeOffset(bytesDownloaded);
1091 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1093 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1094 #endif // QT_NO_HTTP
1099 #ifndef QT_NO_BEARERMANAGEMENT
1100 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1101 const QNetworkRequest &req,
1102 QNetworkAccessManager::Operation op)
1103 : QNetworkReply(parent)
1109 qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1111 QString msg = QCoreApplication::translate("QNetworkAccessManager",
1112 "Network access is disabled.");
1113 setError(UnknownNetworkError, msg);
1115 QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1116 Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1117 QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1120 QDisabledNetworkReply::~QDisabledNetworkReply()
1127 #include "moc_qnetworkreplyimpl_p.cpp"