1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtNetwork module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
42 #include "qnetworkreplyimpl_p.h"
43 #include "qnetworkaccessbackend_p.h"
44 #include "qnetworkcookie.h"
45 #include "qabstractnetworkcache.h"
46 #include "QtCore/qcoreapplication.h"
47 #include "QtCore/qdatetime.h"
48 #include "QtNetwork/qsslconfiguration.h"
49 #include "QtNetwork/qnetworksession.h"
50 #include "qnetworkaccessmanager_p.h"
52 #include <QtCore/QCoreApplication>
54 Q_DECLARE_METATYPE(QSharedPointer<char>)
58 inline QNetworkReplyImplPrivate::QNetworkReplyImplPrivate()
59 : backend(0), outgoingData(0),
61 cacheEnabled(false), cacheSaveDevice(0),
62 notificationHandlingPaused(false),
63 bytesDownloaded(0), lastBytesDownloaded(-1), bytesUploaded(-1), preMigrationDownloaded(-1),
66 , downloadBufferReadPosition(0)
67 , downloadBufferCurrentSize(0)
68 , downloadBufferMaximumSize(0)
73 void QNetworkReplyImplPrivate::_q_startOperation()
75 // ensure this function is only being called once
76 if (state == Working || state == Finished) {
77 qDebug("QNetworkReplyImpl::_q_startOperation was called more than once");
82 // note: if that method is called directly, it cannot happen that the backend is 0,
83 // because we just checked via a qobject_cast that we got a http backend (see
84 // QNetworkReplyImplPrivate::setup())
86 error(QNetworkReplyImpl::ProtocolUnknownError,
87 QCoreApplication::translate("QNetworkReply", "Protocol \"%1\" is unknown").arg(url.scheme())); // not really true!;
92 #ifndef QT_NO_BEARERMANAGEMENT
93 if (!backend->start()) { // ### we should call that method even if bearer is not used
94 // backend failed to start because the session state is not Connected.
95 // QNetworkAccessManager will call reply->backend->start() again for us when the session
97 state = WaitingForSession;
99 QNetworkSession *session = manager->d_func()->networkSession.data();
102 Q_Q(QNetworkReplyImpl);
104 QObject::connect(session, SIGNAL(error(QNetworkSession::SessionError)),
105 q, SLOT(_q_networkSessionFailed()));
107 if (!session->isOpen())
110 qWarning("Backend is waiting for QNetworkSession to connect, but there is none!");
117 if (backend && backend->isSynchronous()) {
119 q_func()->setFinished(true);
121 if (state != Finished) {
122 if (operation == QNetworkAccessManager::GetOperation)
123 pendingNotifications.append(NotifyDownstreamReadyWrite);
125 handleNotifications();
130 void QNetworkReplyImplPrivate::_q_copyReadyRead()
132 Q_Q(QNetworkReplyImpl);
133 if (state != Working)
135 if (!copyDevice || !q->isOpen())
138 // FIXME Optimize to use download buffer if it is a QBuffer.
139 // Needs to be done where sendCacheContents() (?) of HTTP is emitting
143 qint64 bytesToRead = nextDownstreamBlockSize();
144 if (bytesToRead == 0)
145 // we'll be called again, eventually
148 bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
150 byteData.resize(bytesToRead);
151 qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
152 if (bytesActuallyRead == -1) {
154 backendNotify(NotifyCopyFinished);
158 byteData.resize(bytesActuallyRead);
159 readBuffer.append(byteData);
161 if (!copyDevice->isSequential() && copyDevice->atEnd()) {
162 backendNotify(NotifyCopyFinished);
163 bytesDownloaded += bytesActuallyRead;
167 bytesDownloaded += bytesActuallyRead;
170 if (bytesDownloaded == lastBytesDownloaded) {
171 // we didn't read anything
175 lastBytesDownloaded = bytesDownloaded;
176 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
177 if (preMigrationDownloaded != Q_INT64_C(-1))
178 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
179 pauseNotificationHandling();
180 // emit readyRead before downloadProgress incase this will cause events to be
181 // processed and we get into a recursive call (as in QProgressDialog).
183 emit q->downloadProgress(bytesDownloaded,
184 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
185 resumeNotificationHandling();
188 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
193 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
195 Q_Q(QNetworkReplyImpl);
197 // make sure this is only called once, ever.
198 //_q_bufferOutgoingData may call it or the readChannelFinished emission
199 if (state != Buffering)
202 // disconnect signals
203 QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
204 QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
206 // finally, start the request
207 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
210 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
212 Q_Q(QNetworkReplyImpl);
214 if (!outgoingDataBuffer) {
215 // first call, create our buffer
216 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
218 QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
219 QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
222 qint64 bytesBuffered = 0;
223 qint64 bytesToBuffer = 0;
225 // read data into our buffer
227 bytesToBuffer = outgoingData->bytesAvailable();
228 // unknown? just try 2 kB, this also ensures we always try to read the EOF
229 if (bytesToBuffer <= 0)
230 bytesToBuffer = 2*1024;
232 char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
233 bytesBuffered = outgoingData->read(dst, bytesToBuffer);
235 if (bytesBuffered == -1) {
236 // EOF has been reached.
237 outgoingDataBuffer->chop(bytesToBuffer);
239 _q_bufferOutgoingDataFinished();
241 } else if (bytesBuffered == 0) {
242 // nothing read right now, just wait until we get called again
243 outgoingDataBuffer->chop(bytesToBuffer);
247 // don't break, try to read() again
248 outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
253 #ifndef QT_NO_BEARERMANAGEMENT
254 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
256 Q_Q(QNetworkReplyImpl);
258 if (manager.isNull())
261 QNetworkSession *session = manager->d_func()->networkSession.data();
265 if (session->state() != QNetworkSession::Connected)
269 case QNetworkReplyImplPrivate::Buffering:
270 case QNetworkReplyImplPrivate::Working:
271 case QNetworkReplyImplPrivate::Reconnecting:
272 // Migrate existing downloads to new network connection.
275 case QNetworkReplyImplPrivate::WaitingForSession:
276 // Start waiting requests.
277 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
284 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
286 // Abort waiting and working replies.
287 if (state == WaitingForSession || state == Working) {
289 error(QNetworkReplyImpl::UnknownNetworkError,
290 QCoreApplication::translate("QNetworkReply", "Network session error."));
296 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
299 Q_Q(QNetworkReplyImpl);
306 q->QIODevice::open(QIODevice::ReadOnly);
307 // Internal code that does a HTTP reply for the synchronous Ajax
309 QVariant synchronousHttpAttribute = req.attribute(
310 static_cast<QNetworkRequest::Attribute>(QNetworkRequest::SynchronousRequestAttribute));
311 // The synchronous HTTP is a corner case, we will put all upload data in one big QByteArray in the outgoingDataBuffer.
312 // Yes, this is not the most efficient thing to do, but on the other hand synchronous XHR needs to die anyway.
313 if (synchronousHttpAttribute.toBool() && outgoingData) {
314 outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
315 qint64 previousDataSize = 0;
317 previousDataSize = outgoingDataBuffer->size();
318 outgoingDataBuffer->append(outgoingData->readAll());
319 } while (outgoingDataBuffer->size() != previousDataSize);
323 backend->setSynchronous(synchronousHttpAttribute.toBool());
326 if (outgoingData && backend && !backend->isSynchronous()) {
327 // there is data to be uploaded, e.g. HTTP POST.
329 if (!backend->needsResetableUploadData() || !outgoingData->isSequential()) {
330 // backend does not need upload buffering or
331 // fixed size non-sequential
332 // just start the operation
333 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
335 bool bufferingDisallowed =
336 req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
339 if (bufferingDisallowed) {
340 // if a valid content-length header for the request was supplied, we can disable buffering
341 // if not, we will buffer anyway
342 if (req.header(QNetworkRequest::ContentLengthHeader).isValid()) {
343 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
346 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
349 // _q_startOperation will be called when the buffering has finished.
351 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
355 // for HTTP, we want to send out the request as fast as possible to the network, without
356 // invoking methods in a QueuedConnection
358 if (backend && backend->isSynchronous()) {
361 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
364 if (backend && backend->isSynchronous())
367 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
372 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
374 Q_Q(QNetworkReplyImpl);
375 if (!pendingNotifications.contains(notification))
376 pendingNotifications.enqueue(notification);
378 if (pendingNotifications.size() == 1)
379 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
382 void QNetworkReplyImplPrivate::handleNotifications()
384 if (notificationHandlingPaused)
387 NotificationQueue current = pendingNotifications;
388 pendingNotifications.clear();
390 if (state != Working)
393 while (state == Working && !current.isEmpty()) {
394 InternalNotifications notification = current.dequeue();
395 switch (notification) {
396 case NotifyDownstreamReadyWrite:
400 backend->downstreamReadyWrite();
403 case NotifyCloseDownstreamChannel:
404 backend->closeDownstreamChannel();
407 case NotifyCopyFinished: {
408 QIODevice *dev = copyDevice;
410 backend->copyFinished(dev);
417 // Do not handle the notifications while we are emitting downloadProgress
419 void QNetworkReplyImplPrivate::pauseNotificationHandling()
421 notificationHandlingPaused = true;
424 // Resume notification handling
425 void QNetworkReplyImplPrivate::resumeNotificationHandling()
427 Q_Q(QNetworkReplyImpl);
428 notificationHandlingPaused = false;
429 if (pendingNotifications.size() >= 1)
430 QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
433 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
437 return backend->networkCache();
440 void QNetworkReplyImplPrivate::createCache()
442 // check if we can save and if we're allowed to
444 || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool()
445 || request.attribute(QNetworkRequest::CacheLoadControlAttribute,
446 QNetworkRequest::PreferNetwork).toInt()
447 == QNetworkRequest::AlwaysNetwork)
452 bool QNetworkReplyImplPrivate::isCachingEnabled() const
454 return (cacheEnabled && networkCache() != 0);
457 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
459 if (!enable && !cacheEnabled)
460 return; // nothing to do
461 if (enable && cacheEnabled)
462 return; // nothing to do either!
465 if (bytesDownloaded) {
466 // refuse to enable in this case
467 qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
473 // someone told us to turn on, then back off?
474 // ok... but you should make up your mind
475 qDebug("QNetworkReplyImpl: setCachingEnabled(true) called after setCachingEnabled(false) -- "
476 "backend %s probably needs to be fixed",
477 backend->metaObject()->className());
478 networkCache()->remove(url);
480 cacheEnabled = false;
484 void QNetworkReplyImplPrivate::completeCacheSave()
486 if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
487 networkCache()->remove(url);
488 } else if (cacheEnabled && cacheSaveDevice) {
489 networkCache()->insert(cacheSaveDevice);
492 cacheEnabled = false;
495 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
497 Q_Q(QNetworkReplyImpl);
498 bytesUploaded = bytesSent;
499 pauseNotificationHandling();
500 emit q->uploadProgress(bytesSent, bytesTotal);
501 resumeNotificationHandling();
505 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
507 enum { DesiredBufferSize = 32 * 1024 };
508 if (readBufferMaxSize == 0)
509 return DesiredBufferSize;
511 return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
514 void QNetworkReplyImplPrivate::initCacheSaveDevice()
516 Q_Q(QNetworkReplyImpl);
518 // The disk cache does not support partial content, so don't even try to
519 // save any such content into the cache.
520 if (q->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 206) {
521 cacheEnabled = false;
525 // save the meta data
526 QNetworkCacheMetaData metaData;
527 metaData.setUrl(url);
528 metaData = backend->fetchCacheMetaData(metaData);
530 // save the redirect request also in the cache
531 QVariant redirectionTarget = q->attribute(QNetworkRequest::RedirectionTargetAttribute);
532 if (redirectionTarget.isValid()) {
533 QNetworkCacheMetaData::AttributesMap attributes = metaData.attributes();
534 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, redirectionTarget);
535 metaData.setAttributes(attributes);
538 cacheSaveDevice = networkCache()->prepare(metaData);
540 if (!cacheSaveDevice || (cacheSaveDevice && !cacheSaveDevice->isOpen())) {
541 if (cacheSaveDevice && !cacheSaveDevice->isOpen())
542 qCritical("QNetworkReplyImpl: network cache returned a device that is not open -- "
543 "class %s probably needs to be fixed",
544 networkCache()->metaObject()->className());
546 networkCache()->remove(url);
548 cacheEnabled = false;
552 // we received downstream data and send this to the cache
553 // and to our readBuffer (which in turn gets read by the user of QNetworkReply)
554 void QNetworkReplyImplPrivate::appendDownstreamData(QByteDataBuffer &data)
556 Q_Q(QNetworkReplyImpl);
560 if (cacheEnabled && !cacheSaveDevice) {
561 initCacheSaveDevice();
564 qint64 bytesWritten = 0;
565 for (int i = 0; i < data.bufferCount(); i++) {
566 QByteArray const &item = data[i];
569 cacheSaveDevice->write(item.constData(), item.size());
570 readBuffer.append(item);
572 bytesWritten += item.size();
576 bytesDownloaded += bytesWritten;
577 lastBytesDownloaded = bytesDownloaded;
579 appendDownstreamDataSignalEmissions();
582 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
584 Q_Q(QNetworkReplyImpl);
586 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
587 if (preMigrationDownloaded != Q_INT64_C(-1))
588 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
589 pauseNotificationHandling();
590 // important: At the point of this readyRead(), the data parameter list must be empty,
591 // else implicit sharing will trigger memcpy when the user is reading data!
593 // emit readyRead before downloadProgress incase this will cause events to be
594 // processed and we get into a recursive call (as in QProgressDialog).
595 emit q->downloadProgress(bytesDownloaded,
596 totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
598 resumeNotificationHandling();
599 // do we still have room in the buffer?
600 if (nextDownstreamBlockSize() > 0)
601 backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
604 // this is used when it was fetched from the cache, right?
605 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
607 Q_Q(QNetworkReplyImpl);
611 // read until EOF from data
613 qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
614 "backend probly needs to be fixed");
619 q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
620 q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
626 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
633 qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
636 static void downloadBufferDeleter(char *ptr)
641 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
643 Q_Q(QNetworkReplyImpl);
645 if (!downloadBuffer) {
646 // We are requested to create it
647 // Check attribute() if allocating a buffer of that size can be allowed
648 QVariant bufferAllocationPolicy = request.attribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute);
649 if (bufferAllocationPolicy.isValid() && bufferAllocationPolicy.toLongLong() >= size) {
650 downloadBufferCurrentSize = 0;
651 downloadBufferMaximumSize = size;
652 downloadBuffer = new char[downloadBufferMaximumSize]; // throws if allocation fails
653 downloadBufferPointer = QSharedPointer<char>(downloadBuffer, downloadBufferDeleter);
655 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
659 return downloadBuffer;
662 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
664 Q_Q(QNetworkReplyImpl);
666 downloadBufferPointer = sp;
667 downloadBuffer = downloadBufferPointer.data();
668 downloadBufferCurrentSize = 0;
669 downloadBufferMaximumSize = size;
670 q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
674 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
676 Q_Q(QNetworkReplyImpl);
680 if (cacheEnabled && !cacheSaveDevice)
681 initCacheSaveDevice();
683 if (cacheSaveDevice && bytesReceived == bytesTotal) {
684 // if (lastBytesDownloaded == -1)
685 // lastBytesDownloaded = 0;
686 // cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
688 // Write everything in one go if we use a download buffer. might be more performant.
689 cacheSaveDevice->write(downloadBuffer, bytesTotal);
692 bytesDownloaded = bytesReceived;
693 lastBytesDownloaded = bytesReceived;
695 downloadBufferCurrentSize = bytesReceived;
697 // Only emit readyRead when actual data is there
698 // emit readyRead before downloadProgress incase this will cause events to be
699 // processed and we get into a recursive call (as in QProgressDialog).
700 if (bytesDownloaded > 0)
702 emit q->downloadProgress(bytesDownloaded, bytesTotal);
705 void QNetworkReplyImplPrivate::finished()
707 Q_Q(QNetworkReplyImpl);
709 if (state == Finished || state == Aborted || state == WaitingForSession)
712 pauseNotificationHandling();
713 QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
714 if (preMigrationDownloaded != Q_INT64_C(-1))
715 totalSize = totalSize.toLongLong() + preMigrationDownloaded;
717 if (!manager.isNull()) {
718 #ifndef QT_NO_BEARERMANAGEMENT
719 QNetworkSession *session = manager->d_func()->networkSession.data();
720 if (session && session->state() == QNetworkSession::Roaming &&
721 state == Working && errorCode != QNetworkReply::OperationCanceledError) {
722 // only content with a known size will fail with a temporary network failure error
723 if (!totalSize.isNull()) {
724 if (bytesDownloaded != totalSize) {
725 if (migrateBackend()) {
726 // either we are migrating or the request is finished/aborted
727 if (state == Reconnecting || state == WaitingForSession) {
728 resumeNotificationHandling();
729 return; // exit early if we are migrating.
732 error(QNetworkReply::TemporaryNetworkFailureError,
733 QNetworkReply::tr("Temporary network failure."));
740 resumeNotificationHandling();
743 q->setFinished(true);
745 pendingNotifications.clear();
747 pauseNotificationHandling();
748 if (totalSize.isNull() || totalSize == -1) {
749 emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
752 if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
753 emit q->uploadProgress(0, 0);
754 resumeNotificationHandling();
756 // if we don't know the total size of or we received everything save the cache
757 if (totalSize.isNull() || totalSize == -1 || bytesDownloaded == totalSize)
760 // note: might not be a good idea, since users could decide to delete us
761 // which would delete the backend too...
762 // maybe we should protect the backend
763 pauseNotificationHandling();
764 emit q->readChannelFinished();
766 resumeNotificationHandling();
769 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
771 Q_Q(QNetworkReplyImpl);
772 // Can't set and emit multiple errors.
773 if (errorCode != QNetworkReply::NoError) {
774 qWarning() << "QNetworkReplyImplPrivate::error: Internal problem, this method must only be called once.";
779 q->setErrorString(errorMessage);
781 // note: might not be a good idea, since users could decide to delete us
782 // which would delete the backend too...
783 // maybe we should protect the backend
787 void QNetworkReplyImplPrivate::metaDataChanged()
789 Q_Q(QNetworkReplyImpl);
790 // 1. do we have cookies?
791 // 2. are we allowed to set them?
792 if (cookedHeaders.contains(QNetworkRequest::SetCookieHeader) && !manager.isNull()
793 && (static_cast<QNetworkRequest::LoadControl>
794 (request.attribute(QNetworkRequest::CookieSaveControlAttribute,
795 QNetworkRequest::Automatic).toInt()) == QNetworkRequest::Automatic)) {
796 QList<QNetworkCookie> cookies =
797 qvariant_cast<QList<QNetworkCookie> >(cookedHeaders.value(QNetworkRequest::SetCookieHeader));
798 QNetworkCookieJar *jar = manager->cookieJar();
800 jar->setCookiesFromUrl(cookies, url);
802 emit q->metaDataChanged();
805 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
807 attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
810 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
812 #ifndef QT_NO_OPENSSL
813 Q_Q(QNetworkReplyImpl);
814 emit q->sslErrors(errors);
820 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
821 : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
825 QNetworkReplyImpl::~QNetworkReplyImpl()
827 Q_D(QNetworkReplyImpl);
829 // This code removes the data from the cache if it was prematurely aborted.
830 // See QNetworkReplyImplPrivate::completeCacheSave(), we disable caching there after the cache
831 // save had been properly finished. So if it is still enabled it means we got deleted/aborted.
832 if (d->isCachingEnabled())
833 d->networkCache()->remove(url());
836 void QNetworkReplyImpl::abort()
838 Q_D(QNetworkReplyImpl);
839 if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
842 // stop both upload and download
844 disconnect(d->outgoingData, 0, this, 0);
846 disconnect(d->copyDevice, 0, this, 0);
848 QNetworkReply::close();
850 if (d->state != QNetworkReplyImplPrivate::Finished) {
851 // call finished which will emit signals
852 d->error(OperationCanceledError, tr("Operation canceled"));
855 d->state = QNetworkReplyImplPrivate::Aborted;
857 // finished may access the backend
859 d->backend->deleteLater();
864 void QNetworkReplyImpl::close()
866 Q_D(QNetworkReplyImpl);
867 if (d->state == QNetworkReplyImplPrivate::Aborted ||
868 d->state == QNetworkReplyImplPrivate::Finished)
873 d->backend->closeDownstreamChannel();
875 disconnect(d->copyDevice, 0, this, 0);
877 QNetworkReply::close();
879 // call finished which will emit signals
880 d->error(OperationCanceledError, tr("Operation canceled"));
884 bool QNetworkReplyImpl::canReadLine () const
886 Q_D(const QNetworkReplyImpl);
887 return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
892 Returns the number of bytes available for reading with
893 QIODevice::read(). The number of bytes available may grow until
894 the finished() signal is emitted.
896 qint64 QNetworkReplyImpl::bytesAvailable() const
898 // Special case for the "zero copy" download buffer
899 Q_D(const QNetworkReplyImpl);
900 if (d->downloadBuffer) {
901 qint64 maxAvail = d->downloadBufferCurrentSize - d->downloadBufferReadPosition;
902 return QNetworkReply::bytesAvailable() + maxAvail;
905 return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
908 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
910 Q_D(QNetworkReplyImpl);
911 if (size > d->readBufferMaxSize &&
912 size > d->readBuffer.byteAmount())
913 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
915 QNetworkReply::setReadBufferSize(size);
918 d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
921 #ifndef QT_NO_OPENSSL
922 QSslConfiguration QNetworkReplyImpl::sslConfigurationImplementation() const
924 Q_D(const QNetworkReplyImpl);
925 QSslConfiguration config;
927 d->backend->fetchSslConfiguration(config);
931 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
933 Q_D(QNetworkReplyImpl);
934 if (d->backend && !config.isNull())
935 d->backend->setSslConfiguration(config);
938 void QNetworkReplyImpl::ignoreSslErrors()
940 Q_D(QNetworkReplyImpl);
942 d->backend->ignoreSslErrors();
945 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
947 Q_D(QNetworkReplyImpl);
949 d->backend->ignoreSslErrors(errors);
951 #endif // QT_NO_OPENSSL
956 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
958 Q_D(QNetworkReplyImpl);
960 // Special case code if we have the "zero copy" download buffer
961 if (d->downloadBuffer) {
962 qint64 maxAvail = qMin<qint64>(d->downloadBufferCurrentSize - d->downloadBufferReadPosition, maxlen);
964 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
965 // FIXME what about "Aborted" state?
966 qMemCopy(data, d->downloadBuffer + d->downloadBufferReadPosition, maxAvail);
967 d->downloadBufferReadPosition += maxAvail;
972 if (d->readBuffer.isEmpty())
973 return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
974 // FIXME what about "Aborted" state?
976 d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
978 // optimization for getChar()
979 *data = d->readBuffer.getChar();
983 maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
984 return d->readBuffer.read(data, maxlen);
988 \internal Reimplemented for internal purposes
990 bool QNetworkReplyImpl::event(QEvent *e)
992 if (e->type() == QEvent::NetworkReplyUpdated) {
993 d_func()->handleNotifications();
997 return QObject::event(e);
1001 Migrates the backend of the QNetworkReply to a new network connection if required. Returns
1002 true if the reply is migrated or it is not required; otherwise returns false.
1004 bool QNetworkReplyImplPrivate::migrateBackend()
1006 Q_Q(QNetworkReplyImpl);
1008 // Network reply is already finished or aborted, don't need to migrate.
1009 if (state == Finished || state == Aborted)
1012 // Backend does not support resuming download.
1013 if (!backend->canResume())
1016 // Request has outgoing data, not migrating.
1020 // Request is serviced from the cache, don't need to migrate.
1024 state = QNetworkReplyImplPrivate::Reconnecting;
1031 cookedHeaders.clear();
1034 preMigrationDownloaded = bytesDownloaded;
1036 backend = manager->d_func()->findBackend(operation, request);
1039 backend->setParent(q);
1040 backend->reply = this;
1041 backend->setResumeOffset(bytesDownloaded);
1045 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1047 QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1048 #endif // QT_NO_HTTP
1053 #ifndef QT_NO_BEARERMANAGEMENT
1054 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1055 const QNetworkRequest &req,
1056 QNetworkAccessManager::Operation op)
1057 : QNetworkReply(parent)
1063 qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1065 QString msg = QCoreApplication::translate("QNetworkAccessManager",
1066 "Network access is disabled.");
1067 setError(UnknownNetworkError, msg);
1069 QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1070 Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1071 QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1074 QDisabledNetworkReply::~QDisabledNetworkReply()
1081 #include "moc_qnetworkreplyimpl_p.cpp"