ab240f588b7234a76fc830c544f180939d96226b
[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     start();
62 }
63
64 void QNetworkReplyHandler::abort()
65 {
66     m_resourceHandle = 0;
67     if (m_reply) {
68         disconnect(m_reply, 0, this, 0);
69         m_reply->abort();
70         deleteLater();
71         m_reply = 0;
72     }
73 }
74
75 void QNetworkReplyHandler::finish()
76 {
77     sendResponseIfNeeded();
78
79     if (!m_resourceHandle)
80         return;
81     ResourceHandleClient* client = m_resourceHandle->client();
82     m_reply->deleteLater();
83     if (!client)
84         return;
85     if (m_redirected) {
86         m_redirected = false;
87         m_responseSent = false;
88         start();
89     } else if (m_reply->error() != QNetworkReply::NoError) {
90         QUrl url = m_reply->url();
91         ResourceError error(url.host(), m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),
92                             url.toString(), m_reply->errorString());
93         client->didFail(m_resourceHandle, error);
94     } else {
95         client->didFinishLoading(m_resourceHandle);
96     }
97 }
98
99 void QNetworkReplyHandler::sendResponseIfNeeded()
100 {
101     if (m_responseSent || !m_resourceHandle)
102         return;
103     m_responseSent = true;
104
105     ResourceHandleClient* client = m_resourceHandle->client();
106     if (!client)
107         return;
108
109     WebCore::String contentType = m_reply->header(QNetworkRequest::ContentTypeHeader).toString();
110     WebCore::String encoding = extractCharsetFromMediaType(contentType);
111     WebCore::String mimeType = extractMIMETypeFromMediaType(contentType);
112
113     if (mimeType.isEmpty()) {
114         // let's try to guess from the extension
115         QString extension = m_reply->url().path();
116         int index = extension.lastIndexOf(QLatin1Char('.'));
117         if (index > 0) {
118             extension = extension.mid(index + 1);
119             mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
120         }
121     }
122
123     KURL url(m_reply->url());
124     String contentDisposition = QString::fromAscii(m_reply->rawHeader("Content-Disposition"));
125
126     ResourceResponse response(url, mimeType,
127                               m_reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(),
128                               encoding,
129                               filenameFromHTTPContentDisposition(contentDisposition));
130
131     const bool isLocalFileReply = (m_reply->url().scheme() == QLatin1String("file"));
132     int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
133     if (!isLocalFileReply)
134         response.setHTTPStatusCode(statusCode);
135     else if (m_reply->error() == QNetworkReply::ContentNotFoundError)
136         response.setHTTPStatusCode(404);
137
138
139     /* Fill in the other fields
140      * For local file requests remove the content length and the last-modified
141      * headers as required by fast/dom/xmlhttprequest-get.xhtml
142      */
143     foreach (QByteArray headerName, m_reply->rawHeaderList()) {
144
145         if (isLocalFileReply
146             && (headerName == "Content-Length" || headerName == "Last-Modified"))
147             continue;
148
149         response.setHTTPHeaderField(QString::fromAscii(headerName), QString::fromAscii(m_reply->rawHeader(headerName)));
150     }
151
152     QUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
153     if (redirection.isValid()) {
154         QUrl newUrl = m_reply->url().resolved(redirection);
155         ResourceRequest newRequest = m_resourceHandle->request();
156         newRequest.setURL(newUrl);
157
158         if (((statusCode >= 301 && statusCode <= 303) || statusCode == 307) && m_method == QNetworkAccessManager::PostOperation) {
159             m_method = QNetworkAccessManager::GetOperation;
160             newRequest.setHTTPMethod("GET");
161         }
162
163         client->willSendRequest(m_resourceHandle, newRequest, response);
164         m_redirected = true;
165         m_request = newRequest.toNetworkRequest();
166     } else {
167         client->didReceiveResponse(m_resourceHandle, response);
168     }
169 }
170
171 void QNetworkReplyHandler::forwardData()
172 {
173     sendResponseIfNeeded();
174
175     // don't emit the "Document has moved here" type of HTML
176     if (m_redirected)
177         return;
178
179     if (!m_resourceHandle)
180         return;
181
182     QByteArray data = m_reply->read(m_reply->bytesAvailable());
183
184     ResourceHandleClient* client = m_resourceHandle->client();
185     if (!client)
186         return;
187
188     if (!data.isEmpty())
189         client->didReceiveData(m_resourceHandle, data.constData(), data.length(), data.length() /*FixMe*/);
190 }
191
192 void QNetworkReplyHandler::start()
193 {
194     ResourceHandleInternal* d = m_resourceHandle->getInternal();
195
196     QNetworkAccessManager* manager = d->m_frame->page()->networkAccessManager();
197
198     const QUrl url = m_request.url();
199     const QString scheme = url.scheme();
200     // Post requests on files and data don't really make sense, but for
201     // fast/forms/form-post-urlencoded.html and for fast/forms/button-state-restore.html
202     // we still need to retrieve the file/data, which means we map it to a Get instead.
203     if (m_method == QNetworkAccessManager::PostOperation
204         && (!url.toLocalFile().isEmpty() || url.scheme() == QLatin1String("data")))
205         m_method = QNetworkAccessManager::GetOperation;
206
207     switch (m_method) {
208         case QNetworkAccessManager::GetOperation:
209             m_reply = manager->get(m_request);
210             break;
211         case QNetworkAccessManager::PostOperation: {
212             Vector<char> bytes;
213             if (d->m_request.httpBody())
214                 d->m_request.httpBody()->flatten(bytes);
215             m_reply = manager->post(m_request, QByteArray(bytes.data(), bytes.size()));
216             break;
217         }
218         case QNetworkAccessManager::HeadOperation:
219             m_reply = manager->head(m_request);
220             break;
221         case QNetworkAccessManager::PutOperation: {
222             // ### data?
223             Vector<char> bytes;
224             if (d->m_request.httpBody())
225                 d->m_request.httpBody()->flatten(bytes);
226             m_reply = manager->put(m_request, QByteArray(bytes.data(), bytes.size()));
227             break;
228         }
229         case QNetworkAccessManager::UnknownOperation:
230             break; // eh?
231     }
232
233     m_reply->setParent(this);
234
235     connect(m_reply, SIGNAL(finished()),
236             this, SLOT(finish()));
237
238     // For http(s) we know that the headers are complete upon metaDataChanged() emission, so we
239     // can send the response as early as possible
240     if (scheme == QLatin1String("http") || scheme == QLatin1String("https"))
241         connect(m_reply, SIGNAL(metaDataChanged()),
242                 this, SLOT(sendResponseIfNeeded()));
243
244     connect(m_reply, SIGNAL(readyRead()),
245             this, SLOT(forwardData()));
246 }
247
248 }
249
250 #include "moc_QNetworkReplyHandler.cpp"
251
252 #endif