8990d4d68a32e55a033e24db04d63fc3901fe13c
[WebKit-https.git] / WebCore / platform / network / qt / QNetworkReplyHandler.cpp
1 /*
2     Copyright (C) 2007 Trolltech ASA
3     Copyright (C) 2007 Staikos Computing Services Inc.  <info@staikos.net>
4
5     This library is free software; you can redistribute it and/or
6     modify it under the terms of the GNU Library General Public
7     License as published by the Free Software Foundation; either
8     version 2 of the License, or (at your option) any later version.
9
10     This library is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13     Library General Public License for more details.
14
15     You should have received a copy of the GNU Library General Public License
16     along with this library; see the file COPYING.LIB.  If not, write to
17     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18     Boston, MA 02110-1301, USA.
19 */
20 #include "config.h"
21 #include "QNetworkReplyHandler.h"
22
23 #if QT_VERSION >= 0x040400
24
25 #include "HTTPParsers.h"
26 #include "MIMETypeRegistry.h"
27 #include "ResourceHandle.h"
28 #include "ResourceHandleClient.h"
29 #include "ResourceHandleInternal.h"
30 #include "ResourceResponse.h"
31 #include "ResourceRequest.h"
32 #include <QNetworkReply>
33 #include <QNetworkCookie>
34 #include <qwebframe.h>
35 #include <qwebpage.h>
36
37 namespace WebCore {
38
39 QNetworkReplyHandler::QNetworkReplyHandler(ResourceHandle *handle)
40     : QObject(0)
41       , m_resourceHandle(handle)
42       , m_reply(0)
43       , m_redirected(false)
44       , m_responseSent(false)
45 {
46     const ResourceRequest &r = m_resourceHandle->request();
47
48     if (r.httpMethod() == "GET")
49         m_method = QNetworkAccessManager::GetOperation;
50     else if (r.httpMethod() == "HEAD")
51         m_method = QNetworkAccessManager::HeadOperation;
52     else if (r.httpMethod() == "POST")
53         m_method = QNetworkAccessManager::PostOperation;
54     else if (r.httpMethod() == "PUT")
55         m_method = QNetworkAccessManager::PutOperation;
56     else
57         m_method = QNetworkAccessManager::UnknownOperation;
58
59     m_request = r.toNetworkRequest();
60
61     // ### temporary workaround for gzip decoding bug in the new QHttp
62     m_request.setRawHeader("Accept-Encoding", "identity");
63
64     start();
65 }
66
67 void QNetworkReplyHandler::abort()
68 {
69     if (m_reply) {
70         disconnect(m_reply, 0, this, 0);
71         m_reply->abort();
72         deleteLater();
73     }
74 }
75
76 void QNetworkReplyHandler::finish()
77 {
78     sendResponseIfNeeded();
79
80     ResourceHandleClient* client = m_resourceHandle->client();
81     m_reply->deleteLater();
82     if (!client)
83         return;
84     if (m_redirected) {
85         m_redirected = false;
86         start();
87     } else if (m_reply->error() != QNetworkReply::NoError) {
88         QUrl url = m_reply->url();
89         ResourceError error(url.host(), m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),
90                             url.toString(), m_reply->errorString());
91         client->didFail(m_resourceHandle, error);
92     } else {
93         client->didFinishLoading(m_resourceHandle);
94     }
95 }
96
97 void QNetworkReplyHandler::sendResponseIfNeeded()
98 {
99     if (m_responseSent)
100         return;
101     m_responseSent = true;
102
103     ResourceHandleClient* client = m_resourceHandle->client();
104     if (!client)
105         return;
106
107     WebCore::String contentType = m_reply->header(QNetworkRequest::ContentTypeHeader).toString();
108     WebCore::String encoding = extractCharsetFromMediaType(contentType);
109     WebCore::String mimeType = extractMIMETypeFromMediaType(contentType);
110
111     if (mimeType.isEmpty()) {
112         // let's try to guess from the extension
113         QString extension = m_reply->url().path();
114         int index = extension.lastIndexOf(QLatin1Char('.'));
115         if (index > 0) {
116             extension = extension.mid(index + 1);
117             mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
118         }
119     }
120
121     KURL url(m_reply->url());
122     String contentDisposition = QString::fromAscii(m_reply->rawHeader("Content-Disposition"));
123
124     ResourceResponse response(url, mimeType,
125                               m_reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(),
126                               encoding,
127                               filenameFromHTTPContentDisposition(contentDisposition));
128
129     int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
130     if (m_reply->url().scheme() != QLatin1String("file"))
131         response.setHTTPStatusCode(statusCode);
132     else if (m_reply->error() == QNetworkReply::ContentNotFoundError)
133         response.setHTTPStatusCode(404);
134
135
136     /* Fill in the other fields */
137     foreach (QByteArray headerName, m_reply->rawHeaderList())
138         response.setHTTPHeaderField(QString::fromAscii(headerName), QString::fromAscii(m_reply->rawHeader(headerName)));
139
140     QUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
141     if (redirection.isValid()) {
142         QUrl newUrl = m_reply->url().resolved(redirection);
143         ResourceRequest newRequest = m_resourceHandle->request();
144         newRequest.setURL(newUrl);
145         client->willSendRequest(m_resourceHandle, newRequest, response);
146
147         if (statusCode >= 301 && statusCode <= 303 && m_method == QNetworkAccessManager::PostOperation)
148             m_method = QNetworkAccessManager::GetOperation;
149         m_redirected = true;
150         m_responseSent = false;
151
152         m_request.setUrl(newUrl);
153     } else {
154         client->didReceiveResponse(m_resourceHandle, response);
155     }
156 }
157
158 void QNetworkReplyHandler::forwardData()
159 {
160     sendResponseIfNeeded();
161
162     // don't emit the "Document has moved here" type of HTML
163     if (m_redirected)
164         return;
165
166     QByteArray data = m_reply->read(m_reply->bytesAvailable());
167
168     ResourceHandleClient* client = m_resourceHandle->client();
169     if (!client)
170         return;
171
172     if (!data.isEmpty())
173         client->didReceiveData(m_resourceHandle, data.constData(), data.length(), data.length() /*FixMe*/);
174 }
175
176 void QNetworkReplyHandler::start()
177 {
178     ResourceHandleInternal* d = m_resourceHandle->getInternal();
179
180     QNetworkAccessManager* manager = d->m_frame->page()->networkAccessManager();
181
182     switch (m_method) {
183         case QNetworkAccessManager::GetOperation:
184             m_reply = manager->get(m_request);
185             break;
186         case QNetworkAccessManager::PostOperation: {
187             Vector<char> bytes;
188             d->m_request.httpBody()->flatten(bytes);
189             m_reply = manager->post(m_request, QByteArray(bytes.data(), bytes.size()));
190             break;
191         }
192         case QNetworkAccessManager::HeadOperation:
193             m_reply = manager->head(m_request);
194             break;
195         case QNetworkAccessManager::PutOperation: {
196             // ### data?
197             Vector<char> bytes;
198             d->m_request.httpBody()->flatten(bytes);
199             m_reply = manager->put(m_request, QByteArray(bytes.data(), bytes.size()));
200             break;
201         }
202         case QNetworkAccessManager::UnknownOperation:
203             break; // eh?
204     }
205
206     m_reply->setParent(this);
207
208     connect(m_reply, SIGNAL(finished()),
209             this, SLOT(finish()));
210
211     // For http(s) we know that the headers are complete upon metaDataChanged() emission, so we
212     // can send the response as early as possible
213     QString scheme = m_request.url().scheme();
214     if (scheme == QLatin1String("http") || scheme == QLatin1String("https"))
215         connect(m_reply, SIGNAL(metaDataChanged()),
216                 this, SLOT(sendResponseIfNeeded()));
217
218     connect(m_reply, SIGNAL(readyRead()),
219             this, SLOT(forwardData()));
220 }
221
222 }
223
224 #include "moc_QNetworkReplyHandler.cpp"
225
226 #endif