9662efd1a8f92b5775283ab0e8aaab7e27f03e6b
[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         start();
88     } else if (m_reply->error() != QNetworkReply::NoError) {
89         QUrl url = m_reply->url();
90         ResourceError error(url.host(), m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(),
91                             url.toString(), m_reply->errorString());
92         client->didFail(m_resourceHandle, error);
93     } else {
94         client->didFinishLoading(m_resourceHandle);
95     }
96 }
97
98 void QNetworkReplyHandler::sendResponseIfNeeded()
99 {
100     if (m_responseSent || !m_resourceHandle)
101         return;
102     m_responseSent = true;
103
104     ResourceHandleClient* client = m_resourceHandle->client();
105     if (!client)
106         return;
107
108     WebCore::String contentType = m_reply->header(QNetworkRequest::ContentTypeHeader).toString();
109     WebCore::String encoding = extractCharsetFromMediaType(contentType);
110     WebCore::String mimeType = extractMIMETypeFromMediaType(contentType);
111
112     if (mimeType.isEmpty()) {
113         // let's try to guess from the extension
114         QString extension = m_reply->url().path();
115         int index = extension.lastIndexOf(QLatin1Char('.'));
116         if (index > 0) {
117             extension = extension.mid(index + 1);
118             mimeType = MIMETypeRegistry::getMIMETypeForExtension(extension);
119         }
120     }
121
122     KURL url(m_reply->url());
123     String contentDisposition = QString::fromAscii(m_reply->rawHeader("Content-Disposition"));
124
125     ResourceResponse response(url, mimeType,
126                               m_reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(),
127                               encoding,
128                               filenameFromHTTPContentDisposition(contentDisposition));
129
130     int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
131     if (m_reply->url().scheme() != QLatin1String("file"))
132         response.setHTTPStatusCode(statusCode);
133     else if (m_reply->error() == QNetworkReply::ContentNotFoundError)
134         response.setHTTPStatusCode(404);
135
136
137     /* Fill in the other fields */
138     foreach (QByteArray headerName, m_reply->rawHeaderList())
139         response.setHTTPHeaderField(QString::fromAscii(headerName), QString::fromAscii(m_reply->rawHeader(headerName)));
140
141     QUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
142     if (redirection.isValid()) {
143         QUrl newUrl = m_reply->url().resolved(redirection);
144         ResourceRequest newRequest = m_resourceHandle->request();
145         newRequest.setURL(newUrl);
146         client->willSendRequest(m_resourceHandle, newRequest, response);
147
148         if (statusCode >= 301 && statusCode <= 303 && m_method == QNetworkAccessManager::PostOperation)
149             m_method = QNetworkAccessManager::GetOperation;
150         m_redirected = true;
151         m_responseSent = false;
152
153         m_request.setUrl(newUrl);
154     } else {
155         client->didReceiveResponse(m_resourceHandle, response);
156     }
157 }
158
159 void QNetworkReplyHandler::forwardData()
160 {
161     sendResponseIfNeeded();
162
163     // don't emit the "Document has moved here" type of HTML
164     if (m_redirected)
165         return;
166
167     if (!m_resourceHandle)
168         return;
169
170     QByteArray data = m_reply->read(m_reply->bytesAvailable());
171
172     ResourceHandleClient* client = m_resourceHandle->client();
173     if (!client)
174         return;
175
176     if (!data.isEmpty())
177         client->didReceiveData(m_resourceHandle, data.constData(), data.length(), data.length() /*FixMe*/);
178 }
179
180 void QNetworkReplyHandler::start()
181 {
182     ResourceHandleInternal* d = m_resourceHandle->getInternal();
183
184     QNetworkAccessManager* manager = d->m_frame->page()->networkAccessManager();
185
186     switch (m_method) {
187         case QNetworkAccessManager::GetOperation:
188             m_reply = manager->get(m_request);
189             break;
190         case QNetworkAccessManager::PostOperation: {
191             Vector<char> bytes;
192             if (d->m_request.httpBody())
193                 d->m_request.httpBody()->flatten(bytes);
194             m_reply = manager->post(m_request, QByteArray(bytes.data(), bytes.size()));
195             break;
196         }
197         case QNetworkAccessManager::HeadOperation:
198             m_reply = manager->head(m_request);
199             break;
200         case QNetworkAccessManager::PutOperation: {
201             // ### data?
202             Vector<char> bytes;
203             if (d->m_request.httpBody())
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