Set ConnectInBackground based on request
[profile/ivi/qtbase.git] / src / network / access / qnetworkreplyimpl.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
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"
52
53 #include <QtCore/QCoreApplication>
54
55 Q_DECLARE_METATYPE(QSharedPointer<char>)
56
57 QT_BEGIN_NAMESPACE
58
59 inline QNetworkReplyImplPrivate::QNetworkReplyImplPrivate()
60     : backend(0), outgoingData(0),
61       copyDevice(0),
62       cacheEnabled(false), cacheSaveDevice(0),
63       notificationHandlingPaused(false),
64       bytesDownloaded(0), lastBytesDownloaded(-1), bytesUploaded(-1), preMigrationDownloaded(-1),
65       httpStatusCode(0),
66       state(Idle)
67       , downloadBufferReadPosition(0)
68       , downloadBufferCurrentSize(0)
69       , downloadBufferMaximumSize(0)
70       , downloadBuffer(0)
71 {
72 }
73
74 void QNetworkReplyImplPrivate::_q_startOperation()
75 {
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");
79         return;
80     }
81     state = Working;
82
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())
86     if (!backend) {
87         error(QNetworkReplyImpl::ProtocolUnknownError,
88               QCoreApplication::translate("QNetworkReply", "Protocol \"%1\" is unknown").arg(url.scheme())); // not really true!;
89         finished();
90         return;
91     }
92
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
97         // state changes.
98         state = WaitingForSession;
99
100         QNetworkSession *session = manager->d_func()->networkSession.data();
101
102         if (session) {
103             Q_Q(QNetworkReplyImpl);
104
105             QObject::connect(session, SIGNAL(error(QNetworkSession::SessionError)),
106                              q, SLOT(_q_networkSessionFailed()));
107
108             if (!session->isOpen()) {
109                 session->setSessionProperty(QStringLiteral("ConnectInBackground"),
110                     backend->request().attribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(false)));
111                 session->open();
112             }
113         } else {
114             qWarning("Backend is waiting for QNetworkSession to connect, but there is none!");
115             state = Working;
116             error(QNetworkReplyImpl::UnknownNetworkError,
117                   QCoreApplication::translate("QNetworkReply", "Network session error."));
118             finished();
119         }
120 #else
121         qWarning("Backend start failed");
122         state = Working;
123         error(QNetworkReplyImpl::UnknownNetworkError,
124               QCoreApplication::translate("QNetworkReply", "backend start error."));
125         finished();
126 #endif
127         return;
128     }
129
130     if (backend && backend->isSynchronous()) {
131         state = Finished;
132         q_func()->setFinished(true);
133     } else {
134         if (state != Finished) {
135             if (operation == QNetworkAccessManager::GetOperation)
136                 pendingNotifications.append(NotifyDownstreamReadyWrite);
137
138             handleNotifications();
139         }
140     }
141 }
142
143 void QNetworkReplyImplPrivate::_q_copyReadyRead()
144 {
145     Q_Q(QNetworkReplyImpl);
146     if (state != Working)
147         return;
148     if (!copyDevice || !q->isOpen())
149         return;
150
151     // FIXME Optimize to use download buffer if it is a QBuffer.
152     // Needs to be done where sendCacheContents() (?) of HTTP is emitting
153     // metaDataChanged ?
154
155     forever {
156         qint64 bytesToRead = nextDownstreamBlockSize();
157         if (bytesToRead == 0)
158             // we'll be called again, eventually
159             break;
160
161         bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
162         QByteArray byteData;
163         byteData.resize(bytesToRead);
164         qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
165         if (bytesActuallyRead == -1) {
166             byteData.clear();
167             backendNotify(NotifyCopyFinished);
168             break;
169         }
170
171         byteData.resize(bytesActuallyRead);
172         readBuffer.append(byteData);
173
174         if (!copyDevice->isSequential() && copyDevice->atEnd()) {
175             backendNotify(NotifyCopyFinished);
176             bytesDownloaded += bytesActuallyRead;
177             break;
178         }
179
180         bytesDownloaded += bytesActuallyRead;
181     }
182
183     if (bytesDownloaded == lastBytesDownloaded) {
184         // we didn't read anything
185         return;
186     }
187
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).
195     emit q->readyRead();
196     emit q->downloadProgress(bytesDownloaded,
197                              totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
198     resumeNotificationHandling();
199 }
200
201 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
202 {
203     _q_copyReadyRead();
204 }
205
206 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
207 {
208     Q_Q(QNetworkReplyImpl);
209
210     // make sure this is only called once, ever.
211     //_q_bufferOutgoingData may call it or the readChannelFinished emission
212     if (state != Buffering)
213         return;
214
215     // disconnect signals
216     QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
217     QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
218
219     // finally, start the request
220     QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
221 }
222
223 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
224 {
225     Q_Q(QNetworkReplyImpl);
226
227     if (!outgoingDataBuffer) {
228         // first call, create our buffer
229         outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
230
231         QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
232         QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
233     }
234
235     qint64 bytesBuffered = 0;
236     qint64 bytesToBuffer = 0;
237
238     // read data into our buffer
239     forever {
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;
244
245         char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
246         bytesBuffered = outgoingData->read(dst, bytesToBuffer);
247
248         if (bytesBuffered == -1) {
249             // EOF has been reached.
250             outgoingDataBuffer->chop(bytesToBuffer);
251
252             _q_bufferOutgoingDataFinished();
253             break;
254         } else if (bytesBuffered == 0) {
255             // nothing read right now, just wait until we get called again
256             outgoingDataBuffer->chop(bytesToBuffer);
257
258             break;
259         } else {
260             // don't break, try to read() again
261             outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
262         }
263     }
264 }
265
266 #ifndef QT_NO_BEARERMANAGEMENT
267 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
268 {
269     Q_Q(QNetworkReplyImpl);
270
271     if (manager.isNull())
272         return;
273
274     QNetworkSession *session = manager->d_func()->networkSession.data();
275     if (!session)
276         return;
277
278     if (session->state() != QNetworkSession::Connected)
279         return;
280
281     switch (state) {
282     case QNetworkReplyImplPrivate::Buffering:
283     case QNetworkReplyImplPrivate::Working:
284     case QNetworkReplyImplPrivate::Reconnecting:
285         // Migrate existing downloads to new network connection.
286         migrateBackend();
287         break;
288     case QNetworkReplyImplPrivate::WaitingForSession:
289         // Start waiting requests.
290         QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
291         break;
292     default:
293         ;
294     }
295 }
296
297 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
298 {
299     // Abort waiting and working replies.
300     if (state == WaitingForSession || state == Working) {
301         state = Working;
302         error(QNetworkReplyImpl::UnknownNetworkError,
303               QCoreApplication::translate("QNetworkReply", "Network session error."));
304         finished();
305     }
306 }
307 #endif
308
309 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
310                                      QIODevice *data)
311 {
312     Q_Q(QNetworkReplyImpl);
313
314     outgoingData = data;
315     request = req;
316     url = request.url();
317     operation = op;
318
319     q->QIODevice::open(QIODevice::ReadOnly);
320     // Internal code that does a HTTP reply for the synchronous Ajax
321     // in QtWebKit.
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;
329         do {
330             previousDataSize = outgoingDataBuffer->size();
331             outgoingDataBuffer->append(outgoingData->readAll());
332         } while (outgoingDataBuffer->size() != previousDataSize);
333     }
334
335     if (backend)
336         backend->setSynchronous(synchronousHttpAttribute.toBool());
337
338
339     if (outgoingData && backend && !backend->isSynchronous()) {
340         // there is data to be uploaded, e.g. HTTP POST.
341
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);
347         } else {
348             bool bufferingDisallowed =
349                     req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
350                                   false).toBool();
351
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);
357                 } else {
358                     state = Buffering;
359                     QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
360                 }
361             } else {
362                 // _q_startOperation will be called when the buffering has finished.
363                 state = Buffering;
364                 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
365             }
366         }
367     } else {
368         // for HTTP, we want to send out the request as fast as possible to the network, without
369         // invoking methods in a QueuedConnection
370 #ifndef QT_NO_HTTP
371         if (backend && backend->isSynchronous()) {
372             _q_startOperation();
373         } else {
374             QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
375         }
376 #else
377         if (backend && backend->isSynchronous())
378             _q_startOperation();
379         else
380             QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
381 #endif // QT_NO_HTTP
382         }
383 }
384
385 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
386 {
387     Q_Q(QNetworkReplyImpl);
388     if (!pendingNotifications.contains(notification))
389         pendingNotifications.enqueue(notification);
390
391     if (pendingNotifications.size() == 1)
392         QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
393 }
394
395 void QNetworkReplyImplPrivate::handleNotifications()
396 {
397     if (notificationHandlingPaused)
398         return;
399
400     NotificationQueue current = pendingNotifications;
401     pendingNotifications.clear();
402
403     if (state != Working)
404         return;
405
406     while (state == Working && !current.isEmpty()) {
407         InternalNotifications notification = current.dequeue();
408         switch (notification) {
409         case NotifyDownstreamReadyWrite:
410             if (copyDevice)
411                 _q_copyReadyRead();
412             else
413                 backend->downstreamReadyWrite();
414             break;
415
416         case NotifyCloseDownstreamChannel:
417             backend->closeDownstreamChannel();
418             break;
419
420         case NotifyCopyFinished: {
421             QIODevice *dev = copyDevice;
422             copyDevice = 0;
423             backend->copyFinished(dev);
424             break;
425         }
426         }
427     }
428 }
429
430 // Do not handle the notifications while we are emitting downloadProgress
431 // or readyRead
432 void QNetworkReplyImplPrivate::pauseNotificationHandling()
433 {
434     notificationHandlingPaused = true;
435 }
436
437 // Resume notification handling
438 void QNetworkReplyImplPrivate::resumeNotificationHandling()
439 {
440     Q_Q(QNetworkReplyImpl);
441     notificationHandlingPaused = false;
442     if (pendingNotifications.size() >= 1)
443         QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
444 }
445
446 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
447 {
448     if (!backend)
449         return 0;
450     return backend->networkCache();
451 }
452
453 void QNetworkReplyImplPrivate::createCache()
454 {
455     // check if we can save and if we're allowed to
456     if (!networkCache()
457         || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool()
458         || request.attribute(QNetworkRequest::CacheLoadControlAttribute,
459                              QNetworkRequest::PreferNetwork).toInt()
460             == QNetworkRequest::AlwaysNetwork)
461         return;
462     cacheEnabled = true;
463 }
464
465 bool QNetworkReplyImplPrivate::isCachingEnabled() const
466 {
467     return (cacheEnabled && networkCache() != 0);
468 }
469
470 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
471 {
472     if (!enable && !cacheEnabled)
473         return;                 // nothing to do
474     if (enable && cacheEnabled)
475         return;                 // nothing to do either!
476
477     if (enable) {
478         if (bytesDownloaded) {
479             // refuse to enable in this case
480             qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
481             return;
482         }
483
484         createCache();
485     } else {
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);
492         cacheSaveDevice = 0;
493         cacheEnabled = false;
494     }
495 }
496
497 void QNetworkReplyImplPrivate::completeCacheSave()
498 {
499     if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
500         networkCache()->remove(url);
501     } else if (cacheEnabled && cacheSaveDevice) {
502         networkCache()->insert(cacheSaveDevice);
503     }
504     cacheSaveDevice = 0;
505     cacheEnabled = false;
506 }
507
508 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
509 {
510     Q_Q(QNetworkReplyImpl);
511     bytesUploaded = bytesSent;
512     pauseNotificationHandling();
513     emit q->uploadProgress(bytesSent, bytesTotal);
514     resumeNotificationHandling();
515 }
516
517
518 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
519 {
520     enum { DesiredBufferSize = 32 * 1024 };
521     if (readBufferMaxSize == 0)
522         return DesiredBufferSize;
523
524     return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
525 }
526
527 void QNetworkReplyImplPrivate::initCacheSaveDevice()
528 {
529     Q_Q(QNetworkReplyImpl);
530
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;
535         return;
536     }
537
538     // save the meta data
539     QNetworkCacheMetaData metaData;
540     metaData.setUrl(url);
541     metaData = backend->fetchCacheMetaData(metaData);
542
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);
549     }
550
551     cacheSaveDevice = networkCache()->prepare(metaData);
552
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());
558
559         networkCache()->remove(url);
560         cacheSaveDevice = 0;
561         cacheEnabled = false;
562     }
563 }
564
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)
568 {
569     Q_Q(QNetworkReplyImpl);
570     if (!q->isOpen())
571         return;
572
573     if (cacheEnabled && !cacheSaveDevice) {
574         initCacheSaveDevice();
575     }
576
577     qint64 bytesWritten = 0;
578     for (int i = 0; i < data.bufferCount(); i++) {
579         QByteArray const &item = data[i];
580
581         if (cacheSaveDevice)
582             cacheSaveDevice->write(item.constData(), item.size());
583         readBuffer.append(item);
584
585         bytesWritten += item.size();
586     }
587     data.clear();
588
589     bytesDownloaded += bytesWritten;
590     lastBytesDownloaded = bytesDownloaded;
591
592     appendDownstreamDataSignalEmissions();
593 }
594
595 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
596 {
597     Q_Q(QNetworkReplyImpl);
598
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!
605     emit q->readyRead();
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());
610
611     resumeNotificationHandling();
612     // do we still have room in the buffer?
613     if (nextDownstreamBlockSize() > 0)
614         backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
615 }
616
617 // this is used when it was fetched from the cache, right?
618 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
619 {
620     Q_Q(QNetworkReplyImpl);
621     if (!q->isOpen())
622         return;
623
624     // read until EOF from data
625     if (copyDevice) {
626         qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
627                   "backend probly needs to be fixed");
628         return;
629     }
630
631     copyDevice = data;
632     q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
633     q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
634
635     // start the copy:
636     _q_copyReadyRead();
637 }
638
639 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
640 {
641     Q_UNUSED(data)
642     // TODO implement
643
644     // TODO call
645
646     qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
647 }
648
649 static void downloadBufferDeleter(char *ptr)
650 {
651     delete[] ptr;
652 }
653
654 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
655 {
656     Q_Q(QNetworkReplyImpl);
657
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);
667
668             q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
669         }
670     }
671
672     return downloadBuffer;
673 }
674
675 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
676 {
677     Q_Q(QNetworkReplyImpl);
678
679     downloadBufferPointer = sp;
680     downloadBuffer = downloadBufferPointer.data();
681     downloadBufferCurrentSize = 0;
682     downloadBufferMaximumSize = size;
683     q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
684 }
685
686
687 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
688 {
689     Q_Q(QNetworkReplyImpl);
690     if (!q->isOpen())
691         return;
692
693     if (cacheEnabled && !cacheSaveDevice)
694         initCacheSaveDevice();
695
696     if (cacheSaveDevice && bytesReceived == bytesTotal) {
697 //        if (lastBytesDownloaded == -1)
698 //            lastBytesDownloaded = 0;
699 //        cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
700
701         // Write everything in one go if we use a download buffer. might be more performant.
702         cacheSaveDevice->write(downloadBuffer, bytesTotal);
703     }
704
705     bytesDownloaded = bytesReceived;
706     lastBytesDownloaded = bytesReceived;
707
708     downloadBufferCurrentSize = bytesReceived;
709
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)
714         emit q->readyRead();
715     emit q->downloadProgress(bytesDownloaded, bytesTotal);
716 }
717
718 void QNetworkReplyImplPrivate::finished()
719 {
720     Q_Q(QNetworkReplyImpl);
721
722     if (state == Finished || state == Aborted || state == WaitingForSession)
723         return;
724
725     pauseNotificationHandling();
726     QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
727     if (preMigrationDownloaded != Q_INT64_C(-1))
728         totalSize = totalSize.toLongLong() + preMigrationDownloaded;
729
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.
743                         }
744                     } else {
745                         error(QNetworkReply::TemporaryNetworkFailureError,
746                               QNetworkReply::tr("Temporary network failure."));
747                     }
748                 }
749             }
750         }
751 #endif
752     }
753     resumeNotificationHandling();
754
755     state = Finished;
756     q->setFinished(true);
757
758     pendingNotifications.clear();
759
760     pauseNotificationHandling();
761     if (totalSize.isNull() || totalSize == -1) {
762         emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
763     }
764
765     if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
766         emit q->uploadProgress(0, 0);
767     resumeNotificationHandling();
768
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)
771         completeCacheSave();
772
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();
778     emit q->finished();
779     resumeNotificationHandling();
780 }
781
782 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
783 {
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.");
788         return;
789     }
790
791     errorCode = code;
792     q->setErrorString(errorMessage);
793
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
797     emit q->error(code);
798 }
799
800 void QNetworkReplyImplPrivate::metaDataChanged()
801 {
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();
812         if (jar)
813             jar->setCookiesFromUrl(cookies, url);
814     }
815     emit q->metaDataChanged();
816 }
817
818 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
819 {
820     attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
821 }
822
823 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
824 {
825 #ifndef QT_NO_SSL
826     Q_Q(QNetworkReplyImpl);
827     emit q->sslErrors(errors);
828 #else
829     Q_UNUSED(errors);
830 #endif
831 }
832
833 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
834     : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
835 {
836 }
837
838 QNetworkReplyImpl::~QNetworkReplyImpl()
839 {
840     Q_D(QNetworkReplyImpl);
841
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());
847 }
848
849 void QNetworkReplyImpl::abort()
850 {
851     Q_D(QNetworkReplyImpl);
852     if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
853         return;
854
855     // stop both upload and download
856     if (d->outgoingData)
857         disconnect(d->outgoingData, 0, this, 0);
858     if (d->copyDevice)
859         disconnect(d->copyDevice, 0, this, 0);
860
861     QNetworkReply::close();
862
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;
868         d->finished();
869     }
870     d->state = QNetworkReplyImplPrivate::Aborted;
871
872     // finished may access the backend
873     if (d->backend) {
874         d->backend->deleteLater();
875         d->backend = 0;
876     }
877 }
878
879 void QNetworkReplyImpl::close()
880 {
881     Q_D(QNetworkReplyImpl);
882     if (d->state == QNetworkReplyImplPrivate::Aborted ||
883         d->state == QNetworkReplyImplPrivate::Finished)
884         return;
885
886     // stop the download
887     if (d->backend)
888         d->backend->closeDownstreamChannel();
889     if (d->copyDevice)
890         disconnect(d->copyDevice, 0, this, 0);
891
892     QNetworkReply::close();
893
894     // call finished which will emit signals
895     d->error(OperationCanceledError, tr("Operation canceled"));
896     d->finished();
897 }
898
899 bool QNetworkReplyImpl::canReadLine () const
900 {
901     Q_D(const QNetworkReplyImpl);
902     return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
903 }
904
905
906 /*!
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.
910 */
911 qint64 QNetworkReplyImpl::bytesAvailable() const
912 {
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;
918     }
919
920     return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
921 }
922
923 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
924 {
925     Q_D(QNetworkReplyImpl);
926     if (size > d->readBufferMaxSize &&
927         size > d->readBuffer.byteAmount())
928         d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
929
930     QNetworkReply::setReadBufferSize(size);
931
932     if (d->backend)
933         d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
934 }
935
936 #ifndef QT_NO_SSL
937 void QNetworkReplyImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
938 {
939     Q_D(const QNetworkReplyImpl);
940     if (d->backend)
941         d->backend->fetchSslConfiguration(configuration);
942 }
943
944 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
945 {
946     Q_D(QNetworkReplyImpl);
947     if (d->backend && !config.isNull())
948         d->backend->setSslConfiguration(config);
949 }
950
951 void QNetworkReplyImpl::ignoreSslErrors()
952 {
953     Q_D(QNetworkReplyImpl);
954     if (d->backend)
955         d->backend->ignoreSslErrors();
956 }
957
958 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
959 {
960     Q_D(QNetworkReplyImpl);
961     if (d->backend)
962         d->backend->ignoreSslErrors(errors);
963 }
964 #endif  // QT_NO_SSL
965
966 /*!
967     \internal
968 */
969 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
970 {
971     Q_D(QNetworkReplyImpl);
972
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);
976         if (maxAvail == 0)
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;
981         return maxAvail;
982     }
983
984
985     if (d->readBuffer.isEmpty())
986         return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
987     // FIXME what about "Aborted" state?
988
989     d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
990     if (maxlen == 1) {
991         // optimization for getChar()
992         *data = d->readBuffer.getChar();
993         return 1;
994     }
995
996     maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
997     return d->readBuffer.read(data, maxlen);
998 }
999
1000 /*!
1001    \internal Reimplemented for internal purposes
1002 */
1003 bool QNetworkReplyImpl::event(QEvent *e)
1004 {
1005     if (e->type() == QEvent::NetworkReplyUpdated) {
1006         d_func()->handleNotifications();
1007         return true;
1008     }
1009
1010     return QObject::event(e);
1011 }
1012
1013 /*
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.
1016 */
1017 bool QNetworkReplyImplPrivate::migrateBackend()
1018 {
1019     Q_Q(QNetworkReplyImpl);
1020
1021     // Network reply is already finished or aborted, don't need to migrate.
1022     if (state == Finished || state == Aborted)
1023         return true;
1024
1025     // Request has outgoing data, not migrating.
1026     if (outgoingData)
1027         return false;
1028
1029     // Request is serviced from the cache, don't need to migrate.
1030     if (copyDevice)
1031         return true;
1032
1033     // Backend does not support resuming download.
1034     if (!backend->canResume())
1035         return false;
1036
1037     state = QNetworkReplyImplPrivate::Reconnecting;
1038
1039     if (backend) {
1040         delete backend;
1041         backend = 0;
1042     }
1043
1044     cookedHeaders.clear();
1045     rawHeaders.clear();
1046
1047     preMigrationDownloaded = bytesDownloaded;
1048
1049     backend = manager->d_func()->findBackend(operation, request);
1050
1051     if (backend) {
1052         backend->setParent(q);
1053         backend->reply = this;
1054         backend->setResumeOffset(bytesDownloaded);
1055     }
1056
1057 #ifndef QT_NO_HTTP
1058     QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1059 #else
1060     QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1061 #endif // QT_NO_HTTP
1062
1063     return true;
1064 }
1065
1066 #ifndef QT_NO_BEARERMANAGEMENT
1067 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1068                                              const QNetworkRequest &req,
1069                                              QNetworkAccessManager::Operation op)
1070 :   QNetworkReply(parent)
1071 {
1072     setRequest(req);
1073     setUrl(req.url());
1074     setOperation(op);
1075
1076     qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1077
1078     QString msg = QCoreApplication::translate("QNetworkAccessManager",
1079                                               "Network access is disabled.");
1080     setError(UnknownNetworkError, msg);
1081
1082     QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1083         Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1084     QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1085 }
1086
1087 QDisabledNetworkReply::~QDisabledNetworkReply()
1088 {
1089 }
1090 #endif
1091
1092 QT_END_NAMESPACE
1093
1094 #include "moc_qnetworkreplyimpl_p.cpp"
1095