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