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 // ensure this function is only being called once
77 if (state == Working || state == Finished) {
78 qDebug("QNetworkReplyImpl::_q_startOperation was called more than once");
83 // note: if that method is called directly, it cannot happen that the backend is 0,
84 // because we just checked via a qobject_cast that we got a http backend (see
85 // QNetworkReplyImplPrivate::setup())
87 error(QNetworkReplyImpl::ProtocolUnknownError,
88 QCoreApplication::translate("QNetworkReply", "Protocol \"%1\" is unknown").arg(url.scheme())); // not really true!;
93 if (!backend->start()) {
94 #ifndef QT_NO_BEARERMANAGEMENT
95 // backend failed to start because the session state is not Connected.
96 // QNetworkAccessManager will call _q_startOperation again for us when the session
98 state = WaitingForSession;
100 QNetworkSession *session = manager->d_func()->networkSession.data();
103 Q_Q(QNetworkReplyImpl);
105 QObject::connect(session, SIGNAL(error(QNetworkSession::SessionError)),
106 q, SLOT(_q_networkSessionFailed()));
108 if (!session->isOpen()) {
109 session->setSessionProperty(QStringLiteral("ConnectInBackground"),
110 backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(false)));
114 qWarning("Backend is waiting for QNetworkSession to connect, but there is none!");
116 error(QNetworkReplyImpl::UnknownNetworkError,
117 QCoreApplication::translate("QNetworkReply", "Network session error."));
121 qWarning("Backend start failed");
123 error(QNetworkReplyImpl::UnknownNetworkError,
124 QCoreApplication::translate("QNetworkReply", "backend start error."));
130 if (backend && backend->isSynchronous()) {
132 q_func()->setFinished(true);
134 if (state != Finished) {
135 if (operation == QNetworkAccessManager::GetOperation)
136 pendingNotifications.append(NotifyDownstreamReadyWrite);
138 handleNotifications();
143 void QNetworkReplyImplPrivate::_q_copyReadyRead()
145 Q_Q(QNetworkReplyImpl);
146 if (state != Working)
148 if (!copyDevice || !q->isOpen())
151 // FIXME Optimize to use download buffer if it is a QBuffer.
152 // Needs to be done where sendCacheContents() (?) of HTTP is emitting
156 qint64 bytesToRead = nextDownstreamBlockSize();
157 if (bytesToRead == 0)
158 // we'll be called again, eventually
161 bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
163 byteData.resize(bytesToRead);
164 qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
165 if (bytesActuallyRead == -1) {
167 backendNotify(NotifyCopyFinished);
171 byteData.resize(bytesActuallyRead);
172 readBuffer.append(byteData);
174 if (!copyDevice->isSequential() && copyDevice->atEnd()) {
175 backendNotify(NotifyCopyFinished);
176 bytesDownloaded += bytesActuallyRead;
180 bytesDownloaded += bytesActuallyRead;
183 if (bytesDownloaded == lastBytesDownloaded) {
184 // we didn't read anything
188 lastBytesDownloaded = bytesDownloaded;
189 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
190 if (preMigrationDownloaded != Q_INT64_C(-1))
191 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
192 pauseNotificationHandling();
193 // emit readyRead before downloadProgress incase this will cause events to be
194 // processed and we get into a recursive call (as in QProgressDialog).
196 emit q->downloadProgress(bytesDownloaded,
197 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
198 resumeNotificationHandling();
201 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
206 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
208 Q_Q(QNetworkReplyImpl);
210 // make sure this is only called once, ever.
211 //_q_bufferOutgoingData may call it or the readChannelFinished emission
212 if (state != Buffering)
215 // disconnect signals
216 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
217 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
219 // finally, start the request
220 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
223 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
225 Q_Q(QNetworkReplyImpl);
227 if (!outgoingDataBuffer) {
228 // first call, create our buffer
229 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
231 QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
232 QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
235 qint64 bytesBuffered = 0;
236 qint64 bytesToBuffer = 0;
238 // read data into our buffer
240 bytesToBuffer = outgoingData->bytesAvailable();
241 // unknown? just try 2 kB, this also ensures we always try to read the EOF
242 if (bytesToBuffer <= 0)
243 bytesToBuffer = 2*1024;
245 char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
246 bytesBuffered = outgoingData->read(dst, bytesToBuffer);
248 if (bytesBuffered == -1) {
249 // EOF has been reached.
250 outgoingDataBuffer->chop(bytesToBuffer);
252 _q_bufferOutgoingDataFinished();
254 } else if (bytesBuffered == 0) {
255 // nothing read right now, just wait until we get called again
256 outgoingDataBuffer->chop(bytesToBuffer);
260 // don't break, try to read() again
261 outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
266 #ifndef QT_NO_BEARERMANAGEMENT
267 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
269 Q_Q(QNetworkReplyImpl);
271 if (manager.isNull())
274 QNetworkSession *session = manager->d_func()->networkSession.data();
278 if (session->state() != QNetworkSession::Connected)
282 case QNetworkReplyImplPrivate::Buffering:
283 case QNetworkReplyImplPrivate::Working:
284 case QNetworkReplyImplPrivate::Reconnecting:
285 // Migrate existing downloads to new network connection.
288 case QNetworkReplyImplPrivate::WaitingForSession:
289 // Start waiting requests.
290 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
297 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
299 // Abort waiting and working replies.
300 if (state == WaitingForSession || state == Working) {
302 error(QNetworkReplyImpl::UnknownNetworkError,
303 QCoreApplication::translate("QNetworkReply", "Network session error."));
309 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
312 Q_Q(QNetworkReplyImpl);
319 q->QIODevice::open(QIODevice::ReadOnly);
320 // Internal code that does a HTTP reply for the synchronous Ajax
322 QVariant synchronousHttpAttribute = req.attribute(
323 static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute));
324 // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
325 // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
326 if (synchronousHttpAttribute.toBool() && outgoingData) {
327 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
328 qint64 previousDataSize = 0;
330 previousDataSize = outgoingDataBuffer->size();
331 outgoingDataBuffer->append(outgoingData->readAll());
332 } while (outgoingDataBuffer->size() != previousDataSize);
336 backend->setSynchronous(synchronousHttpAttribute.toBool());
339 if (outgoingData && backend && !backend->isSynchronous()) {
340 // there is data to be uploaded, e.g. HTTP POST.
342 if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) {
343 // backend does not need upload buffering or
344 // fixed size non-sequential
345 // just start the operation
346 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
348 bool bufferingDisallowed =
349 req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
352 if (bufferingDisallowed) {
353 // if a valid content-length header for the request was supplied, we can disable buffering
354 // if not, we will buffer anyway
355 if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) {
356 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
359 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
362 // _q_startOperation will be called when the buffering has finished.
364 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
368 // for HTTP, we want to send out the request as fast as possible to the network, without
369 // invoking methods in a QueuedConnection
371 if (backend && backend->isSynchronous()) {
374 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
377 if (backend && backend->isSynchronous())
380 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
385 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
387 Q_Q(QNetworkReplyImpl);
388 if (!pendingNotifications.contains(notification))
389 pendingNotifications.enqueue(notification);
391 if (pendingNotifications.size() == 1)
392 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
395 void QNetworkReplyImplPrivate::handleNotifications()
397 if (notificationHandlingPaused)
400 NotificationQueue current = pendingNotifications;
401 pendingNotifications.clear();
403 if (state != Working)
406 while (state == Working && !current.isEmpty()) {
407 InternalNotifications notification = current.dequeue();
408 switch (notification) {
409 case NotifyDownstreamReadyWrite:
413 backend->downstreamReadyWrite();
416 case NotifyCloseDownstreamChannel:
417 backend->closeDownstreamChannel();
420 case NotifyCopyFinished: {
421 QIODevice *dev = copyDevice;
423 backend->copyFinished(dev);
430 // Do not handle the notifications while we are emitting downloadProgress
432 void QNetworkReplyImplPrivate::pauseNotificationHandling()
434 notificationHandlingPaused = true;
437 // Resume notification handling
438 void QNetworkReplyImplPrivate::resumeNotificationHandling()
440 Q_Q(QNetworkReplyImpl);
441 notificationHandlingPaused = false;
442 if (pendingNotifications.size() >= 1)
443 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
446 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
450 return backend->networkCache();
453 void QNetworkReplyImplPrivate::createCache()
455 // check if we can save and if we're allowed to
457 || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool()
458 || request.attribute(QNetworkRequest::CacheLoadControlAttribute,
459 QNetworkRequest::PreferNetwork).toInt()
460 == QNetworkRequest::AlwaysNetwork)
465 bool QNetworkReplyImplPrivate::isCachingEnabled() const
467 return (cacheEnabled && networkCache() != 0);
470 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
472 if (!enable && !cacheEnabled)
473 return; // nothing to do
474 if (enable && cacheEnabled)
475 return; // nothing to do either!
478 if (bytesDownloaded) {
479 // refuse to enable in this case
480 qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
486 // someone told us to turn on, then back off?
487 // ok... but you should make up your mind
488 qDebug("QNetworkReplyImpl: setCachingEnabled(true) called after setCachingEnabled(false) -- "
489 "backend %s probably needs to be fixed",
490 backend->metaObject()->className());
491 networkCache()->remove(url);
493 cacheEnabled = false;
497 void QNetworkReplyImplPrivate::completeCacheSave()
499 if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
500 networkCache()->remove(url);
501 } else if (cacheEnabled && cacheSaveDevice) {
502 networkCache()->insert(cacheSaveDevice);
505 cacheEnabled = false;
508 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
510 Q_Q(QNetworkReplyImpl);
511 bytesUploaded = bytesSent;
512 pauseNotificationHandling();
513 emit q->uploadProgress(bytesSent, bytesTotal);
514 resumeNotificationHandling();
518 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
520 enum { DesiredBufferSize = 32 * 1024 };
521 if (readBufferMaxSize == 0)
522 return DesiredBufferSize;
524 return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
527 void QNetworkReplyImplPrivate::initCacheSaveDevice()
529 Q_Q(QNetworkReplyImpl);
531 // The disk cache does not support partial content, so don't even try to
532 // save any such content into the cache.
533 if (q->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 206) {
534 cacheEnabled = false;
538 // save the meta data
539 QNetworkCacheMetaData metaData;
540 metaData.setUrl(url);
541 metaData = backend->fetchCacheMetaData(metaData);
543 // save the redirect request also in the cache
544 QVariant redirectionTarget = q->attribute(QNetworkRequest::RedirectionTargetAttribute);
545 if (redirectionTarget.isValid()) {
546 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
547 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
548 metaData.setAttributes(attributes);
551 cacheSaveDevice = networkCache()->prepare(metaData);
553 if (!cacheSaveDevice || (cacheSaveDevice && !cacheSaveDevice->isOpen())) {
554 if (cacheSaveDevice && !cacheSaveDevice->isOpen())
555 qCritical("QNetworkReplyImpl: network cache returned a device that is not open -- "
556 "class %s probably needs to be fixed",
557 networkCache()->metaObject()->className());
559 networkCache()->remove(url);
561 cacheEnabled = false;
565 // we received downstream data and send this to the cache
566 // and to our readBuffer (which in turn gets read by the user of QNetworkReply)
567 void QNetworkReplyImplPrivate::appendDownstreamData(QByteDataBuffer &data)
569 Q_Q(QNetworkReplyImpl);
573 if (cacheEnabled && !cacheSaveDevice) {
574 initCacheSaveDevice();
577 qint64 bytesWritten = 0;
578 for (int i = 0; i < data.bufferCount(); i++) {
579 QByteArray const &item = data[i];
582 cacheSaveDevice->write(item.constData(), item.size());
583 readBuffer.append(item);
585 bytesWritten += item.size();
589 bytesDownloaded += bytesWritten;
590 lastBytesDownloaded = bytesDownloaded;
592 appendDownstreamDataSignalEmissions();
595 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
597 Q_Q(QNetworkReplyImpl);
599 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
600 if (preMigrationDownloaded != Q_INT64_C(-1))
601 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
602 pauseNotificationHandling();
603 // important: At the point of this readyRead(), the data parameter list must be empty,
604 // else implicit sharing will trigger memcpy when the user is reading data!
606 // emit readyRead before downloadProgress incase this will cause events to be
607 // processed and we get into a recursive call (as in QProgressDialog).
608 emit q->downloadProgress(bytesDownloaded,
609 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
611 resumeNotificationHandling();
612 // do we still have room in the buffer?
613 if (nextDownstreamBlockSize() > 0)
614 backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
617 // this is used when it was fetched from the cache, right?
618 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
620 Q_Q(QNetworkReplyImpl);
624 // read until EOF from data
626 qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
627 "backend probly needs to be fixed");
632 q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
633 q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
639 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
646 qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
649 static void downloadBufferDeleter(char *ptr)
654 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
656 Q_Q(QNetworkReplyImpl);
658 if (!downloadBuffer) {
659 // We are requested to create it
660 // Check attribute() if allocating a buffer of that size can be allowed
661 QVariant bufferAllocationPolicy = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
662 if (bufferAllocationPolicy.isValid() && bufferAllocationPolicy.toLongLong() >= size) {
663 downloadBufferCurrentSize = 0;
664 downloadBufferMaximumSize = size;
665 downloadBuffer = new char[downloadBufferMaximumSize]; // throws if allocation fails
666 downloadBufferPointer = QSharedPointer<char>(downloadBuffer, downloadBufferDeleter);
668 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
672 return downloadBuffer;
675 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
677 Q_Q(QNetworkReplyImpl);
679 downloadBufferPointer = sp;
680 downloadBuffer = downloadBufferPointer.data();
681 downloadBufferCurrentSize = 0;
682 downloadBufferMaximumSize = size;
683 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
687 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
689 Q_Q(QNetworkReplyImpl);
693 if (cacheEnabled && !cacheSaveDevice)
694 initCacheSaveDevice();
696 if (cacheSaveDevice && bytesReceived == bytesTotal) {
697 // if (lastBytesDownloaded == -1)
698 // lastBytesDownloaded = 0;
699 // cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
701 // Write everything in one go if we use a download buffer. might be more performant.
702 cacheSaveDevice->write(downloadBuffer, bytesTotal);
705 bytesDownloaded = bytesReceived;
706 lastBytesDownloaded = bytesReceived;
708 downloadBufferCurrentSize = bytesReceived;
710 // Only emit readyRead when actual data is there
711 // emit readyRead before downloadProgress incase this will cause events to be
712 // processed and we get into a recursive call (as in QProgressDialog).
713 if (bytesDownloaded > 0)
715 emit q->downloadProgress(bytesDownloaded, bytesTotal);
718 void QNetworkReplyImplPrivate::finished()
720 Q_Q(QNetworkReplyImpl);
722 if (state == Finished || state == Aborted || state == WaitingForSession)
725 pauseNotificationHandling();
726 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
727 if (preMigrationDownloaded != Q_INT64_C(-1))
728 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
730 if (!manager.isNull()) {
731 #ifndef QT_NO_BEARERMANAGEMENT
732 QNetworkSession *session = manager->d_func()->networkSession.data();
733 if (session && session->state() == QNetworkSession::Roaming &&
734 state == Working && errorCode != QNetworkReply::OperationCanceledError) {
735 // only content with a known size will fail with a temporary network failure error
736 if (!totalSize.isNull()) {
737 if (bytesDownloaded != totalSize) {
738 if (migrateBackend()) {
739 // either we are migrating or the request is finished/aborted
740 if (state == Reconnecting || state == WaitingForSession) {
741 resumeNotificationHandling();
742 return; // exit early if we are migrating.
745 error(QNetworkReply::TemporaryNetworkFailureError,
746 QNetworkReply::tr("Temporary network failure."));
753 resumeNotificationHandling();
756 q->setFinished(true);
758 pendingNotifications.clear();
760 pauseNotificationHandling();
761 if (totalSize.isNull() || totalSize == -1) {
762 emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
765 if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
766 emit q->uploadProgress(0, 0);
767 resumeNotificationHandling();
769 // if we don't know the total size of or we received everything save the cache
770 if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
773 // note: might not be a good idea, since users could decide to delete us
774 // which would delete the backend too...
775 // maybe we should protect the backend
776 pauseNotificationHandling();
777 emit q->readChannelFinished();
779 resumeNotificationHandling();
782 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
784 Q_Q(QNetworkReplyImpl);
785 // Can't set and emit multiple errors.
786 if (errorCode != QNetworkReply::NoError) {
787 qWarning( "QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.");
792 q->setErrorString(errorMessage);
794 // note: might not be a good idea, since users could decide to delete us
795 // which would delete the backend too...
796 // maybe we should protect the backend
800 void QNetworkReplyImplPrivate::metaDataChanged()
802 Q_Q(QNetworkReplyImpl);
803 // 1. do we have cookies?
804 // 2. are we allowed to set them?
805 if (cookedHeaders.contains(QNetworkRequest::SetCookieHeader) && !manager.isNull()
806 && (static_cast<QNetworkRequest::LoadControl>
807 (request.attribute(QNetworkRequest::CookieSaveControlAttribute,
808 QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic)) {
809 QList<QNetworkCookie> cookies =
810 qvariant_cast<QList<QNetworkCookie> >(cookedHeaders.value(QNetworkRequest::SetCookieHeader));
811 QNetworkCookieJar *jar = manager->cookieJar();
813 jar->setCookiesFromUrl(cookies, url);
815 emit q->metaDataChanged();
818 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
820 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
823 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
826 Q_Q(QNetworkReplyImpl);
827 emit q->sslErrors(errors);
833 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
834 : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
838 QNetworkReplyImpl::~QNetworkReplyImpl()
840 Q_D(QNetworkReplyImpl);
842 // This code removes the data from the cache if it was prematurely aborted.
843 // See QNetworkReplyImplPrivate::completeCacheSave(), we disable caching there after the cache
844 // save had been properly finished. So if it is still enabled it means we got deleted/aborted.
845 if (d->isCachingEnabled())
846 d->networkCache()->remove(url());
849 void QNetworkReplyImpl::abort()
851 Q_D(QNetworkReplyImpl);
852 if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
855 // stop both upload and download
857 disconnect(d->outgoingData, 0, this, 0);
859 disconnect(d->copyDevice, 0, this, 0);
861 QNetworkReply::close();
863 if (d->state != QNetworkReplyImplPrivate::Finished) {
864 // call finished which will emit signals
865 d->error(OperationCanceledError, tr("Operation canceled"));
866 if (d->state == QNetworkReplyImplPrivate::WaitingForSession)
867 d->state = QNetworkReplyImplPrivate::Working;
870 d->state = QNetworkReplyImplPrivate::Aborted;
872 // finished may access the backend
874 d->backend->deleteLater();
879 void QNetworkReplyImpl::close()
881 Q_D(QNetworkReplyImpl);
882 if (d->state == QNetworkReplyImplPrivate::Aborted ||
883 d->state == QNetworkReplyImplPrivate::Finished)
888 d->backend->closeDownstreamChannel();
890 disconnect(d->copyDevice, 0, this, 0);
892 QNetworkReply::close();
894 // call finished which will emit signals
895 d->error(OperationCanceledError, tr("Operation canceled"));
899 bool QNetworkReplyImpl::canReadLine () const
901 Q_D(const QNetworkReplyImpl);
902 return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
907 Returns the number of bytes available for reading with
908 QIODevice::read(). The number of bytes available may grow until
909 the finished() signal is emitted.
911 qint64 QNetworkReplyImpl::bytesAvailable() const
913 // Special case for the "zero copy" download buffer
914 Q_D(const QNetworkReplyImpl);
915 if (d->downloadBuffer) {
916 qint64 maxAvail = d->downloadBufferCurrentSize - d->downloadBufferReadPosition;
917 return QNetworkReply::bytesAvailable() + maxAvail;
920 return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
923 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
925 Q_D(QNetworkReplyImpl);
926 if (size > d->readBufferMaxSize &&
927 size > d->readBuffer.byteAmount())
928 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
930 QNetworkReply::setReadBufferSize(size);
933 d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
937 void QNetworkReplyImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
939 Q_D(const QNetworkReplyImpl);
941 d->backend->fetchSslConfiguration(configuration);
944 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
946 Q_D(QNetworkReplyImpl);
947 if (d->backend && !config.isNull())
948 d->backend->setSslConfiguration(config);
951 void QNetworkReplyImpl::ignoreSslErrors()
953 Q_D(QNetworkReplyImpl);
955 d->backend->ignoreSslErrors();
958 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
960 Q_D(QNetworkReplyImpl);
962 d->backend->ignoreSslErrors(errors);
969 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
971 Q_D(QNetworkReplyImpl);
973 // Special case code if we have the "zero copy" download buffer
974 if (d->downloadBuffer) {
975 qint64 maxAvail = qMin<qint64>(d->downloadBufferCurrentSize - d->downloadBufferReadPosition, maxlen);
977 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
978 // FIXME what about "Aborted" state?
979 memcpy(data, d->downloadBuffer + d->downloadBufferReadPosition, maxAvail);
980 d->downloadBufferReadPosition += maxAvail;
985 if (d->readBuffer.isEmpty())
986 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
987 // FIXME what about "Aborted" state?
989 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
991 // optimization for getChar()
992 *data = d->readBuffer.getChar();
996 maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
997 return d->readBuffer.read(data, maxlen);
1001 \internal Reimplemented for internal purposes
1003 bool QNetworkReplyImpl::event(QEvent *e)
1005 if (e->type() == QEvent::NetworkReplyUpdated) {
1006 d_func()->handleNotifications();
1010 return QObject::event(e);
1014 Migrates the backend of the QNetworkReply to a new network connection if required. Returns
1015 true if the reply is migrated or it is not required; otherwise returns false.
1017 bool QNetworkReplyImplPrivate::migrateBackend()
1019 Q_Q(QNetworkReplyImpl);
1021 // Network reply is already finished or aborted, don't need to migrate.
1022 if (state == Finished || state == Aborted)
1025 // Request has outgoing data, not migrating.
1029 // Request is serviced from the cache, don't need to migrate.
1033 // Backend does not support resuming download.
1034 if (!backend->canResume())
1037 state = QNetworkReplyImplPrivate::Reconnecting;
1044 cookedHeaders.clear();
1047 preMigrationDownloaded = bytesDownloaded;
1049 backend = manager->d_func()->findBackend(operation, request);
1052 backend->setParent(q);
1053 backend->reply = this;
1054 backend->setResumeOffset(bytesDownloaded);
1058 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1060 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1061 #endif // QT_NO_HTTP
1066 #ifndef QT_NO_BEARERMANAGEMENT
1067 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1068 const QNetworkRequest &req,
1069 QNetworkAccessManager::Operation op)
1070 : QNetworkReply(parent)
1076 qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1078 QString msg = QCoreApplication::translate("QNetworkAccessManager",
1079 "Network access is disabled.");
1080 setError(UnknownNetworkError, msg);
1082 QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1083 Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1084 QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1087 QDisabledNetworkReply::~QDisabledNetworkReply()
1094 #include "moc_qnetworkreplyimpl_p.cpp"