Fix crashes in the new networking code.
[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     m_resourceHandle = 0;
70     if (m_reply) {
71         disconnect(m_reply, 0, this, 0);
72         m_reply->abort();
73         deleteLater();
74     }
75 }
76
77 void QNetworkReplyHandler::finish()
78 {
79     sendResponseIfNeeded();
80
81     if (!m_resourceHandle)
82         return;
83     ResourceHandleClient* client = m_resourceHandle->client();
84     m_reply->deleteLater();
85     if (!client)
86         return;
87     if (m_redirected) {
88         m_redirected = false;
89         start();
90     } else if (m_reply->error() != QNetworkReply::NoError) {
91         QUrl url = m_reply->url();
92         ResourceError error(url.host(), m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),
93                             url.toString(), m_reply->errorString());
94         client->didFail(m_resourceHandle, error);
95     } else {
96         client->didFinishLoading(m_resourceHandle);
97     }
98 }
99
100 void QNetworkReplyHandler::sendResponseIfNeeded()
101 {
102     if (m_responseSent || !m_resourceHandle)
103         return;
104     m_responseSent = true;
105
106     ResourceHandleClient* client = m_resourceHandle->client();
107     if (!client)
108         return;
109
110     WebCore::String contentType = m_reply->header(QNetworkRequest::ContentTypeHeader).toString();
111     WebCore::String encoding = extractCharsetFromMediaType(contentType);
112     WebCore::String mimeType = extractMIMETypeFromMediaType(contentType);
113
114     if (mimeType.isEmpty()) {
115         // let's try to guess from the extension
116         QString extension = m_reply->url().path();
117         int index = extension.lastIndexOf(QLatin1Char('.'));
118         if (index > 0) {
119             extension = extension.mid(index + 1);
120             mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
121         }
122     }
123
124     KURL url(m_reply->url());
125     String contentDisposition = QString::fromAscii(m_reply->rawHeader("Content-Disposition"));
126
127     ResourceResponse response(url, mimeType,
128                               m_reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(),
129                               encoding,
130                               filenameFromHTTPContentDisposition(contentDisposition));
131
132     int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
133     if (m_reply->url().scheme() != QLatin1String("file"))
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     foreach (QByteArray headerName, m_reply->rawHeaderList())
141         response.setHTTPHeaderField(QString::fromAscii(headerName), QString::fromAscii(m_reply->rawHeader(headerName)));
142
143     QUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
144     if (redirection.isValid()) {
145         QUrl newUrl = m_reply->url().resolved(redirection);
146         ResourceRequest newRequest = m_resourceHandle->request();
147         newRequest.setURL(newUrl);
148         client->willSendRequest(m_resourceHandle, newRequest, response);
149
150         if (statusCode >= 301 && statusCode <= 303 && m_method == QNetworkAccessManager::PostOperation)
151             m_method = QNetworkAccessManager::GetOperation;
152         m_redirected = true;
153         m_responseSent = false;
154
155         m_request.setUrl(newUrl);
156     } else {
157         client->didReceiveResponse(m_resourceHandle, response);
158     }
159 }
160
161 void QNetworkReplyHandler::forwardData()
162 {
163     sendResponseIfNeeded();
164
165     // don't emit the "Document has moved here" type of HTML
166     if (m_redirected)
167         return;
168
169     if (!m_resourceHandle)
170         return;
171
172     QByteArray data = m_reply->read(m_reply->bytesAvailable());
173
174     ResourceHandleClient* client = m_resourceHandle->client();
175     if (!client)
176         return;
177
178     if (!data.isEmpty())
179         client->didReceiveData(m_resourceHandle, data.constData(), data.length(), data.length() /*FixMe*/);
180 }
181
182 void QNetworkReplyHandler::start()
183 {
184     ResourceHandleInternal* d = m_resourceHandle->getInternal();
185
186     QNetworkAccessManager* manager = d->m_frame->page()->networkAccessManager();
187
188     switch (m_method) {
189         case QNetworkAccessManager::GetOperation:
190             m_reply = manager->get(m_request);
191             break;
192         case QNetworkAccessManager::PostOperation: {
193             Vector<char> bytes;
194             d->m_request.httpBody()->flatten(bytes);
195             m_reply = manager->post(m_request, QByteArray(bytes.data(), bytes.size()));
196             break;
197         }
198         case QNetworkAccessManager::HeadOperation:
199             m_reply = manager->head(m_request);
200             break;
201         case QNetworkAccessManager::PutOperation: {
202             // ### data?
203             Vector<char> bytes;
204             d->m_request.httpBody()->flatten(bytes);
205             m_reply = manager->put(m_request, QByteArray(bytes.data(), bytes.size()));
206             break;
207         }
208         case QNetworkAccessManager::UnknownOperation:
209             break; // eh?
210     }
211
212     m_reply->setParent(this);
213
214     connect(m_reply, SIGNAL(finished()),
215             this, SLOT(finish()));
216
217     // For http(s) we know that the headers are complete upon metaDataChanged() emission, so we
218     // can send the response as early as possible
219     QString scheme = m_request.url().scheme();
220     if (scheme == QLatin1String("http") || scheme == QLatin1String("https"))
221         connect(m_reply, SIGNAL(metaDataChanged()),
222                 this, SLOT(sendResponseIfNeeded()));
223
224     connect(m_reply, SIGNAL(readyRead()),
225             this, SLOT(forwardData()));
226 }
227
228 }
229
230 #include "moc_QNetworkReplyHandler.cpp"
231
232 #endif