QNetworkReplyHandler.cpp 19.5 KB
Newer Older
1
/*
2
    Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
3
    Copyright (C) 2007 Staikos Computing Services Inc.  <info@staikos.net>
4
    Copyright (C) 2008 Holger Hans Peter Freyther
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "QNetworkReplyHandler.h"

#include "HTTPParsers.h"
#include "MIMETypeRegistry.h"
#include "ResourceHandle.h"
#include "ResourceHandleClient.h"
#include "ResourceHandleInternal.h"
#include "ResourceResponse.h"
#include "ResourceRequest.h"
31
#include <QDateTime>
32
#include <QFile>
33
#include <QFileInfo>
34
35
36
37
#include <QNetworkReply>
#include <QNetworkCookie>
#include <qwebframe.h>
#include <qwebpage.h>
38

39
#include <wtf/text/CString.h>
40

41
#include <QDebug>
42
#include <QCoreApplication>
43

44
45
// What type of connection should be used for the signals of the
// QNetworkReply? This depends on if Qt has a bugfix for this or not.
46
47
48
// It is fixed in Qt 4.6.3. See https://bugs.webkit.org/show_bug.cgi?id=32113
// and https://bugs.webkit.org/show_bug.cgi?id=36755
#if QT_VERSION > QT_VERSION_CHECK(4, 6, 2)
49
50
51
52
53
#define SIGNAL_CONN Qt::DirectConnection
#else
#define SIGNAL_CONN Qt::QueuedConnection
#endif

54
static const int gMaxRecursionLimit = 10;
55

56
57
namespace WebCore {

58
59
60
61
62
// Take a deep copy of the FormDataElement
FormDataIODevice::FormDataIODevice(FormData* data)
    : m_formElements(data ? data->elements() : Vector<FormDataElement>())
    , m_currentFile(0)
    , m_currentDelta(0)
63
64
    , m_fileSize(0)
    , m_dataSize(0)
65
66
{
    setOpenMode(FormDataIODevice::ReadOnly);
67
68
69

    if (!m_formElements.isEmpty() && m_formElements[0].m_type == FormDataElement::encodedFile)
        openFileForCurrentElement();
70
    computeSize();
71
72
73
74
75
76
77
}

FormDataIODevice::~FormDataIODevice()
{
    delete m_currentFile;
}

78
79
80
81
82
83
84
85
86
87
88
89
90
91
qint64 FormDataIODevice::computeSize() 
{
    for (int i = 0; i < m_formElements.size(); ++i) {
        const FormDataElement& element = m_formElements[i];
        if (element.m_type == FormDataElement::data) 
            m_dataSize += element.m_data.size();
        else {
            QFileInfo fi(element.m_filename);
            m_fileSize += fi.size();
        }
    }
    return m_dataSize + m_fileSize;
}

92
93
94
95
96
97
98
99
100
101
102
void FormDataIODevice::moveToNextElement()
{
    if (m_currentFile)
        m_currentFile->close();
    m_currentDelta = 0;

    m_formElements.remove(0);

    if (m_formElements.isEmpty() || m_formElements[0].m_type == FormDataElement::data)
        return;

103
104
105
106
107
    openFileForCurrentElement();
}

void FormDataIODevice::openFileForCurrentElement()
{
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    if (!m_currentFile)
        m_currentFile = new QFile;

    m_currentFile->setFileName(m_formElements[0].m_filename);
    m_currentFile->open(QFile::ReadOnly);
}

// m_formElements[0] is the current item. If the destination buffer is
// big enough we are going to read from more than one FormDataElement
qint64 FormDataIODevice::readData(char* destination, qint64 size)
{
    if (m_formElements.isEmpty())
        return -1;

    qint64 copied = 0;
    while (copied < size && !m_formElements.isEmpty()) {
        const FormDataElement& element = m_formElements[0];
        const qint64 available = size-copied;

        if (element.m_type == FormDataElement::data) {
            const qint64 toCopy = qMin<qint64>(available, element.m_data.size() - m_currentDelta);
            memcpy(destination+copied, element.m_data.data()+m_currentDelta, toCopy); 
            m_currentDelta += toCopy;
            copied += toCopy;

            if (m_currentDelta == element.m_data.size())
                moveToNextElement();
        } else {
            const QByteArray data = m_currentFile->read(available);
            memcpy(destination+copied, data.constData(), data.size());
            copied += data.size();

            if (m_currentFile->atEnd() || !m_currentFile->isOpen())
                moveToNextElement();
        }
    }

    return copied;
}

qint64 FormDataIODevice::writeData(const char*, qint64)
{
    return -1;
}

bool FormDataIODevice::isSequential() const
{
    return true;
}

158
String QNetworkReplyHandler::httpMethod() const
159
{
160
    switch (m_method) {
161
162
163
164
165
166
167
168
169
170
171
172
    case QNetworkAccessManager::GetOperation:
        return "GET";
    case QNetworkAccessManager::HeadOperation:
        return "HEAD";
    case QNetworkAccessManager::PostOperation:
        return "POST";
    case QNetworkAccessManager::PutOperation:
        return "PUT";
    case QNetworkAccessManager::DeleteOperation:
        return "DELETE";
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
    case QNetworkAccessManager::CustomOperation:
173
        return m_resourceHandle->firstRequest().httpMethod();
174
175
#endif
    default:
176
        ASSERT_NOT_REACHED();
177
178
179
180
        return "GET";
    }
}

181
QNetworkReplyHandler::QNetworkReplyHandler(ResourceHandle* handle, LoadMode loadMode)
182
    : QObject(0)
183
    , m_reply(0)
184
    , m_resourceHandle(handle)
185
186
    , m_redirected(false)
    , m_responseSent(false)
187
    , m_responseContainsData(false)
188
189
190
191
192
    , m_loadMode(loadMode)
    , m_shouldStart(true)
    , m_shouldFinish(false)
    , m_shouldSendResponse(false)
    , m_shouldForwardData(false)
193
    , m_redirectionTries(gMaxRecursionLimit)
194
{
ap@apple.com's avatar
ap@apple.com committed
195
    const ResourceRequest &r = m_resourceHandle->firstRequest();
196
197
198
199
200
201
202
203
204

    if (r.httpMethod() == "GET")
        m_method = QNetworkAccessManager::GetOperation;
    else if (r.httpMethod() == "HEAD")
        m_method = QNetworkAccessManager::HeadOperation;
    else if (r.httpMethod() == "POST")
        m_method = QNetworkAccessManager::PostOperation;
    else if (r.httpMethod() == "PUT")
        m_method = QNetworkAccessManager::PutOperation;
205
206
    else if (r.httpMethod() == "DELETE")
        m_method = QNetworkAccessManager::DeleteOperation;
207
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
208
    else
209
        m_method = QNetworkAccessManager::CustomOperation;
210
#else
211
212
    else
        m_method = QNetworkAccessManager::UnknownOperation;
213
#endif
214

215
216
217
218
219
    QObject* originatingObject = 0;
    if (m_resourceHandle->getInternal()->m_context)
        originatingObject = m_resourceHandle->getInternal()->m_context->originatingObject();

    m_request = r.toNetworkRequest(originatingObject);
220

221
222
223
224
225
226
    if (m_loadMode == LoadNormal)
        start();
}

void QNetworkReplyHandler::setLoadMode(LoadMode mode)
{
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    // https://bugs.webkit.org/show_bug.cgi?id=26556
    // We cannot call sendQueuedItems() from here, because the signal that 
    // caused us to get into deferred mode, might not be processed yet.
    switch (mode) {
    case LoadNormal:
        m_loadMode = LoadResuming;
        emit processQueuedItems();
        break;
    case LoadDeferred:
        m_loadMode = LoadDeferred;
        break;
    case LoadResuming:
        Q_ASSERT(0); // should never happen
        break;
    };
242
243
244
245
}

void QNetworkReplyHandler::abort()
{
246
    m_resourceHandle = 0;
247
    if (m_reply) {
248
249
        QNetworkReply* reply = release();
        reply->abort();
250
        reply->deleteLater();
251
    }
252
    deleteLater();
253
254
}

255
QNetworkReply* QNetworkReplyHandler::release()
256
{
257
    QNetworkReply* reply = m_reply;
258
259
    if (m_reply) {
        disconnect(m_reply, 0, this, 0);
260
261
262
263
        // We have queued connections to the QNetworkReply. Make sure any
        // posted meta call events that were the result of a signal emission
        // don't reach the slots in our instance.
        QCoreApplication::removePostedEvents(this, QEvent::MetaCall);
264
        m_reply->setParent(0);
265
266
267
268
269
        m_reply = 0;
    }
    return reply;
}

270
271
272
273
274
275
276
static bool ignoreHttpError(QNetworkReply* reply, bool receivedData)
{
    int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (httpStatusCode == 401 || httpStatusCode == 407)
        return true;

277
    if (receivedData && (httpStatusCode >= 400 && httpStatusCode < 600))
278
279
280
281
282
        return true;

    return false;
}

283
284
void QNetworkReplyHandler::finish()
{
285
286
    m_shouldFinish = (m_loadMode != LoadNormal);
    if (m_shouldFinish)
287
288
        return;

289
290
291
    if (!m_reply)
        return;

292
    sendResponseIfNeeded();
293

294
295
    if (!m_resourceHandle)
        return;
296
    ResourceHandleClient* client = m_resourceHandle->client();
297
298
299
    if (!client) {
        m_reply->deleteLater();
        m_reply = 0;
300
        return;
301
    }
302

303
304
305
    if (!m_redirected) {
        if (!m_reply->error() || ignoreHttpError(m_reply, m_responseContainsData)) {
            client->didFinishLoading(m_resourceHandle, 0);
306
        } else {
307
308
309
310
311
312
313
314
315
316
317
318
319
320
            QUrl url = m_reply->url();
            int httpStatusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

            if (httpStatusCode) {
                ResourceError error("HTTP", httpStatusCode, url.toString(), m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
                client->didFail(m_resourceHandle, error);
            } else {
                ResourceError error("QtNetwork", m_reply->error(), url.toString(), m_reply->errorString());
                client->didFail(m_resourceHandle, error);
            }
        }
        if (m_reply) {
            m_reply->deleteLater();
            m_reply = 0;
321
        }
322
323
324
325
326
327
328
    } else {
        if (m_reply) {
            m_reply->deleteLater();
            m_reply = 0;
        }
        resetState();
        start();
329
330
331
332
333
    }
}

void QNetworkReplyHandler::sendResponseIfNeeded()
{
334
335
    m_shouldSendResponse = (m_loadMode != LoadNormal);
    if (m_shouldSendResponse)
336
337
        return;

338
    if (m_reply->error() && !ignoreHttpError(m_reply, m_responseContainsData))
339
340
        return;

341
    if (m_responseSent || !m_resourceHandle)
342
343
344
345
346
347
348
        return;
    m_responseSent = true;

    ResourceHandleClient* client = m_resourceHandle->client();
    if (!client)
        return;

349
350
351
    WTF::String contentType = m_reply->header(QNetworkRequest::ContentTypeHeader).toString();
    WTF::String encoding = extractCharsetFromMediaType(contentType);
    WTF::String mimeType = extractMIMETypeFromMediaType(contentType);
352
353
354

    if (mimeType.isEmpty()) {
        // let's try to guess from the extension
355
        mimeType = MIMETypeRegistry::getMIMETypeForPath(m_reply->url().path());
356
357
    }

358
    KURL url(m_reply->url());
359
    ResourceResponse response(url, mimeType.lower(),
360
                              m_reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(),
361
                              encoding, String());
362

363
364
365
366
367
368
    if (url.isLocalFile()) {
        client->didReceiveResponse(m_resourceHandle, response);
        return;
    }

    // The status code is equal to 0 for protocols not in the HTTP family.
369
    int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
370
371
372
373
374
375
376
377
378

    if (url.protocolInHTTPFamily()) {
        String suggestedFilename = filenameFromHTTPContentDisposition(QString::fromAscii(m_reply->rawHeader("Content-Disposition")));

        if (!suggestedFilename.isEmpty())
            response.setSuggestedFilename(suggestedFilename);
        else
            response.setSuggestedFilename(url.lastPathComponent());

379
        response.setHTTPStatusCode(statusCode);
380
        response.setHTTPStatusText(m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray().constData());
381

382
        // Add remaining headers.
383
384
385
386
387
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
        foreach (const QNetworkReply::RawHeaderPair& pair, m_reply->rawHeaderPairs()) {
            response.setHTTPHeaderField(QString::fromAscii(pair.first), QString::fromAscii(pair.second));
        }
#else
388
389
390
        foreach (const QByteArray& headerName, m_reply->rawHeaderList()) {
            response.setHTTPHeaderField(QString::fromAscii(headerName), QString::fromAscii(m_reply->rawHeader(headerName)));
        }
391
#endif
392
    }
393
394
395

    QUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
    if (redirection.isValid()) {
396
        QUrl newUrl = m_reply->url().resolved(redirection);
397
398
399

        m_redirectionTries--;
        if (m_redirectionTries == 0) { // 10 or more redirections to the same url is considered infinite recursion
400
401
            ResourceError error(newUrl.host(), 400 /*bad request*/,
                                newUrl.toString(),
402
                                QCoreApplication::translate("QWebPage", "Redirection limit reached"));
403
404
405
            client->didFail(m_resourceHandle, error);
            return;
        }
406
407
        m_redirected = true;

408

409
410
411
412
413
        //  Status Code 301 (Moved Permanently), 302 (Moved Temporarily), 303 (See Other):
        //    - If original request is POST convert to GET and redirect automatically
        //  Status Code 307 (Temporary Redirect) and all other redirect status codes:
        //    - Use the HTTP method from the previous request
        if ((statusCode >= 301 && statusCode <= 303) && m_resourceHandle->firstRequest().httpMethod() == "POST")
414
            m_method = QNetworkAccessManager::GetOperation;
415
416

        ResourceRequest newRequest = m_resourceHandle->firstRequest();
417
        newRequest.setHTTPMethod(httpMethod());
418
        newRequest.setURL(newUrl);
419

420
421
422
423
        // Should not set Referer after a redirect from a secure resource to non-secure one.
        if (!newRequest.url().protocolIs("https") && protocolIs(newRequest.httpReferrer(), "https"))
            newRequest.clearHTTPReferrer();

424
        client->willSendRequest(m_resourceHandle, newRequest, response);
425
426
427
        if (!m_resourceHandle) // network error did cancel the request
            return;

428
429
430
431
432
        QObject* originatingObject = 0;
        if (m_resourceHandle->getInternal()->m_context)
            originatingObject = m_resourceHandle->getInternal()->m_context->originatingObject();

        m_request = newRequest.toNetworkRequest(originatingObject);
433
        return;
434
    }
435
436

    client->didReceiveResponse(m_resourceHandle, response);
437
438
439
440
}

void QNetworkReplyHandler::forwardData()
{
441
442
    m_shouldForwardData = (m_loadMode != LoadNormal);
    if (m_shouldForwardData)
443
444
        return;

445
446
447
    if (m_reply->bytesAvailable())
        m_responseContainsData = true;

448
449
450
451
452
453
    sendResponseIfNeeded();

    // don't emit the "Document has moved here" type of HTML
    if (m_redirected)
        return;

454
455
456
    if (!m_resourceHandle)
        return;

457
458
459
460
461
462
    QByteArray data = m_reply->read(m_reply->bytesAvailable());

    ResourceHandleClient* client = m_resourceHandle->client();
    if (!client)
        return;

463
    if (!data.isEmpty())
464
465
466
        client->didReceiveData(m_resourceHandle, data.constData(), data.length(), data.length() /*FixMe*/);
}

467
468
469
470
471
472
473
474
475
476
477
478
void QNetworkReplyHandler::uploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
    if (!m_resourceHandle)
        return;

    ResourceHandleClient* client = m_resourceHandle->client();
    if (!client)
        return;

    client->didSendData(m_resourceHandle, bytesSent, bytesTotal);
}

479
480
void QNetworkReplyHandler::start()
{
481
482
    m_shouldStart = false;

483
484
    ResourceHandleInternal* d = m_resourceHandle->getInternal();

485
486
487
488
489
490
    QNetworkAccessManager* manager = 0;
    if (d->m_context)
        manager = d->m_context->networkAccessManager();

    if (!manager)
        return;
491

492
493
494
495
496
    const QUrl url = m_request.url();
    const QString scheme = url.scheme();
    // Post requests on files and data don't really make sense, but for
    // fast/forms/form-post-urlencoded.html and for fast/forms/button-state-restore.html
    // we still need to retrieve the file/data, which means we map it to a Get instead.
497
    if (m_method == QNetworkAccessManager::PostOperation
498
        && (!url.toLocalFile().isEmpty() || url.scheme() == QLatin1String("data")))
499
500
        m_method = QNetworkAccessManager::GetOperation;

501
502
503
504
505
    switch (m_method) {
        case QNetworkAccessManager::GetOperation:
            m_reply = manager->get(m_request);
            break;
        case QNetworkAccessManager::PostOperation: {
ap@apple.com's avatar
ap@apple.com committed
506
            FormDataIODevice* postDevice = new FormDataIODevice(d->m_firstRequest.httpBody()); 
507
508
509
            // We may be uploading files so prevent QNR from buffering data
            m_request.setHeader(QNetworkRequest::ContentLengthHeader, postDevice->getFormDataSize());
            m_request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, QVariant(true));
510
511
            m_reply = manager->post(m_request, postDevice);
            postDevice->setParent(m_reply);
512
513
514
515
516
517
            break;
        }
        case QNetworkAccessManager::HeadOperation:
            m_reply = manager->head(m_request);
            break;
        case QNetworkAccessManager::PutOperation: {
ap@apple.com's avatar
ap@apple.com committed
518
            FormDataIODevice* putDevice = new FormDataIODevice(d->m_firstRequest.httpBody()); 
519
520
521
            // We may be uploading files so prevent QNR from buffering data
            m_request.setHeader(QNetworkRequest::ContentLengthHeader, putDevice->getFormDataSize());
            m_request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, QVariant(true));
522
523
            m_reply = manager->put(m_request, putDevice);
            putDevice->setParent(m_reply);
524
525
            break;
        }
526
527
528
529
        case QNetworkAccessManager::DeleteOperation: {
            m_reply = manager->deleteResource(m_request);
            break;
        }
530
#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
531
        case QNetworkAccessManager::CustomOperation:
ap@apple.com's avatar
ap@apple.com committed
532
            m_reply = manager->sendCustomRequest(m_request, m_resourceHandle->firstRequest().httpMethod().latin1().data());
533
            break;
534
#endif
535
536
537
538
539
540
541
542
543
544
545
        case QNetworkAccessManager::UnknownOperation: {
            m_reply = 0;
            ResourceHandleClient* client = m_resourceHandle->client();
            if (client) {
                ResourceError error(url.host(), 400 /*bad request*/,
                                    url.toString(),
                                    QCoreApplication::translate("QWebPage", "Bad HTTP request"));
                client->didFail(m_resourceHandle, error);
            }
            return;
        }
546
547
548
549
550
    }

    m_reply->setParent(this);

    connect(m_reply, SIGNAL(finished()),
551
            this, SLOT(finish()), SIGNAL_CONN);
552
553
554
555
556

    // For http(s) we know that the headers are complete upon metaDataChanged() emission, so we
    // can send the response as early as possible
    if (scheme == QLatin1String("http") || scheme == QLatin1String("https"))
        connect(m_reply, SIGNAL(metaDataChanged()),
557
                this, SLOT(sendResponseIfNeeded()), SIGNAL_CONN);
558
559

    connect(m_reply, SIGNAL(readyRead()),
560
561
            this, SLOT(forwardData()), SIGNAL_CONN);

ap@apple.com's avatar
ap@apple.com committed
562
    if (m_resourceHandle->firstRequest().reportUploadProgress()) {
563
564
565
566
        connect(m_reply, SIGNAL(uploadProgress(qint64, qint64)),
                this, SLOT(uploadProgress(qint64, qint64)), SIGNAL_CONN);
    }

567
    // Make this a direct function call once we require 4.6.1+.
568
    connect(this, SIGNAL(processQueuedItems()),
569
            this, SLOT(sendQueuedItems()), SIGNAL_CONN);
570
571
}

572
573
574
575
void QNetworkReplyHandler::resetState()
{
    m_redirected = false;
    m_responseSent = false;
576
    m_responseContainsData = false;
577
578
579
580
581
582
583
584
    m_shouldStart = true;
    m_shouldFinish = false;
    m_shouldSendResponse = false;
    m_shouldForwardData = false;
}

void QNetworkReplyHandler::sendQueuedItems()
{
585
586
587
    if (m_loadMode != LoadResuming)
        return;
    m_loadMode = LoadNormal;
588
589
590
591
592
593
594
595
596
597
598
599
600
601

    if (m_shouldStart)
        start();

    if (m_shouldSendResponse)
        sendResponseIfNeeded();

    if (m_shouldForwardData)
        forwardData();

    if (m_shouldFinish)
        finish(); 
}

602
603
604
}

#include "moc_QNetworkReplyHandler.cpp"