Responses to request with AlwaysNetwork set should be cached
[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->open();
110         } else {
111             qWarning("Backend is waiting for QNetworkSession to connect, but there is none!");
112             state = Working;
113             error(QNetworkReplyImpl::UnknownNetworkError,
114                   QCoreApplication::translate("QNetworkReply", "Network session error."));
115             finished();
116         }
117 #else
118         qWarning("Backend start failed");
119         state = Working;
120         error(QNetworkReplyImpl::UnknownNetworkError,
121               QCoreApplication::translate("QNetworkReply", "backend start error."));
122         finished();
123 #endif
124         return;
125     }
126
127     if (backend && backend->isSynchronous()) {
128         state = Finished;
129         q_func()->setFinished(true);
130     } else {
131         if (state != Finished) {
132             if (operation == QNetworkAccessManager::GetOperation)
133                 pendingNotifications.append(NotifyDownstreamReadyWrite);
134
135             handleNotifications();
136         }
137     }
138 }
139
140 void QNetworkReplyImplPrivate::_q_copyReadyRead()
141 {
142     Q_Q(QNetworkReplyImpl);
143     if (state != Working)
144         return;
145     if (!copyDevice || !q->isOpen())
146         return;
147
148     // FIXME Optimize to use download buffer if it is a QBuffer.
149     // Needs to be done where sendCacheContents() (?) of HTTP is emitting
150     // metaDataChanged ?
151
152     forever {
153         qint64 bytesToRead = nextDownstreamBlockSize();
154         if (bytesToRead == 0)
155             // we'll be called again, eventually
156             break;
157
158         bytesToRead = qBound<qint64>(1, bytesToRead, copyDevice->bytesAvailable());
159         QByteArray byteData;
160         byteData.resize(bytesToRead);
161         qint64 bytesActuallyRead = copyDevice->read(byteData.data(), byteData.size());
162         if (bytesActuallyRead == -1) {
163             byteData.clear();
164             backendNotify(NotifyCopyFinished);
165             break;
166         }
167
168         byteData.resize(bytesActuallyRead);
169         readBuffer.append(byteData);
170
171         if (!copyDevice->isSequential() && copyDevice->atEnd()) {
172             backendNotify(NotifyCopyFinished);
173             bytesDownloaded += bytesActuallyRead;
174             break;
175         }
176
177         bytesDownloaded += bytesActuallyRead;
178     }
179
180     if (bytesDownloaded == lastBytesDownloaded) {
181         // we didn't read anything
182         return;
183     }
184
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).
192     emit q->readyRead();
193     emit q->downloadProgress(bytesDownloaded,
194                              totalSize.isNull() ? Q_INT64_C(-1) : totalSize.toLongLong());
195     resumeNotificationHandling();
196 }
197
198 void QNetworkReplyImplPrivate::_q_copyReadChannelFinished()
199 {
200     _q_copyReadyRead();
201 }
202
203 void QNetworkReplyImplPrivate::_q_bufferOutgoingDataFinished()
204 {
205     Q_Q(QNetworkReplyImpl);
206
207     // make sure this is only called once, ever.
208     //_q_bufferOutgoingData may call it or the readChannelFinished emission
209     if (state != Buffering)
210         return;
211
212     // disconnect signals
213     QObject::disconnect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
214     QObject::disconnect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
215
216     // finally, start the request
217     QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
218 }
219
220 void QNetworkReplyImplPrivate::_q_bufferOutgoingData()
221 {
222     Q_Q(QNetworkReplyImpl);
223
224     if (!outgoingDataBuffer) {
225         // first call, create our buffer
226         outgoingDataBuffer = QSharedPointer<QRingBuffer>(new QRingBuffer());
227
228         QObject::connect(outgoingData, SIGNAL(readyRead()), q, SLOT(_q_bufferOutgoingData()));
229         QObject::connect(outgoingData, SIGNAL(readChannelFinished()), q, SLOT(_q_bufferOutgoingDataFinished()));
230     }
231
232     qint64 bytesBuffered = 0;
233     qint64 bytesToBuffer = 0;
234
235     // read data into our buffer
236     forever {
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;
241
242         char *dst = outgoingDataBuffer->reserve(bytesToBuffer);
243         bytesBuffered = outgoingData->read(dst, bytesToBuffer);
244
245         if (bytesBuffered == -1) {
246             // EOF has been reached.
247             outgoingDataBuffer->chop(bytesToBuffer);
248
249             _q_bufferOutgoingDataFinished();
250             break;
251         } else if (bytesBuffered == 0) {
252             // nothing read right now, just wait until we get called again
253             outgoingDataBuffer->chop(bytesToBuffer);
254
255             break;
256         } else {
257             // don't break, try to read() again
258             outgoingDataBuffer->chop(bytesToBuffer - bytesBuffered);
259         }
260     }
261 }
262
263 #ifndef QT_NO_BEARERMANAGEMENT
264 void QNetworkReplyImplPrivate::_q_networkSessionConnected()
265 {
266     Q_Q(QNetworkReplyImpl);
267
268     if (manager.isNull())
269         return;
270
271     QNetworkSession *session = manager->d_func()->networkSession.data();
272     if (!session)
273         return;
274
275     if (session->state() != QNetworkSession::Connected)
276         return;
277
278     switch (state) {
279     case QNetworkReplyImplPrivate::Buffering:
280     case QNetworkReplyImplPrivate::Working:
281     case QNetworkReplyImplPrivate::Reconnecting:
282         // Migrate existing downloads to new network connection.
283         migrateBackend();
284         break;
285     case QNetworkReplyImplPrivate::WaitingForSession:
286         // Start waiting requests.
287         QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
288         break;
289     default:
290         ;
291     }
292 }
293
294 void QNetworkReplyImplPrivate::_q_networkSessionFailed()
295 {
296     // Abort waiting and working replies.
297     if (state == WaitingForSession || state == Working) {
298         state = Working;
299         error(QNetworkReplyImpl::UnknownNetworkError,
300               QCoreApplication::translate("QNetworkReply", "Network session error."));
301         finished();
302     }
303 }
304 #endif
305
306 void QNetworkReplyImplPrivate::setup(QNetworkAccessManager::Operation op, const QNetworkRequest &req,
307                                      QIODevice *data)
308 {
309     Q_Q(QNetworkReplyImpl);
310
311     outgoingData = data;
312     request = req;
313     url = request.url();
314     operation = op;
315
316     q->QIODevice::open(QIODevice::ReadOnly);
317     // Internal code that does a HTTP reply for the synchronous Ajax
318     // in QtWebKit.
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;
326         do {
327             previousDataSize = outgoingDataBuffer->size();
328             outgoingDataBuffer->append(outgoingData->readAll());
329         } while (outgoingDataBuffer->size() != previousDataSize);
330     }
331
332     if (backend)
333         backend->setSynchronous(synchronousHttpAttribute.toBool());
334
335
336     if (outgoingData && backend && !backend->isSynchronous()) {
337         // there is data to be uploaded, e.g. HTTP POST.
338
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);
344         } else {
345             bool bufferingDisallowed =
346                     req.attribute(QNetworkRequest::DoNotBufferUploadDataAttribute,
347                                   false).toBool();
348
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);
354                 } else {
355                     state = Buffering;
356                     QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
357                 }
358             } else {
359                 // _q_startOperation will be called when the buffering has finished.
360                 state = Buffering;
361                 QMetaObject::invokeMethod(q, "_q_bufferOutgoingData", Qt::QueuedConnection);
362             }
363         }
364     } else {
365         // for HTTP, we want to send out the request as fast as possible to the network, without
366         // invoking methods in a QueuedConnection
367 #ifndef QT_NO_HTTP
368         if (backend && backend->isSynchronous()) {
369             _q_startOperation();
370         } else {
371             QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
372         }
373 #else
374         if (backend && backend->isSynchronous())
375             _q_startOperation();
376         else
377             QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
378 #endif // QT_NO_HTTP
379         }
380 }
381
382 void QNetworkReplyImplPrivate::backendNotify(InternalNotifications notification)
383 {
384     Q_Q(QNetworkReplyImpl);
385     if (!pendingNotifications.contains(notification))
386         pendingNotifications.enqueue(notification);
387
388     if (pendingNotifications.size() == 1)
389         QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
390 }
391
392 void QNetworkReplyImplPrivate::handleNotifications()
393 {
394     if (notificationHandlingPaused)
395         return;
396
397     NotificationQueue current = pendingNotifications;
398     pendingNotifications.clear();
399
400     if (state != Working)
401         return;
402
403     while (state == Working && !current.isEmpty()) {
404         InternalNotifications notification = current.dequeue();
405         switch (notification) {
406         case NotifyDownstreamReadyWrite:
407             if (copyDevice)
408                 _q_copyReadyRead();
409             else
410                 backend->downstreamReadyWrite();
411             break;
412
413         case NotifyCloseDownstreamChannel:
414             backend->closeDownstreamChannel();
415             break;
416
417         case NotifyCopyFinished: {
418             QIODevice *dev = copyDevice;
419             copyDevice = 0;
420             backend->copyFinished(dev);
421             break;
422         }
423         }
424     }
425 }
426
427 // Do not handle the notifications while we are emitting downloadProgress
428 // or readyRead
429 void QNetworkReplyImplPrivate::pauseNotificationHandling()
430 {
431     notificationHandlingPaused = true;
432 }
433
434 // Resume notification handling
435 void QNetworkReplyImplPrivate::resumeNotificationHandling()
436 {
437     Q_Q(QNetworkReplyImpl);
438     notificationHandlingPaused = false;
439     if (pendingNotifications.size() >= 1)
440         QCoreApplication::postEvent(q, new QEvent(QEvent::NetworkReplyUpdated));
441 }
442
443 QAbstractNetworkCache *QNetworkReplyImplPrivate::networkCache() const
444 {
445     if (!backend)
446         return 0;
447     return backend->networkCache();
448 }
449
450 void QNetworkReplyImplPrivate::createCache()
451 {
452     // check if we can save and if we're allowed to
453     if (!networkCache()
454         || !request.attribute(QNetworkRequest::CacheSaveControlAttribute, true).toBool())
455         return;
456     cacheEnabled = true;
457 }
458
459 bool QNetworkReplyImplPrivate::isCachingEnabled() const
460 {
461     return (cacheEnabled && networkCache() != 0);
462 }
463
464 void QNetworkReplyImplPrivate::setCachingEnabled(bool enable)
465 {
466     if (!enable && !cacheEnabled)
467         return;                 // nothing to do
468     if (enable && cacheEnabled)
469         return;                 // nothing to do either!
470
471     if (enable) {
472         if (bytesDownloaded) {
473             // refuse to enable in this case
474             qCritical("QNetworkReplyImpl: backend error: caching was enabled after some bytes had been written");
475             return;
476         }
477
478         createCache();
479     } else {
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);
486         cacheSaveDevice = 0;
487         cacheEnabled = false;
488     }
489 }
490
491 void QNetworkReplyImplPrivate::completeCacheSave()
492 {
493     if (cacheEnabled && errorCode != QNetworkReplyImpl::NoError) {
494         networkCache()->remove(url);
495     } else if (cacheEnabled && cacheSaveDevice) {
496         networkCache()->insert(cacheSaveDevice);
497     }
498     cacheSaveDevice = 0;
499     cacheEnabled = false;
500 }
501
502 void QNetworkReplyImplPrivate::emitUploadProgress(qint64 bytesSent, qint64 bytesTotal)
503 {
504     Q_Q(QNetworkReplyImpl);
505     bytesUploaded = bytesSent;
506     pauseNotificationHandling();
507     emit q->uploadProgress(bytesSent, bytesTotal);
508     resumeNotificationHandling();
509 }
510
511
512 qint64 QNetworkReplyImplPrivate::nextDownstreamBlockSize() const
513 {
514     enum { DesiredBufferSize = 32 * 1024 };
515     if (readBufferMaxSize == 0)
516         return DesiredBufferSize;
517
518     return qMax<qint64>(0, readBufferMaxSize - readBuffer.byteAmount());
519 }
520
521 void QNetworkReplyImplPrivate::initCacheSaveDevice()
522 {
523     Q_Q(QNetworkReplyImpl);
524
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;
529         return;
530     }
531
532     // save the meta data
533     QNetworkCacheMetaData metaData;
534     metaData.setUrl(url);
535     metaData = backend->fetchCacheMetaData(metaData);
536
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);
543     }
544
545     cacheSaveDevice = networkCache()->prepare(metaData);
546
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());
552
553         networkCache()->remove(url);
554         cacheSaveDevice = 0;
555         cacheEnabled = false;
556     }
557 }
558
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)
562 {
563     Q_Q(QNetworkReplyImpl);
564     if (!q->isOpen())
565         return;
566
567     if (cacheEnabled && !cacheSaveDevice) {
568         initCacheSaveDevice();
569     }
570
571     qint64 bytesWritten = 0;
572     for (int i = 0; i < data.bufferCount(); i++) {
573         QByteArray const &item = data[i];
574
575         if (cacheSaveDevice)
576             cacheSaveDevice->write(item.constData(), item.size());
577         readBuffer.append(item);
578
579         bytesWritten += item.size();
580     }
581     data.clear();
582
583     bytesDownloaded += bytesWritten;
584     lastBytesDownloaded = bytesDownloaded;
585
586     appendDownstreamDataSignalEmissions();
587 }
588
589 void QNetworkReplyImplPrivate::appendDownstreamDataSignalEmissions()
590 {
591     Q_Q(QNetworkReplyImpl);
592
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!
599     emit q->readyRead();
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());
604
605     resumeNotificationHandling();
606     // do we still have room in the buffer?
607     if (nextDownstreamBlockSize() > 0)
608         backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
609 }
610
611 // this is used when it was fetched from the cache, right?
612 void QNetworkReplyImplPrivate::appendDownstreamData(QIODevice *data)
613 {
614     Q_Q(QNetworkReplyImpl);
615     if (!q->isOpen())
616         return;
617
618     // read until EOF from data
619     if (copyDevice) {
620         qCritical("QNetworkReplyImpl: copy from QIODevice already in progress -- "
621                   "backend probly needs to be fixed");
622         return;
623     }
624
625     copyDevice = data;
626     q->connect(copyDevice, SIGNAL(readyRead()), SLOT(_q_copyReadyRead()));
627     q->connect(copyDevice, SIGNAL(readChannelFinished()), SLOT(_q_copyReadChannelFinished()));
628
629     // start the copy:
630     _q_copyReadyRead();
631 }
632
633 void QNetworkReplyImplPrivate::appendDownstreamData(const QByteArray &data)
634 {
635     Q_UNUSED(data)
636     // TODO implement
637
638     // TODO call
639
640     qFatal("QNetworkReplyImplPrivate::appendDownstreamData not implemented");
641 }
642
643 static void downloadBufferDeleter(char *ptr)
644 {
645     delete[] ptr;
646 }
647
648 char* QNetworkReplyImplPrivate::getDownloadBuffer(qint64 size)
649 {
650     Q_Q(QNetworkReplyImpl);
651
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);
661
662             q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
663         }
664     }
665
666     return downloadBuffer;
667 }
668
669 void QNetworkReplyImplPrivate::setDownloadBuffer(QSharedPointer<char> sp, qint64 size)
670 {
671     Q_Q(QNetworkReplyImpl);
672
673     downloadBufferPointer = sp;
674     downloadBuffer = downloadBufferPointer.data();
675     downloadBufferCurrentSize = 0;
676     downloadBufferMaximumSize = size;
677     q->setAttribute(QNetworkRequest::DownloadBufferAttribute, qVariantFromValue<QSharedPointer<char> > (downloadBufferPointer));
678 }
679
680
681 void QNetworkReplyImplPrivate::appendDownstreamDataDownloadBuffer(qint64 bytesReceived, qint64 bytesTotal)
682 {
683     Q_Q(QNetworkReplyImpl);
684     if (!q->isOpen())
685         return;
686
687     if (cacheEnabled && !cacheSaveDevice)
688         initCacheSaveDevice();
689
690     if (cacheSaveDevice && bytesReceived == bytesTotal) {
691 //        if (lastBytesDownloaded == -1)
692 //            lastBytesDownloaded = 0;
693 //        cacheSaveDevice->write(downloadBuffer + lastBytesDownloaded, bytesReceived - lastBytesDownloaded);
694
695         // Write everything in one go if we use a download buffer. might be more performant.
696         cacheSaveDevice->write(downloadBuffer, bytesTotal);
697     }
698
699     bytesDownloaded = bytesReceived;
700     lastBytesDownloaded = bytesReceived;
701
702     downloadBufferCurrentSize = bytesReceived;
703
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)
708         emit q->readyRead();
709     emit q->downloadProgress(bytesDownloaded, bytesTotal);
710 }
711
712 void QNetworkReplyImplPrivate::finished()
713 {
714     Q_Q(QNetworkReplyImpl);
715
716     if (state == Finished || state == Aborted || state == WaitingForSession)
717         return;
718
719     pauseNotificationHandling();
720     QVariant totalSize = cookedHeaders.value(QNetworkRequest::ContentLengthHeader);
721     if (preMigrationDownloaded != Q_INT64_C(-1))
722         totalSize = totalSize.toLongLong() + preMigrationDownloaded;
723
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.
737                         }
738                     } else {
739                         error(QNetworkReply::TemporaryNetworkFailureError,
740                               QNetworkReply::tr("Temporary network failure."));
741                     }
742                 }
743             }
744         }
745 #endif
746     }
747     resumeNotificationHandling();
748
749     state = Finished;
750     q->setFinished(true);
751
752     pendingNotifications.clear();
753
754     pauseNotificationHandling();
755     if (totalSize.isNull() || totalSize == -1) {
756         emit q->downloadProgress(bytesDownloaded, bytesDownloaded);
757     }
758
759     if (bytesUploaded == -1 && (outgoingData || outgoingDataBuffer))
760         emit q->uploadProgress(0, 0);
761     resumeNotificationHandling();
762
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)
765         completeCacheSave();
766
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();
772     emit q->finished();
773     resumeNotificationHandling();
774 }
775
776 void QNetworkReplyImplPrivate::error(QNetworkReplyImpl::NetworkError code, const QString &errorMessage)
777 {
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.");
782         return;
783     }
784
785     errorCode = code;
786     q->setErrorString(errorMessage);
787
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
791     emit q->error(code);
792 }
793
794 void QNetworkReplyImplPrivate::metaDataChanged()
795 {
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();
806         if (jar)
807             jar->setCookiesFromUrl(cookies, url);
808     }
809     emit q->metaDataChanged();
810 }
811
812 void QNetworkReplyImplPrivate::redirectionRequested(const QUrl &target)
813 {
814     attributes.insert(QNetworkRequest::RedirectionTargetAttribute, target);
815 }
816
817 void QNetworkReplyImplPrivate::sslErrors(const QList<QSslError> &errors)
818 {
819 #ifndef QT_NO_SSL
820     Q_Q(QNetworkReplyImpl);
821     emit q->sslErrors(errors);
822 #else
823     Q_UNUSED(errors);
824 #endif
825 }
826
827 QNetworkReplyImpl::QNetworkReplyImpl(QObject *parent)
828     : QNetworkReply(*new QNetworkReplyImplPrivate, parent)
829 {
830 }
831
832 QNetworkReplyImpl::~QNetworkReplyImpl()
833 {
834     Q_D(QNetworkReplyImpl);
835
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());
841 }
842
843 void QNetworkReplyImpl::abort()
844 {
845     Q_D(QNetworkReplyImpl);
846     if (d->state == QNetworkReplyImplPrivate::Finished || d->state == QNetworkReplyImplPrivate::Aborted)
847         return;
848
849     // stop both upload and download
850     if (d->outgoingData)
851         disconnect(d->outgoingData, 0, this, 0);
852     if (d->copyDevice)
853         disconnect(d->copyDevice, 0, this, 0);
854
855     QNetworkReply::close();
856
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;
862         d->finished();
863     }
864     d->state = QNetworkReplyImplPrivate::Aborted;
865
866     // finished may access the backend
867     if (d->backend) {
868         d->backend->deleteLater();
869         d->backend = 0;
870     }
871 }
872
873 void QNetworkReplyImpl::close()
874 {
875     Q_D(QNetworkReplyImpl);
876     if (d->state == QNetworkReplyImplPrivate::Aborted ||
877         d->state == QNetworkReplyImplPrivate::Finished)
878         return;
879
880     // stop the download
881     if (d->backend)
882         d->backend->closeDownstreamChannel();
883     if (d->copyDevice)
884         disconnect(d->copyDevice, 0, this, 0);
885
886     QNetworkReply::close();
887
888     // call finished which will emit signals
889     d->error(OperationCanceledError, tr("Operation canceled"));
890     d->finished();
891 }
892
893 bool QNetworkReplyImpl::canReadLine () const
894 {
895     Q_D(const QNetworkReplyImpl);
896     return QNetworkReply::canReadLine() || d->readBuffer.canReadLine();
897 }
898
899
900 /*!
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.
904 */
905 qint64 QNetworkReplyImpl::bytesAvailable() const
906 {
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;
912     }
913
914     return QNetworkReply::bytesAvailable() + d_func()->readBuffer.byteAmount();
915 }
916
917 void QNetworkReplyImpl::setReadBufferSize(qint64 size)
918 {
919     Q_D(QNetworkReplyImpl);
920     if (size > d->readBufferMaxSize &&
921         size > d->readBuffer.byteAmount())
922         d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
923
924     QNetworkReply::setReadBufferSize(size);
925
926     if (d->backend)
927         d->backend->setDownstreamLimited(d->readBufferMaxSize > 0);
928 }
929
930 #ifndef QT_NO_SSL
931 void QNetworkReplyImpl::sslConfigurationImplementation(QSslConfiguration &configuration) const
932 {
933     Q_D(const QNetworkReplyImpl);
934     if (d->backend)
935         d->backend->fetchSslConfiguration(configuration);
936 }
937
938 void QNetworkReplyImpl::setSslConfigurationImplementation(const QSslConfiguration &config)
939 {
940     Q_D(QNetworkReplyImpl);
941     if (d->backend && !config.isNull())
942         d->backend->setSslConfiguration(config);
943 }
944
945 void QNetworkReplyImpl::ignoreSslErrors()
946 {
947     Q_D(QNetworkReplyImpl);
948     if (d->backend)
949         d->backend->ignoreSslErrors();
950 }
951
952 void QNetworkReplyImpl::ignoreSslErrorsImplementation(const QList<QSslError> &errors)
953 {
954     Q_D(QNetworkReplyImpl);
955     if (d->backend)
956         d->backend->ignoreSslErrors(errors);
957 }
958 #endif  // QT_NO_SSL
959
960 /*!
961     \internal
962 */
963 qint64 QNetworkReplyImpl::readData(char *data, qint64 maxlen)
964 {
965     Q_D(QNetworkReplyImpl);
966
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);
970         if (maxAvail == 0)
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;
975         return maxAvail;
976     }
977
978
979     if (d->readBuffer.isEmpty())
980         return d->state == QNetworkReplyImplPrivate::Finished ? -1 : 0;
981     // FIXME what about "Aborted" state?
982
983     d->backendNotify(QNetworkReplyImplPrivate::NotifyDownstreamReadyWrite);
984     if (maxlen == 1) {
985         // optimization for getChar()
986         *data = d->readBuffer.getChar();
987         return 1;
988     }
989
990     maxlen = qMin<qint64>(maxlen, d->readBuffer.byteAmount());
991     return d->readBuffer.read(data, maxlen);
992 }
993
994 /*!
995    \internal Reimplemented for internal purposes
996 */
997 bool QNetworkReplyImpl::event(QEvent *e)
998 {
999     if (e->type() == QEvent::NetworkReplyUpdated) {
1000         d_func()->handleNotifications();
1001         return true;
1002     }
1003
1004     return QObject::event(e);
1005 }
1006
1007 /*
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.
1010 */
1011 bool QNetworkReplyImplPrivate::migrateBackend()
1012 {
1013     Q_Q(QNetworkReplyImpl);
1014
1015     // Network reply is already finished or aborted, don't need to migrate.
1016     if (state == Finished || state == Aborted)
1017         return true;
1018
1019     // Request has outgoing data, not migrating.
1020     if (outgoingData)
1021         return false;
1022
1023     // Request is serviced from the cache, don't need to migrate.
1024     if (copyDevice)
1025         return true;
1026
1027     // Backend does not support resuming download.
1028     if (!backend->canResume())
1029         return false;
1030
1031     state = QNetworkReplyImplPrivate::Reconnecting;
1032
1033     if (backend) {
1034         delete backend;
1035         backend = 0;
1036     }
1037
1038     cookedHeaders.clear();
1039     rawHeaders.clear();
1040
1041     preMigrationDownloaded = bytesDownloaded;
1042
1043     backend = manager->d_func()->findBackend(operation, request);
1044
1045     if (backend) {
1046         backend->setParent(q);
1047         backend->reply = this;
1048         backend->setResumeOffset(bytesDownloaded);
1049     }
1050
1051 #ifndef QT_NO_HTTP
1052     QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1053 #else
1054     QMetaObject::invokeMethod(q, "_q_startOperation", Qt::QueuedConnection);
1055 #endif // QT_NO_HTTP
1056
1057     return true;
1058 }
1059
1060 #ifndef QT_NO_BEARERMANAGEMENT
1061 QDisabledNetworkReply::QDisabledNetworkReply(QObject *parent,
1062                                              const QNetworkRequest &req,
1063                                              QNetworkAccessManager::Operation op)
1064 :   QNetworkReply(parent)
1065 {
1066     setRequest(req);
1067     setUrl(req.url());
1068     setOperation(op);
1069
1070     qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
1071
1072     QString msg = QCoreApplication::translate("QNetworkAccessManager",
1073                                               "Network access is disabled.");
1074     setError(UnknownNetworkError, msg);
1075
1076     QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
1077         Q_ARG(QNetworkReply::NetworkError, UnknownNetworkError));
1078     QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
1079 }
1080
1081 QDisabledNetworkReply::~QDisabledNetworkReply()
1082 {
1083 }
1084 #endif
1085
1086 QT_END_NAMESPACE
1087
1088 #include "moc_qnetworkreplyimpl_p.cpp"
1089