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())
111 qWarning("Backend is waiting for QNetworkSession to connect, but there is none!");
113 error(QNetworkReplyImpl::UnknownNetworkError,
114 QCoreApplication::translate("QNetworkReply", "Network session error."));
118 qWarning("Backend start failed");
120 error(QNetworkReplyImpl::UnknownNetworkError,
121 QCoreApplication::translate("QNetworkReply", "backend start error."));
127 if (backend && backend->isSynchronous()) {
129 q_func()->setFinished(true);
131 if (state != Finished) {
132 if (operation == QNetworkAccessManager::GetOperation)
133 pendingNotifications.append(NotifyDownstreamReadyWrite);
135 handleNotifications();
140 void QNetworkReplyImplPrivate::_q_copyReadyRead()
142 Q_Q(QNetworkReplyImpl);
143 if (state != Working)
145 if (!copyDevice || !q->isOpen())
148 // FIXME Optimize to use download buffer if it is a QBuffer.
149 // Needs to be done where sendCacheContents() (?) of HTTP is emitting
153 qint64 bytesToRead = nextDownstreamBlockSize();
154 if (bytesToRead == 0)
155 // we'll be called again, eventually
158 bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
160 byteData.resize(bytesToRead);
161 qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
162 if (bytesActuallyRead == -1) {
164 backendNotify(NotifyCopyFinished);
168 byteData.resize(bytesActuallyRead);
169 readBuffer.append(byteData);
171 if (!copyDevice->isSequential() && copyDevice->atEnd()) {
172 backendNotify(NotifyCopyFinished);
173 bytesDownloaded += bytesActuallyRead;
177 bytesDownloaded += bytesActuallyRead;
180 if (bytesDownloaded == lastBytesDownloaded) {
181 // we didn't read anything
185 lastBytesDownloaded = bytesDownloaded;
186 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
187 if (preMigrationDownloaded != Q_INT64_C(-1))
188 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
189 pauseNotificationHandling();
190 // emit readyRead before downloadProgress incase this will cause events to be
191 // processed and we get into a recursive call (as in QProgressDialog).
193 emit q->downloadProgress(bytesDownloaded,
194 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
195 resumeNotificationHandling();
198 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
203 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
205 Q_Q(QNetworkReplyImpl);
207 // make sure this is only called once, ever.
208 //_q_bufferOutgoingData may call it or the readChannelFinished emission
209 if (state != Buffering)
212 // disconnect signals
213 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
214 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
216 // finally, start the request
217 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
220 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
222 Q_Q(QNetworkReplyImpl);
224 if (!outgoingDataBuffer) {
225 // first call, create our buffer
226 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
228 QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
229 QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
232 qint64 bytesBuffered = 0;
233 qint64 bytesToBuffer = 0;
235 // read data into our buffer
237 bytesToBuffer = outgoingData->bytesAvailable();
238 // unknown? just try 2 kB, this also ensures we always try to read the EOF
239 if (bytesToBuffer <= 0)
240 bytesToBuffer = 2*1024;
242 char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
243 bytesBuffered = outgoingData->read(dst, bytesToBuffer);
245 if (bytesBuffered == -1) {
246 // EOF has been reached.
247 outgoingDataBuffer->chop(bytesToBuffer);
249 _q_bufferOutgoingDataFinished();
251 } else if (bytesBuffered == 0) {
252 // nothing read right now, just wait until we get called again
253 outgoingDataBuffer->chop(bytesToBuffer);
257 // don't break, try to read() again
258 outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
263 #ifndef QT_NO_BEARERMANAGEMENT
264 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
266 Q_Q(QNetworkReplyImpl);
268 if (manager.isNull())
271 QNetworkSession *session = manager->d_func()->networkSession.data();
275 if (session->state() != QNetworkSession::Connected)
279 case QNetworkReplyImplPrivate::Buffering:
280 case QNetworkReplyImplPrivate::Working:
281 case QNetworkReplyImplPrivate::Reconnecting:
282 // Migrate existing downloads to new network connection.
285 case QNetworkReplyImplPrivate::WaitingForSession:
286 // Start waiting requests.
287 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
294 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
296 // Abort waiting and working replies.
297 if (state == WaitingForSession || state == Working) {
299 error(QNetworkReplyImpl::UnknownNetworkError,
300 QCoreApplication::translate("QNetworkReply", "Network session error."));
306 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
309 Q_Q(QNetworkReplyImpl);
316 q->QIODevice::open(QIODevice::ReadOnly);
317 // Internal code that does a HTTP reply for the synchronous Ajax
319 QVariant synchronousHttpAttribute = req.attribute(
320 static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute));
321 // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
322 // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
323 if (synchronousHttpAttribute.toBool() && outgoingData) {
324 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
325 qint64 previousDataSize = 0;
327 previousDataSize = outgoingDataBuffer->size();
328 outgoingDataBuffer->append(outgoingData->readAll());
329 } while (outgoingDataBuffer->size() != previousDataSize);
333 backend->setSynchronous(synchronousHttpAttribute.toBool());
336 if (outgoingData && backend && !backend->isSynchronous()) {
337 // there is data to be uploaded, e.g. HTTP POST.
339 if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) {
340 // backend does not need upload buffering or
341 // fixed size non-sequential
342 // just start the operation
343 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
345 bool bufferingDisallowed =
346 req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
349 if (bufferingDisallowed) {
350 // if a valid content-length header for the request was supplied, we can disable buffering
351 // if not, we will buffer anyway
352 if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) {
353 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
356 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
359 // _q_startOperation will be called when the buffering has finished.
361 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
365 // for HTTP, we want to send out the request as fast as possible to the network, without
366 // invoking methods in a QueuedConnection
368 if (backend && backend->isSynchronous()) {
371 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
374 if (backend && backend->isSynchronous())
377 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
382 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
384 Q_Q(QNetworkReplyImpl);
385 if (!pendingNotifications.contains(notification))
386 pendingNotifications.enqueue(notification);
388 if (pendingNotifications.size() == 1)
389 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
392 void QNetworkReplyImplPrivate::handleNotifications()
394 if (notificationHandlingPaused)
397 NotificationQueue current = pendingNotifications;
398 pendingNotifications.clear();
400 if (state != Working)
403 while (state == Working && !current.isEmpty()) {
404 InternalNotifications notification = current.dequeue();
405 switch (notification) {
406 case NotifyDownstreamReadyWrite:
410 backend->downstreamReadyWrite();
413 case NotifyCloseDownstreamChannel:
414 backend->closeDownstreamChannel();
417 case NotifyCopyFinished: {
418 QIODevice *dev = copyDevice;
420 backend->copyFinished(dev);
427 // Do not handle the notifications while we are emitting downloadProgress
429 void QNetworkReplyImplPrivate::pauseNotificationHandling()
431 notificationHandlingPaused = true;
434 // Resume notification handling
435 void QNetworkReplyImplPrivate::resumeNotificationHandling()
437 Q_Q(QNetworkReplyImpl);
438 notificationHandlingPaused = false;
439 if (pendingNotifications.size() >= 1)
440 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
443 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
447 return backend->networkCache();
450 void QNetworkReplyImplPrivate::createCache()
452 // check if we can save and if we're allowed to
454 || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool())
459 bool QNetworkReplyImplPrivate::isCachingEnabled() const
461 return (cacheEnabled && networkCache() != 0);
464 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
466 if (!enable && !cacheEnabled)
467 return; // nothing to do
468 if (enable && cacheEnabled)
469 return; // nothing to do either!
472 if (bytesDownloaded) {
473 // refuse to enable in this case
474 qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
480 // someone told us to turn on, then back off?
481 // ok... but you should make up your mind
482 qDebug("QNetworkReplyImpl: setCachingEnabled(true) called after setCachingEnabled(false) -- "
483 "backend %s probably needs to be fixed",
484 backend->metaObject()->className());
485 networkCache()->remove(url);
487 cacheEnabled = false;
491 void QNetworkReplyImplPrivate::completeCacheSave()
493 if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
494 networkCache()->remove(url);
495 } else if (cacheEnabled && cacheSaveDevice) {
496 networkCache()->insert(cacheSaveDevice);
499 cacheEnabled = false;
502 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
504 Q_Q(QNetworkReplyImpl);
505 bytesUploaded = bytesSent;
506 pauseNotificationHandling();
507 emit q->uploadProgress(bytesSent, bytesTotal);
508 resumeNotificationHandling();
512 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
514 enum { DesiredBufferSize = 32 * 1024 };
515 if (readBufferMaxSize == 0)
516 return DesiredBufferSize;
518 return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
521 void QNetworkReplyImplPrivate::initCacheSaveDevice()
523 Q_Q(QNetworkReplyImpl);
525 // The disk cache does not support partial content, so don't even try to
526 // save any such content into the cache.
527 if (q->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 206) {
528 cacheEnabled = false;
532 // save the meta data
533 QNetworkCacheMetaData metaData;
534 metaData.setUrl(url);
535 metaData = backend->fetchCacheMetaData(metaData);
537 // save the redirect request also in the cache
538 QVariant redirectionTarget = q->attribute(QNetworkRequest::RedirectionTargetAttribute);
539 if (redirectionTarget.isValid()) {
540 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
541 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
542 metaData.setAttributes(attributes);
545 cacheSaveDevice = networkCache()->prepare(metaData);
547 if (!cacheSaveDevice || (cacheSaveDevice && !cacheSaveDevice->isOpen())) {
548 if (cacheSaveDevice && !cacheSaveDevice->isOpen())
549 qCritical("QNetworkReplyImpl: network cache returned a device that is not open -- "
550 "class %s probably needs to be fixed",
551 networkCache()->metaObject()->className());
553 networkCache()->remove(url);
555 cacheEnabled = false;
559 // we received downstream data and send this to the cache
560 // and to our readBuffer (which in turn gets read by the user of QNetworkReply)
561 void QNetworkReplyImplPrivate::appendDownstreamData(QByteDataBuffer &data)
563 Q_Q(QNetworkReplyImpl);
567 if (cacheEnabled && !cacheSaveDevice) {
568 initCacheSaveDevice();
571 qint64 bytesWritten = 0;
572 for (int i = 0; i < data.bufferCount(); i++) {
573 QByteArray const &item = data[i];
576 cacheSaveDevice->write(item.constData(), item.size());
577 readBuffer.append(item);
579 bytesWritten += item.size();
583 bytesDownloaded += bytesWritten;
584 lastBytesDownloaded = bytesDownloaded;
586 appendDownstreamDataSignalEmissions();
589 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
591 Q_Q(QNetworkReplyImpl);
593 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
594 if (preMigrationDownloaded != Q_INT64_C(-1))
595 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
596 pauseNotificationHandling();
597 // important: At the point of this readyRead(), the data parameter list must be empty,
598 // else implicit sharing will trigger memcpy when the user is reading data!
600 // emit readyRead before downloadProgress incase this will cause events to be
601 // processed and we get into a recursive call (as in QProgressDialog).
602 emit q->downloadProgress(bytesDownloaded,
603 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
605 resumeNotificationHandling();
606 // do we still have room in the buffer?
607 if (nextDownstreamBlockSize() > 0)
608 backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
611 // this is used when it was fetched from the cache, right?
612 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
614 Q_Q(QNetworkReplyImpl);
618 // read until EOF from data
620 qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
621 "backend probly needs to be fixed");
626 q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
627 q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
633 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
640 qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
643 static void downloadBufferDeleter(char *ptr)
648 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
650 Q_Q(QNetworkReplyImpl);
652 if (!downloadBuffer) {
653 // We are requested to create it
654 // Check attribute() if allocating a buffer of that size can be allowed
655 QVariant bufferAllocationPolicy = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
656 if (bufferAllocationPolicy.isValid() && bufferAllocationPolicy.toLongLong() >= size) {
657 downloadBufferCurrentSize = 0;
658 downloadBufferMaximumSize = size;
659 downloadBuffer = new char[downloadBufferMaximumSize]; // throws if allocation fails
660 downloadBufferPointer = QSharedPointer<char>(downloadBuffer, downloadBufferDeleter);
662 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
666 return downloadBuffer;
669 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
671 Q_Q(QNetworkReplyImpl);
673 downloadBufferPointer = sp;
674 downloadBuffer = downloadBufferPointer.data();
675 downloadBufferCurrentSize = 0;
676 downloadBufferMaximumSize = size;
677 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
681 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
683 Q_Q(QNetworkReplyImpl);
687 if (cacheEnabled && !cacheSaveDevice)
688 initCacheSaveDevice();
690 if (cacheSaveDevice && bytesReceived == bytesTotal) {
691 // if (lastBytesDownloaded == -1)
692 // lastBytesDownloaded = 0;
693 // cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
695 // Write everything in one go if we use a download buffer. might be more performant.
696 cacheSaveDevice->write(downloadBuffer, bytesTotal);
699 bytesDownloaded = bytesReceived;
700 lastBytesDownloaded = bytesReceived;
702 downloadBufferCurrentSize = bytesReceived;
704 // Only emit readyRead when actual data is there
705 // emit readyRead before downloadProgress incase this will cause events to be
706 // processed and we get into a recursive call (as in QProgressDialog).
707 if (bytesDownloaded > 0)
709 emit q->downloadProgress(bytesDownloaded, bytesTotal);
712 void QNetworkReplyImplPrivate::finished()
714 Q_Q(QNetworkReplyImpl);
716 if (state == Finished || state == Aborted || state == WaitingForSession)
719 pauseNotificationHandling();
720 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
721 if (preMigrationDownloaded != Q_INT64_C(-1))
722 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
724 if (!manager.isNull()) {
725 #ifndef QT_NO_BEARERMANAGEMENT
726 QNetworkSession *session = manager->d_func()->networkSession.data();
727 if (session && session->state() == QNetworkSession::Roaming &&
728 state == Working && errorCode != QNetworkReply::OperationCanceledError) {
729 // only content with a known size will fail with a temporary network failure error
730 if (!totalSize.isNull()) {
731 if (bytesDownloaded != totalSize) {
732 if (migrateBackend()) {
733 // either we are migrating or the request is finished/aborted
734 if (state == Reconnecting || state == WaitingForSession) {
735 resumeNotificationHandling();
736 return; // exit early if we are migrating.
739 error(QNetworkReply::TemporaryNetworkFailureError,
740 QNetworkReply::tr("Temporary network failure."));
747 resumeNotificationHandling();
750 q->setFinished(true);
752 pendingNotifications.clear();
754 pauseNotificationHandling();
755 if (totalSize.isNull() || totalSize == -1) {
756 emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
759 if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
760 emit q->uploadProgress(0, 0);
761 resumeNotificationHandling();
763 // if we don't know the total size of or we received everything save the cache
764 if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
767 // note: might not be a good idea, since users could decide to delete us
768 // which would delete the backend too...
769 // maybe we should protect the backend
770 pauseNotificationHandling();
771 emit q->readChannelFinished();
773 resumeNotificationHandling();
776 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
778 Q_Q(QNetworkReplyImpl);
779 // Can't set and emit multiple errors.
780 if (errorCode != QNetworkReply::NoError) {
781 qWarning( "QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.");
786 q->setErrorString(errorMessage);
788 // note: might not be a good idea, since users could decide to delete us
789 // which would delete the backend too...
790 // maybe we should protect the backend
794 void QNetworkReplyImplPrivate::metaDataChanged()
796 Q_Q(QNetworkReplyImpl);
797 // 1. do we have cookies?
798 // 2. are we allowed to set them?
799 if (cookedHeaders.contains(QNetworkRequest::SetCookieHeader) && !manager.isNull()
800 && (static_cast<QNetworkRequest::LoadControl>
801 (request.attribute(QNetworkRequest::CookieSaveControlAttribute,
802 QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic)) {
803 QList<QNetworkCookie> cookies =
804 qvariant_cast<QList<QNetworkCookie> >(cookedHeaders.value(QNetworkRequest::SetCookieHeader));
805 QNetworkCookieJar *jar = manager->cookieJar();
807 jar->setCookiesFromUrl(cookies, url);
809 emit q->metaDataChanged();
812 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
814 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
817 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
820 Q_Q(QNetworkReplyImpl);
821 emit q->sslErrors(errors);
827 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
828 : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
832 QNetworkReplyImpl::~QNetworkReplyImpl()
834 Q_D(QNetworkReplyImpl);
836 // This code removes the data from the cache if it was prematurely aborted.
837 // See QNetworkReplyImplPrivate::completeCacheSave(), we disable caching there after the cache
838 // save had been properly finished. So if it is still enabled it means we got deleted/aborted.
839 if (d->isCachingEnabled())
840 d->networkCache()->remove(url());
843 void QNetworkReplyImpl::abort()
845 Q_D(QNetworkReplyImpl);
846 if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
849 // stop both upload and download
851 disconnect(d->outgoingData, 0, this, 0);
853 disconnect(d->copyDevice, 0, this, 0);
855 QNetworkReply::close();
857 if (d->state != QNetworkReplyImplPrivate::Finished) {
858 // call finished which will emit signals
859 d->error(OperationCanceledError, tr("Operation canceled"));
860 if (d->state == QNetworkReplyImplPrivate::WaitingForSession)
861 d->state = QNetworkReplyImplPrivate::Working;
864 d->state = QNetworkReplyImplPrivate::Aborted;
866 // finished may access the backend
868 d->backend->deleteLater();
873 void QNetworkReplyImpl::close()
875 Q_D(QNetworkReplyImpl);
876 if (d->state == QNetworkReplyImplPrivate::Aborted ||
877 d->state == QNetworkReplyImplPrivate::Finished)
882 d->backend->closeDownstreamChannel();
884 disconnect(d->copyDevice, 0, this, 0);
886 QNetworkReply::close();
888 // call finished which will emit signals
889 d->error(OperationCanceledError, tr("Operation canceled"));
893 bool QNetworkReplyImpl::canReadLine () const
895 Q_D(const QNetworkReplyImpl);
896 return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
901 Returns the number of bytes available for reading with
902 QIODevice::read(). The number of bytes available may grow until
903 the finished() signal is emitted.
905 qint64 QNetworkReplyImpl::bytesAvailable() const
907 // Special case for the "zero copy" download buffer
908 Q_D(const QNetworkReplyImpl);
909 if (d->downloadBuffer) {
910 qint64 maxAvail = d->downloadBufferCurrentSize - d->downloadBufferReadPosition;
911 return QNetworkReply::bytesAvailable() + maxAvail;
914 return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
917 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
919 Q_D(QNetworkReplyImpl);
920 if (size > d->readBufferMaxSize &&
921 size > d->readBuffer.byteAmount())
922 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
924 QNetworkReply::setReadBufferSize(size);
927 d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
931 void QNetworkReplyImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
933 Q_D(const QNetworkReplyImpl);
935 d->backend->fetchSslConfiguration(configuration);
938 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
940 Q_D(QNetworkReplyImpl);
941 if (d->backend && !config.isNull())
942 d->backend->setSslConfiguration(config);
945 void QNetworkReplyImpl::ignoreSslErrors()
947 Q_D(QNetworkReplyImpl);
949 d->backend->ignoreSslErrors();
952 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
954 Q_D(QNetworkReplyImpl);
956 d->backend->ignoreSslErrors(errors);
963 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
965 Q_D(QNetworkReplyImpl);
967 // Special case code if we have the "zero copy" download buffer
968 if (d->downloadBuffer) {
969 qint64 maxAvail = qMin<qint64>(d->downloadBufferCurrentSize - d->downloadBufferReadPosition, maxlen);
971 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
972 // FIXME what about "Aborted" state?
973 qMemCopy(data, d->downloadBuffer + d->downloadBufferReadPosition, maxAvail);
974 d->downloadBufferReadPosition += maxAvail;
979 if (d->readBuffer.isEmpty())
980 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
981 // FIXME what about "Aborted" state?
983 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
985 // optimization for getChar()
986 *data = d->readBuffer.getChar();
990 maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
991 return d->readBuffer.read(data, maxlen);
995 \internal Reimplemented for internal purposes
997 bool QNetworkReplyImpl::event(QEvent *e)
999 if (e->type() == QEvent::NetworkReplyUpdated) {
1000 d_func()->handleNotifications();
1004 return QObject::event(e);
1008 Migrates the backend of the QNetworkReply to a new network connection if required. Returns
1009 true if the reply is migrated or it is not required; otherwise returns false.
1011 bool QNetworkReplyImplPrivate::migrateBackend()
1013 Q_Q(QNetworkReplyImpl);
1015 // Network reply is already finished or aborted, don't need to migrate.
1016 if (state == Finished || state == Aborted)
1019 // Request has outgoing data, not migrating.
1023 // Request is serviced from the cache, don't need to migrate.
1027 // Backend does not support resuming download.
1028 if (!backend->canResume())
1031 state = QNetworkReplyImplPrivate::Reconnecting;
1038 cookedHeaders.clear();
1041 preMigrationDownloaded = bytesDownloaded;
1043 backend = manager->d_func()->findBackend(operation, request);
1046 backend->setParent(q);
1047 backend->reply = this;
1048 backend->setResumeOffset(bytesDownloaded);
1052 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1054 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1055 #endif // QT_NO_HTTP
1060 #ifndef QT_NO_BEARERMANAGEMENT
1061 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1062 const QNetworkRequest &req,
1063 QNetworkAccessManager::Operation op)
1064 : QNetworkReply(parent)
1070 qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1072 QString msg = QCoreApplication::translate("QNetworkAccessManager",
1073 "Network access is disabled.");
1074 setError(UnknownNetworkError, msg);
1076 QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1077 Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1078 QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1081 QDisabledNetworkReply::~QDisabledNetworkReply()
1088 #include "moc_qnetworkreplyimpl_p.cpp"