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."));
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 if (backend && backend->isSynchronous()) {
149 q_func()->setFinished(true);
151 if (state != Finished) {
152 if (operation == QNetworkAccessManager::GetOperation)
153 pendingNotifications.append(NotifyDownstreamReadyWrite);
155 handleNotifications();
160 void QNetworkReplyImplPrivate::_q_copyReadyRead()
162 Q_Q(QNetworkReplyImpl);
163 if (state != Working)
165 if (!copyDevice || !q->isOpen())
168 // FIXME Optimize to use download buffer if it is a QBuffer.
169 // Needs to be done where sendCacheContents() (?) of HTTP is emitting
173 qint64 bytesToRead = nextDownstreamBlockSize();
174 if (bytesToRead == 0)
175 // we'll be called again, eventually
178 bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
180 byteData.resize(bytesToRead);
181 qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
182 if (bytesActuallyRead == -1) {
184 backendNotify(NotifyCopyFinished);
188 byteData.resize(bytesActuallyRead);
189 readBuffer.append(byteData);
191 if (!copyDevice->isSequential() && copyDevice->atEnd()) {
192 backendNotify(NotifyCopyFinished);
193 bytesDownloaded += bytesActuallyRead;
197 bytesDownloaded += bytesActuallyRead;
200 if (bytesDownloaded == lastBytesDownloaded) {
201 // we didn't read anything
205 lastBytesDownloaded = bytesDownloaded;
206 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
207 if (preMigrationDownloaded != Q_INT64_C(-1))
208 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
209 pauseNotificationHandling();
210 // emit readyRead before downloadProgress incase this will cause events to be
211 // processed and we get into a recursive call (as in QProgressDialog).
213 emit q->downloadProgress(bytesDownloaded,
214 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
215 resumeNotificationHandling();
218 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
223 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
225 Q_Q(QNetworkReplyImpl);
227 // make sure this is only called once, ever.
228 //_q_bufferOutgoingData may call it or the readChannelFinished emission
229 if (state != Buffering)
232 // disconnect signals
233 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
234 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
236 // finally, start the request
237 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
240 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
242 Q_Q(QNetworkReplyImpl);
244 if (!outgoingDataBuffer) {
245 // first call, create our buffer
246 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
248 QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
249 QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
252 qint64 bytesBuffered = 0;
253 qint64 bytesToBuffer = 0;
255 // read data into our buffer
257 bytesToBuffer = outgoingData->bytesAvailable();
258 // unknown? just try 2 kB, this also ensures we always try to read the EOF
259 if (bytesToBuffer <= 0)
260 bytesToBuffer = 2*1024;
262 char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
263 bytesBuffered = outgoingData->read(dst, bytesToBuffer);
265 if (bytesBuffered == -1) {
266 // EOF has been reached.
267 outgoingDataBuffer->chop(bytesToBuffer);
269 _q_bufferOutgoingDataFinished();
271 } else if (bytesBuffered == 0) {
272 // nothing read right now, just wait until we get called again
273 outgoingDataBuffer->chop(bytesToBuffer);
277 // don't break, try to read() again
278 outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
283 #ifndef QT_NO_BEARERMANAGEMENT
284 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
286 Q_Q(QNetworkReplyImpl);
288 if (manager.isNull())
291 QNetworkSession *session = manager->d_func()->networkSession.data();
295 if (session->state() != QNetworkSession::Connected)
299 case QNetworkReplyImplPrivate::Buffering:
300 case QNetworkReplyImplPrivate::Working:
301 case QNetworkReplyImplPrivate::Reconnecting:
302 // Migrate existing downloads to new network connection.
305 case QNetworkReplyImplPrivate::WaitingForSession:
306 // Start waiting requests.
307 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
314 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
316 // Abort waiting and working replies.
317 if (state == WaitingForSession || state == Working) {
319 QSharedPointer<QNetworkSession> session(manager->d_func()->networkSession);
322 errorStr = session->errorString();
324 errorStr = QCoreApplication::translate("QNetworkReply", "Network session error.");
325 error(QNetworkReplyImpl::NetworkSessionFailedError, errorStr);
330 void QNetworkReplyImplPrivate::_q_networkSessionUsagePoliciesChanged(QNetworkSession::UsagePolicies newPolicies)
332 if (backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute).toBool()) {
333 if (newPolicies & QNetworkSession::NoBackgroundTrafficPolicy) {
334 // Abort waiting and working replies.
335 if (state == WaitingForSession || state == Working) {
337 error(QNetworkReply::BackgroundRequestNotAllowedError,
338 QCoreApplication::translate("QNetworkReply", "Background request not allowed."));
341 // ### if backend->canResume(), then we could resume automatically, however no backend supports resuming
347 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
350 Q_Q(QNetworkReplyImpl);
357 q->QIODevice::open(QIODevice::ReadOnly);
358 // Internal code that does a HTTP reply for the synchronous Ajax
360 QVariant synchronousHttpAttribute = req.attribute(
361 static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute));
362 // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
363 // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
364 if (synchronousHttpAttribute.toBool() && outgoingData) {
365 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
366 qint64 previousDataSize = 0;
368 previousDataSize = outgoingDataBuffer->size();
369 outgoingDataBuffer->append(outgoingData->readAll());
370 } while (outgoingDataBuffer->size() != previousDataSize);
374 backend->setSynchronous(synchronousHttpAttribute.toBool());
377 if (outgoingData && backend && !backend->isSynchronous()) {
378 // there is data to be uploaded, e.g. HTTP POST.
380 if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) {
381 // backend does not need upload buffering or
382 // fixed size non-sequential
383 // just start the operation
384 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
386 bool bufferingDisallowed =
387 req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
390 if (bufferingDisallowed) {
391 // if a valid content-length header for the request was supplied, we can disable buffering
392 // if not, we will buffer anyway
393 if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) {
394 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
397 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
400 // _q_startOperation will be called when the buffering has finished.
402 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
406 // for HTTP, we want to send out the request as fast as possible to the network, without
407 // invoking methods in a QueuedConnection
409 if (backend && backend->isSynchronous()) {
412 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
415 if (backend && backend->isSynchronous())
418 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
423 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
425 Q_Q(QNetworkReplyImpl);
426 if (!pendingNotifications.contains(notification))
427 pendingNotifications.enqueue(notification);
429 if (pendingNotifications.size() == 1)
430 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
433 void QNetworkReplyImplPrivate::handleNotifications()
435 if (notificationHandlingPaused)
438 NotificationQueue current = pendingNotifications;
439 pendingNotifications.clear();
441 if (state != Working)
444 while (state == Working && !current.isEmpty()) {
445 InternalNotifications notification = current.dequeue();
446 switch (notification) {
447 case NotifyDownstreamReadyWrite:
451 backend->downstreamReadyWrite();
454 case NotifyCloseDownstreamChannel:
455 backend->closeDownstreamChannel();
458 case NotifyCopyFinished: {
459 QIODevice *dev = copyDevice;
461 backend->copyFinished(dev);
468 // Do not handle the notifications while we are emitting downloadProgress
470 void QNetworkReplyImplPrivate::pauseNotificationHandling()
472 notificationHandlingPaused = true;
475 // Resume notification handling
476 void QNetworkReplyImplPrivate::resumeNotificationHandling()
478 Q_Q(QNetworkReplyImpl);
479 notificationHandlingPaused = false;
480 if (pendingNotifications.size() >= 1)
481 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
484 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
488 return backend->networkCache();
491 void QNetworkReplyImplPrivate::createCache()
493 // check if we can save and if we're allowed to
495 || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool())
500 bool QNetworkReplyImplPrivate::isCachingEnabled() const
502 return (cacheEnabled && networkCache() != 0);
505 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
507 if (!enable && !cacheEnabled)
508 return; // nothing to do
509 if (enable && cacheEnabled)
510 return; // nothing to do either!
513 if (bytesDownloaded) {
514 // refuse to enable in this case
515 qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
521 // someone told us to turn on, then back off?
522 // ok... but you should make up your mind
523 qDebug("QNetworkReplyImpl: setCachingEnabled(true) called after setCachingEnabled(false) -- "
524 "backend %s probably needs to be fixed",
525 backend->metaObject()->className());
526 networkCache()->remove(url);
528 cacheEnabled = false;
532 void QNetworkReplyImplPrivate::completeCacheSave()
534 if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
535 networkCache()->remove(url);
536 } else if (cacheEnabled && cacheSaveDevice) {
537 networkCache()->insert(cacheSaveDevice);
540 cacheEnabled = false;
543 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
545 Q_Q(QNetworkReplyImpl);
546 bytesUploaded = bytesSent;
547 pauseNotificationHandling();
548 emit q->uploadProgress(bytesSent, bytesTotal);
549 resumeNotificationHandling();
553 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
555 enum { DesiredBufferSize = 32 * 1024 };
556 if (readBufferMaxSize == 0)
557 return DesiredBufferSize;
559 return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
562 void QNetworkReplyImplPrivate::initCacheSaveDevice()
564 Q_Q(QNetworkReplyImpl);
566 // The disk cache does not support partial content, so don't even try to
567 // save any such content into the cache.
568 if (q->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 206) {
569 cacheEnabled = false;
573 // save the meta data
574 QNetworkCacheMetaData metaData;
575 metaData.setUrl(url);
576 metaData = backend->fetchCacheMetaData(metaData);
578 // save the redirect request also in the cache
579 QVariant redirectionTarget = q->attribute(QNetworkRequest::RedirectionTargetAttribute);
580 if (redirectionTarget.isValid()) {
581 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
582 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
583 metaData.setAttributes(attributes);
586 cacheSaveDevice = networkCache()->prepare(metaData);
588 if (!cacheSaveDevice || (cacheSaveDevice && !cacheSaveDevice->isOpen())) {
589 if (cacheSaveDevice && !cacheSaveDevice->isOpen())
590 qCritical("QNetworkReplyImpl: network cache returned a device that is not open -- "
591 "class %s probably needs to be fixed",
592 networkCache()->metaObject()->className());
594 networkCache()->remove(url);
596 cacheEnabled = false;
600 // we received downstream data and send this to the cache
601 // and to our readBuffer (which in turn gets read by the user of QNetworkReply)
602 void QNetworkReplyImplPrivate::appendDownstreamData(QByteDataBuffer &data)
604 Q_Q(QNetworkReplyImpl);
608 if (cacheEnabled && !cacheSaveDevice) {
609 initCacheSaveDevice();
612 qint64 bytesWritten = 0;
613 for (int i = 0; i < data.bufferCount(); i++) {
614 QByteArray const &item = data[i];
617 cacheSaveDevice->write(item.constData(), item.size());
618 readBuffer.append(item);
620 bytesWritten += item.size();
624 bytesDownloaded += bytesWritten;
625 lastBytesDownloaded = bytesDownloaded;
627 appendDownstreamDataSignalEmissions();
630 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
632 Q_Q(QNetworkReplyImpl);
634 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
635 if (preMigrationDownloaded != Q_INT64_C(-1))
636 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
637 pauseNotificationHandling();
638 // important: At the point of this readyRead(), the data parameter list must be empty,
639 // else implicit sharing will trigger memcpy when the user is reading data!
641 // emit readyRead before downloadProgress incase this will cause events to be
642 // processed and we get into a recursive call (as in QProgressDialog).
643 emit q->downloadProgress(bytesDownloaded,
644 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
646 resumeNotificationHandling();
647 // do we still have room in the buffer?
648 if (nextDownstreamBlockSize() > 0)
649 backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
652 // this is used when it was fetched from the cache, right?
653 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
655 Q_Q(QNetworkReplyImpl);
659 // read until EOF from data
661 qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
662 "backend probly needs to be fixed");
667 q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
668 q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
674 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
681 qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
684 static void downloadBufferDeleter(char *ptr)
689 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
691 Q_Q(QNetworkReplyImpl);
693 if (!downloadBuffer) {
694 // We are requested to create it
695 // Check attribute() if allocating a buffer of that size can be allowed
696 QVariant bufferAllocationPolicy = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
697 if (bufferAllocationPolicy.isValid() && bufferAllocationPolicy.toLongLong() >= size) {
698 downloadBufferCurrentSize = 0;
699 downloadBufferMaximumSize = size;
700 downloadBuffer = new char[downloadBufferMaximumSize]; // throws if allocation fails
701 downloadBufferPointer = QSharedPointer<char>(downloadBuffer, downloadBufferDeleter);
703 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, QVariant::fromValue<QSharedPointer<char> > (downloadBufferPointer));
707 return downloadBuffer;
710 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
712 Q_Q(QNetworkReplyImpl);
714 downloadBufferPointer = sp;
715 downloadBuffer = downloadBufferPointer.data();
716 downloadBufferCurrentSize = 0;
717 downloadBufferMaximumSize = size;
718 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, QVariant::fromValue<QSharedPointer<char> > (downloadBufferPointer));
722 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
724 Q_Q(QNetworkReplyImpl);
728 if (cacheEnabled && !cacheSaveDevice)
729 initCacheSaveDevice();
731 if (cacheSaveDevice && bytesReceived == bytesTotal) {
732 // if (lastBytesDownloaded == -1)
733 // lastBytesDownloaded = 0;
734 // cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
736 // Write everything in one go if we use a download buffer. might be more performant.
737 cacheSaveDevice->write(downloadBuffer, bytesTotal);
740 bytesDownloaded = bytesReceived;
741 lastBytesDownloaded = bytesReceived;
743 downloadBufferCurrentSize = bytesReceived;
745 // Only emit readyRead when actual data is there
746 // emit readyRead before downloadProgress incase this will cause events to be
747 // processed and we get into a recursive call (as in QProgressDialog).
748 if (bytesDownloaded > 0)
750 emit q->downloadProgress(bytesDownloaded, bytesTotal);
753 void QNetworkReplyImplPrivate::finished()
755 Q_Q(QNetworkReplyImpl);
757 if (state == Finished || state == Aborted || state == WaitingForSession)
760 pauseNotificationHandling();
761 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
762 if (preMigrationDownloaded != Q_INT64_C(-1))
763 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
765 if (!manager.isNull()) {
766 #ifndef QT_NO_BEARERMANAGEMENT
767 QNetworkSession *session = manager->d_func()->networkSession.data();
768 if (session && session->state() == QNetworkSession::Roaming &&
769 state == Working && errorCode != QNetworkReply::OperationCanceledError) {
770 // only content with a known size will fail with a temporary network failure error
771 if (!totalSize.isNull()) {
772 if (bytesDownloaded != totalSize) {
773 if (migrateBackend()) {
774 // either we are migrating or the request is finished/aborted
775 if (state == Reconnecting || state == WaitingForSession) {
776 resumeNotificationHandling();
777 return; // exit early if we are migrating.
780 error(QNetworkReply::TemporaryNetworkFailureError,
781 QNetworkReply::tr("Temporary network failure."));
788 resumeNotificationHandling();
791 q->setFinished(true);
793 pendingNotifications.clear();
795 pauseNotificationHandling();
796 if (totalSize.isNull() || totalSize == -1) {
797 emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
800 if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
801 emit q->uploadProgress(0, 0);
802 resumeNotificationHandling();
804 // if we don't know the total size of or we received everything save the cache
805 if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
808 // note: might not be a good idea, since users could decide to delete us
809 // which would delete the backend too...
810 // maybe we should protect the backend
811 pauseNotificationHandling();
812 emit q->readChannelFinished();
814 resumeNotificationHandling();
817 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
819 Q_Q(QNetworkReplyImpl);
820 // Can't set and emit multiple errors.
821 if (errorCode != QNetworkReply::NoError) {
822 qWarning( "QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.");
827 q->setErrorString(errorMessage);
829 // note: might not be a good idea, since users could decide to delete us
830 // which would delete the backend too...
831 // maybe we should protect the backend
835 void QNetworkReplyImplPrivate::metaDataChanged()
837 Q_Q(QNetworkReplyImpl);
838 // 1. do we have cookies?
839 // 2. are we allowed to set them?
840 if (cookedHeaders.contains(QNetworkRequest::SetCookieHeader) && !manager.isNull()
841 && (static_cast<QNetworkRequest::LoadControl>
842 (request.attribute(QNetworkRequest::CookieSaveControlAttribute,
843 QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic)) {
844 QList<QNetworkCookie> cookies =
845 qvariant_cast<QList<QNetworkCookie> >(cookedHeaders.value(QNetworkRequest::SetCookieHeader));
846 QNetworkCookieJar *jar = manager->cookieJar();
848 jar->setCookiesFromUrl(cookies, url);
850 emit q->metaDataChanged();
853 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
855 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
858 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
861 Q_Q(QNetworkReplyImpl);
862 emit q->sslErrors(errors);
868 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
869 : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
873 QNetworkReplyImpl::~QNetworkReplyImpl()
875 Q_D(QNetworkReplyImpl);
877 // This code removes the data from the cache if it was prematurely aborted.
878 // See QNetworkReplyImplPrivate::completeCacheSave(), we disable caching there after the cache
879 // save had been properly finished. So if it is still enabled it means we got deleted/aborted.
880 if (d->isCachingEnabled())
881 d->networkCache()->remove(url());
884 void QNetworkReplyImpl::abort()
886 Q_D(QNetworkReplyImpl);
887 if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
890 // stop both upload and download
892 disconnect(d->outgoingData, 0, this, 0);
894 disconnect(d->copyDevice, 0, this, 0);
896 QNetworkReply::close();
898 if (d->state != QNetworkReplyImplPrivate::Finished) {
899 // call finished which will emit signals
900 d->error(OperationCanceledError, tr("Operation canceled"));
901 if (d->state == QNetworkReplyImplPrivate::WaitingForSession)
902 d->state = QNetworkReplyImplPrivate::Working;
905 d->state = QNetworkReplyImplPrivate::Aborted;
907 // finished may access the backend
909 d->backend->deleteLater();
914 void QNetworkReplyImpl::close()
916 Q_D(QNetworkReplyImpl);
917 if (d->state == QNetworkReplyImplPrivate::Aborted ||
918 d->state == QNetworkReplyImplPrivate::Finished)
923 d->backend->closeDownstreamChannel();
925 disconnect(d->copyDevice, 0, this, 0);
927 QNetworkReply::close();
929 // call finished which will emit signals
930 d->error(OperationCanceledError, tr("Operation canceled"));
934 bool QNetworkReplyImpl::canReadLine () const
936 Q_D(const QNetworkReplyImpl);
937 return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
942 Returns the number of bytes available for reading with
943 QIODevice::read(). The number of bytes available may grow until
944 the finished() signal is emitted.
946 qint64 QNetworkReplyImpl::bytesAvailable() const
948 // Special case for the "zero copy" download buffer
949 Q_D(const QNetworkReplyImpl);
950 if (d->downloadBuffer) {
951 qint64 maxAvail = d->downloadBufferCurrentSize - d->downloadBufferReadPosition;
952 return QNetworkReply::bytesAvailable() + maxAvail;
955 return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
958 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
960 Q_D(QNetworkReplyImpl);
961 if (size > d->readBufferMaxSize &&
962 size > d->readBuffer.byteAmount())
963 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
965 QNetworkReply::setReadBufferSize(size);
968 d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
972 void QNetworkReplyImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
974 Q_D(const QNetworkReplyImpl);
976 d->backend->fetchSslConfiguration(configuration);
979 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
981 Q_D(QNetworkReplyImpl);
982 if (d->backend && !config.isNull())
983 d->backend->setSslConfiguration(config);
986 void QNetworkReplyImpl::ignoreSslErrors()
988 Q_D(QNetworkReplyImpl);
990 d->backend->ignoreSslErrors();
993 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
995 Q_D(QNetworkReplyImpl);
997 d->backend->ignoreSslErrors(errors);
1004 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
1006 Q_D(QNetworkReplyImpl);
1008 // Special case code if we have the "zero copy" download buffer
1009 if (d->downloadBuffer) {
1010 qint64 maxAvail = qMin<qint64>(d->downloadBufferCurrentSize - d->downloadBufferReadPosition, maxlen);
1012 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
1013 // FIXME what about "Aborted" state?
1014 memcpy(data, d->downloadBuffer + d->downloadBufferReadPosition, maxAvail);
1015 d->downloadBufferReadPosition += maxAvail;
1020 if (d->readBuffer.isEmpty())
1021 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
1022 // FIXME what about "Aborted" state?
1024 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
1026 // optimization for getChar()
1027 *data = d->readBuffer.getChar();
1031 maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
1032 return d->readBuffer.read(data, maxlen);
1036 \internal Reimplemented for internal purposes
1038 bool QNetworkReplyImpl::event(QEvent *e)
1040 if (e->type() == QEvent::NetworkReplyUpdated) {
1041 d_func()->handleNotifications();
1045 return QObject::event(e);
1049 Migrates the backend of the QNetworkReply to a new network connection if required. Returns
1050 true if the reply is migrated or it is not required; otherwise returns false.
1052 bool QNetworkReplyImplPrivate::migrateBackend()
1054 Q_Q(QNetworkReplyImpl);
1056 // Network reply is already finished or aborted, don't need to migrate.
1057 if (state == Finished || state == Aborted)
1060 // Request has outgoing data, not migrating.
1064 // Request is serviced from the cache, don't need to migrate.
1068 // Backend does not support resuming download.
1069 if (!backend->canResume())
1072 state = QNetworkReplyImplPrivate::Reconnecting;
1079 cookedHeaders.clear();
1082 preMigrationDownloaded = bytesDownloaded;
1084 backend = manager->d_func()->findBackend(operation, request);
1087 backend->setParent(q);
1088 backend->reply = this;
1089 backend->setResumeOffset(bytesDownloaded);
1093 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1095 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1096 #endif // QT_NO_HTTP
1101 #ifndef QT_NO_BEARERMANAGEMENT
1102 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1103 const QNetworkRequest &req,
1104 QNetworkAccessManager::Operation op)
1105 : QNetworkReply(parent)
1111 qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1113 QString msg = QCoreApplication::translate("QNetworkAccessManager",
1114 "Network access is disabled.");
1115 setError(UnknownNetworkError, msg);
1117 QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1118 Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1119 QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1122 QDisabledNetworkReply::~QDisabledNetworkReply()
1129 #include "moc_qnetworkreplyimpl_p.cpp"