2010-10-13 Sergio Villar Senin <svillar@igalia.com>
[WebKit-https.git] / WebCore / platform / network / soup / ResourceHandleSoup.cpp
1 /*
2  * Copyright (C) 2008 Alp Toker <alp@atoker.com>
3  * Copyright (C) 2008 Xan Lopez <xan@gnome.org>
4  * Copyright (C) 2008, 2010 Collabora Ltd.
5  * Copyright (C) 2009 Holger Hans Peter Freyther
6  * Copyright (C) 2009 Gustavo Noronha Silva <gns@gnome.org>
7  * Copyright (C) 2009 Christian Dywan <christian@imendio.com>
8  * Copyright (C) 2009 Igalia S.L.
9  * Copyright (C) 2009 John Kjellberg <john.kjellberg@power.alstom.com>
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public License
22  * along with this library; see the file COPYING.LIB.  If not, write to
23  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  */
26
27 #include "config.h"
28 #include "ResourceHandle.h"
29
30 #include "Base64.h"
31 #include "CString.h"
32 #include "ChromeClient.h"
33 #include "CookieJarSoup.h"
34 #include "CachedResourceLoader.h"
35 #include "FileSystem.h"
36 #include "Frame.h"
37 #include "GOwnPtrSoup.h"
38 #include "HTTPParsers.h"
39 #include "Logging.h"
40 #include "MIMETypeRegistry.h"
41 #include "NotImplemented.h"
42 #include "Page.h"
43 #include "ResourceError.h"
44 #include "ResourceHandleClient.h"
45 #include "ResourceHandleInternal.h"
46 #include "ResourceResponse.h"
47 #include "SharedBuffer.h"
48 #include "soup-request-http.h"
49 #include "TextEncoding.h"
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <gio/gio.h>
53 #include <glib.h>
54 #include <libsoup/soup.h>
55 #include <sys/stat.h>
56 #include <sys/types.h>
57 #include <unistd.h>
58
59 namespace WebCore {
60
61 #define READ_BUFFER_SIZE 8192
62
63 class WebCoreSynchronousLoader : public ResourceHandleClient, public Noncopyable {
64 public:
65     WebCoreSynchronousLoader(ResourceError&, ResourceResponse &, Vector<char>&);
66     ~WebCoreSynchronousLoader();
67
68     virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
69     virtual void didReceiveData(ResourceHandle*, const char*, int, int lengthReceived);
70     virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
71     virtual void didFail(ResourceHandle*, const ResourceError&);
72
73     void run();
74
75 private:
76     ResourceError& m_error;
77     ResourceResponse& m_response;
78     Vector<char>& m_data;
79     bool m_finished;
80     GMainLoop* m_mainLoop;
81 };
82
83 WebCoreSynchronousLoader::WebCoreSynchronousLoader(ResourceError& error, ResourceResponse& response, Vector<char>& data)
84     : m_error(error)
85     , m_response(response)
86     , m_data(data)
87     , m_finished(false)
88 {
89     m_mainLoop = g_main_loop_new(0, false);
90 }
91
92 WebCoreSynchronousLoader::~WebCoreSynchronousLoader()
93 {
94     g_main_loop_unref(m_mainLoop);
95 }
96
97 void WebCoreSynchronousLoader::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
98 {
99     m_response = response;
100 }
101
102 void WebCoreSynchronousLoader::didReceiveData(ResourceHandle*, const char* data, int length, int)
103 {
104     m_data.append(data, length);
105 }
106
107 void WebCoreSynchronousLoader::didFinishLoading(ResourceHandle*, double)
108 {
109     g_main_loop_quit(m_mainLoop);
110     m_finished = true;
111 }
112
113 void WebCoreSynchronousLoader::didFail(ResourceHandle* handle, const ResourceError& error)
114 {
115     m_error = error;
116     didFinishLoading(handle, 0);
117 }
118
119 void WebCoreSynchronousLoader::run()
120 {
121     if (!m_finished)
122         g_main_loop_run(m_mainLoop);
123 }
124
125 static void cleanupSoupRequestOperation(ResourceHandle*, bool isDestroying);
126 static void sendRequestCallback(GObject*, GAsyncResult*, gpointer);
127 static void readCallback(GObject*, GAsyncResult*, gpointer);
128 static void closeCallback(GObject*, GAsyncResult*, gpointer);
129 static bool startGio(ResourceHandle*, KURL);
130
131 ResourceHandleInternal::~ResourceHandleInternal()
132 {
133     if (m_soupRequest)
134         g_object_set_data(G_OBJECT(m_soupRequest.get()), "webkit-resource", 0);
135
136     if (m_idleHandler) {
137         g_source_remove(m_idleHandler);
138         m_idleHandler = 0;
139     }
140 }
141
142 ResourceHandle::~ResourceHandle()
143 {
144     cleanupSoupRequestOperation(this, true);
145 }
146
147 void ResourceHandle::prepareForURL(const KURL &url)
148 {
149 #ifdef HAVE_LIBSOUP_2_29_90
150     GOwnPtr<SoupURI> soupURI(soup_uri_new(url.prettyURL().utf8().data()));
151     if (!soupURI)
152         return;
153     soup_session_prepare_for_uri(ResourceHandle::defaultSession(), soupURI.get());
154 #endif
155 }
156
157 // All other kinds of redirections, except for the *304* status code
158 // (SOUP_STATUS_NOT_MODIFIED) which needs to be fed into WebCore, will be
159 // handled by soup directly.
160 static gboolean statusWillBeHandledBySoup(guint statusCode)
161 {
162     if (SOUP_STATUS_IS_TRANSPORT_ERROR(statusCode)
163         || (SOUP_STATUS_IS_REDIRECTION(statusCode) && (statusCode != SOUP_STATUS_NOT_MODIFIED))
164         || (statusCode == SOUP_STATUS_UNAUTHORIZED))
165         return true;
166
167     return false;
168 }
169
170 static void fillResponseFromMessage(SoupMessage* msg, ResourceResponse* response)
171 {
172     response->updateFromSoupMessage(msg);
173 }
174
175 // Called each time the message is going to be sent again except the first time.
176 // It's used mostly to let webkit know about redirects.
177 static void restartedCallback(SoupMessage* msg, gpointer data)
178 {
179     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
180     if (!handle)
181         return;
182     ResourceHandleInternal* d = handle->getInternal();
183     if (d->m_cancelled)
184         return;
185
186     GOwnPtr<char> uri(soup_uri_to_string(soup_message_get_uri(msg), false));
187     String location = String::fromUTF8(uri.get());
188     KURL newURL = KURL(handle->firstRequest().url(), location);
189
190     ResourceRequest request = handle->firstRequest();
191     ResourceResponse response;
192     request.setURL(newURL);
193     request.setHTTPMethod(msg->method);
194     fillResponseFromMessage(msg, &response);
195
196     // Should not set Referer after a redirect from a secure resource to non-secure one.
197     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https")) {
198         request.clearHTTPReferrer();
199         soup_message_headers_remove(msg->request_headers, "Referer");
200     }
201
202     if (d->client())
203         d->client()->willSendRequest(handle, request, response);
204
205     if (d->m_cancelled)
206         return;
207
208 #ifdef HAVE_LIBSOUP_2_29_90
209     // Update the first party in case the base URL changed with the redirect
210     String firstPartyString = request.firstPartyForCookies().string();
211     if (!firstPartyString.isEmpty()) {
212         GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
213         soup_message_set_first_party(d->m_soupMessage.get(), firstParty.get());
214     }
215 #endif
216 }
217
218 static void gotHeadersCallback(SoupMessage* msg, gpointer data)
219 {
220     // For 401, we will accumulate the resource body, and only use it
221     // in case authentication with the soup feature doesn't happen
222     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
223         soup_message_body_set_accumulate(msg->response_body, TRUE);
224         return;
225     }
226
227     // For all the other responses, we handle each chunk ourselves,
228     // and we don't need msg->response_body to contain all of the data
229     // we got, when we finish downloading.
230     soup_message_body_set_accumulate(msg->response_body, FALSE);
231
232     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
233
234     // The content-sniffed callback will handle the response if WebCore
235     // require us to sniff.
236     if (!handle || statusWillBeHandledBySoup(msg->status_code) || handle->shouldContentSniff())
237         return;
238
239     ResourceHandleInternal* d = handle->getInternal();
240     if (d->m_cancelled)
241         return;
242     ResourceHandleClient* client = handle->client();
243     if (!client)
244         return;
245
246     fillResponseFromMessage(msg, &d->m_response);
247     client->didReceiveResponse(handle.get(), d->m_response);
248 }
249
250 // This callback will not be called if the content sniffer is disabled in startHttp.
251 static void contentSniffedCallback(SoupMessage* msg, const char* sniffedType, GHashTable *params, gpointer data)
252 {
253     if (sniffedType) {
254         const char* officialType = soup_message_headers_get_one(msg->response_headers, "Content-Type");
255
256         if (!officialType || strcmp(officialType, sniffedType))
257             soup_message_headers_set_content_type(msg->response_headers, sniffedType, params);
258     }
259
260     if (statusWillBeHandledBySoup(msg->status_code))
261         return;
262
263     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
264     if (!handle)
265         return;
266     ResourceHandleInternal* d = handle->getInternal();
267     if (d->m_cancelled)
268         return;
269     ResourceHandleClient* client = handle->client();
270     if (!client)
271         return;
272
273     fillResponseFromMessage(msg, &d->m_response);
274     client->didReceiveResponse(handle.get(), d->m_response);
275 }
276
277 static void gotChunkCallback(SoupMessage* msg, SoupBuffer* chunk, gpointer data)
278 {
279     if (statusWillBeHandledBySoup(msg->status_code))
280         return;
281
282     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
283     if (!handle)
284         return;
285     ResourceHandleInternal* d = handle->getInternal();
286     if (d->m_cancelled)
287         return;
288     ResourceHandleClient* client = handle->client();
289     if (!client)
290         return;
291
292     client->didReceiveData(handle.get(), chunk->data, chunk->length, false);
293
294 }
295
296 static gboolean parseDataUrl(gpointer callbackData)
297 {
298     ResourceHandle* handle = static_cast<ResourceHandle*>(callbackData);
299     ResourceHandleClient* client = handle->client();
300     ResourceHandleInternal* d = handle->getInternal();
301     if (d->m_cancelled)
302         return false;
303
304     d->m_idleHandler = 0;
305
306     ASSERT(client);
307     if (!client)
308         return false;
309
310     String url = handle->firstRequest().url().string();
311     ASSERT(url.startsWith("data:", false));
312
313     int index = url.find(',');
314     if (index == -1) {
315         client->cannotShowURL(handle);
316         return false;
317     }
318
319     String mediaType = url.substring(5, index - 5);
320
321     bool isBase64 = mediaType.endsWith(";base64", false);
322     if (isBase64)
323         mediaType = mediaType.left(mediaType.length() - 7);
324
325     if (mediaType.isEmpty())
326         mediaType = "text/plain;charset=US-ASCII";
327
328     String mimeType = extractMIMETypeFromMediaType(mediaType);
329     String charset = extractCharsetFromMediaType(mediaType);
330
331     ResourceResponse response;
332     response.setURL(handle->firstRequest().url());
333     response.setMimeType(mimeType);
334
335     // For non base64 encoded data we have to convert to UTF-16 early
336     // due to limitations in KURL
337     response.setTextEncodingName(isBase64 ? charset : "UTF-16");
338     client->didReceiveResponse(handle, response);
339
340     // The load may be cancelled, and the client may be destroyed
341     // by any of the client reporting calls, so we check, and bail
342     // out in either of those cases.
343     if (d->m_cancelled || !handle->client())
344         return false;
345
346     SoupSession* session = handle->defaultSession();
347     GOwnPtr<GError> error;
348     d->m_soupRequest = adoptPlatformRef(webkit_soup_requester_request(d->m_requester.get(), handle->firstRequest().url().string().utf8().data(), session, &error.outPtr()));
349     if (error) {
350         d->m_soupRequest = 0;
351         return false;
352     }
353
354     d->m_inputStream = adoptPlatformRef(webkit_soup_request_send(d->m_soupRequest.get(), 0, &error.outPtr()));
355     if (error) {
356         d->m_inputStream = 0;
357         return false;
358     }
359
360     d->m_buffer = static_cast<char*>(g_slice_alloc0(READ_BUFFER_SIZE));
361     d->m_total = 0;
362
363     g_object_set_data(G_OBJECT(d->m_inputStream.get()), "webkit-resource", handle);
364     // balanced by a deref() in cleanupSoupRequestOperation, which should always run
365     handle->ref();
366
367     d->m_cancellable = adoptPlatformRef(g_cancellable_new());
368     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE, G_PRIORITY_DEFAULT,
369                               d->m_cancellable.get(), readCallback, GINT_TO_POINTER(!isBase64));
370
371     return false;
372 }
373
374 static bool startData(ResourceHandle* handle, String urlString)
375 {
376     ASSERT(handle);
377
378     ResourceHandleInternal* d = handle->getInternal();
379
380     // If parseDataUrl is called synchronously the job is not yet effectively started
381     // and webkit won't never know that the data has been parsed even didFinishLoading is called.
382     d->m_idleHandler = g_timeout_add(0, parseDataUrl, handle);
383     return true;
384 }
385
386 static SoupSession* createSoupSession()
387 {
388     return soup_session_async_new();
389 }
390
391 // Values taken from http://stevesouders.com/ua/index.php following
392 // the rule "Do What Every Other Modern Browser Is Doing". They seem
393 // to significantly improve page loading time compared to soup's
394 // default values.
395 #define MAX_CONNECTIONS          60
396 #define MAX_CONNECTIONS_PER_HOST 6
397
398 static void ensureSessionIsInitialized(SoupSession* session)
399 {
400     if (g_object_get_data(G_OBJECT(session), "webkit-init"))
401         return;
402
403     SoupCookieJar* jar = reinterpret_cast<SoupCookieJar*>(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
404     if (!jar)
405         soup_session_add_feature(session, SOUP_SESSION_FEATURE(defaultCookieJar()));
406     else
407         setDefaultCookieJar(jar);
408
409     if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
410         SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
411         soup_logger_attach(logger, session);
412         g_object_unref(logger);
413     }
414
415     g_object_set(session,
416                  SOUP_SESSION_MAX_CONNS, MAX_CONNECTIONS,
417                  SOUP_SESSION_MAX_CONNS_PER_HOST, MAX_CONNECTIONS_PER_HOST,
418                  NULL);
419
420     g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
421 }
422
423 static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroying = false)
424 {
425     ResourceHandleInternal* d = handle->getInternal();
426
427     if (d->m_soupRequest) {
428         g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", 0);
429         d->m_soupRequest.clear();
430     }
431
432     if (d->m_inputStream) {
433         g_object_set_data(G_OBJECT(d->m_inputStream.get()), "webkit-resource", 0);
434         d->m_inputStream.clear();
435     }
436
437     d->m_cancellable.clear();
438
439     if (d->m_soupMessage) {
440         g_signal_handlers_disconnect_matched(d->m_soupMessage.get(), G_SIGNAL_MATCH_DATA,
441                                              0, 0, 0, 0, handle);
442         d->m_soupMessage.clear();
443     }
444
445     if (d->m_buffer) {
446         g_slice_free1(READ_BUFFER_SIZE, d->m_buffer);
447         d->m_buffer = 0;
448     }
449
450     if (!isDestroying)
451         handle->deref();
452 }
453
454 static void sendRequestCallback(GObject* source, GAsyncResult* res, gpointer userData)
455 {
456     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
457     if (!handle)
458         return;
459
460     ResourceHandleInternal* d = handle->getInternal();
461     ResourceHandleClient* client = handle->client();
462
463     if (d->m_gotChunkHandler) {
464         // No need to call gotChunkHandler anymore. Received data will
465         // be reported by readCallback
466         if (g_signal_handler_is_connected(d->m_soupMessage.get(), d->m_gotChunkHandler))
467             g_signal_handler_disconnect(d->m_soupMessage.get(), d->m_gotChunkHandler);
468     }
469
470     if (d->m_cancelled || !client) {
471         cleanupSoupRequestOperation(handle.get());
472         return;
473     }
474
475     GOwnPtr<GError> error;
476     GInputStream* in = webkit_soup_request_send_finish(d->m_soupRequest.get(), res, &error.outPtr());
477
478     if (error) {
479         SoupMessage* soupMsg = d->m_soupMessage.get();
480         gboolean isTransportError = d->m_soupMessage && SOUP_STATUS_IS_TRANSPORT_ERROR(soupMsg->status_code);
481
482         if (isTransportError || (error->domain == G_IO_ERROR)) {
483             SoupURI* uri = webkit_soup_request_get_uri(d->m_soupRequest.get());
484             GOwnPtr<char> uriStr(soup_uri_to_string(uri, false));
485             gint errorCode = isTransportError ? soupMsg->status_code : error->code;
486             const gchar* errorMsg = isTransportError ? soupMsg->reason_phrase : error->message;
487             const gchar* quarkStr = isTransportError ? g_quark_to_string(SOUP_HTTP_ERROR) : g_quark_to_string(G_IO_ERROR);
488             ResourceError resourceError(quarkStr, errorCode, uriStr.get(), String::fromUTF8(errorMsg));
489
490             cleanupSoupRequestOperation(handle.get());
491             client->didFail(handle.get(), resourceError);
492             return;
493         }
494
495         if (d->m_soupMessage && soupMessage->status_code == SOUP_STATUS_UNAUTHORIZED) {
496             fillResponseFromMessage(soupMsg, &d->m_response);
497             client->didReceiveResponse(handle.get(), d->m_response);
498
499             // WebCore might have cancelled the job in the while
500             if (!d->m_cancelled && soupMsg->response_body->data)
501                 client->didReceiveData(handle.get(), soupMsg->response_body->data, soupMsg->response_body->length, true);
502         }
503
504         // didReceiveData above might have cancelled it
505         if (d->m_cancelled || !client) {
506             cleanupSoupRequestOperation(handle.get());
507             return;
508         }
509
510         client->didFinishLoading(handle.get(), 0);
511         return;
512     }
513
514     if (d->m_cancelled) {
515         cleanupSoupRequestOperation(handle.get());
516         return;
517     }
518
519     d->m_inputStream = adoptPlatformRef(in);
520     d->m_buffer = static_cast<char*>(g_slice_alloc0(READ_BUFFER_SIZE));
521     d->m_total = 0;
522
523     // readCallback needs it
524     g_object_set_data(G_OBJECT(d->m_inputStream.get()), "webkit-resource", handle.get());
525
526     // We need to check if it's a file: URL and if it is a regular
527     // file as it could be a directory. In that case Soup properly
528     // returns a stream whose content is a HTML with a list of files
529     // in the directory
530     if (equalIgnoringCase(handle->firstRequest().url().protocol(), "file")
531         && G_IS_FILE_INPUT_STREAM(in)) {
532         ResourceResponse response;
533
534         response.setURL(handle->firstRequest().url());
535         response.setMimeType(webkit_soup_request_get_content_type(d->m_soupRequest.get()));
536         response.setExpectedContentLength(webkit_soup_request_get_content_length(d->m_soupRequest.get()));
537         client->didReceiveResponse(handle.get(), response);
538
539         if (d->m_cancelled) {
540             cleanupSoupRequestOperation(handle.get());
541             return;
542         }
543     }
544
545     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
546                               G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, 0);
547 }
548
549 static bool startHttp(ResourceHandle* handle)
550 {
551     ASSERT(handle);
552
553     SoupSession* session = handle->defaultSession();
554     ensureSessionIsInitialized(session);
555
556     ResourceHandleInternal* d = handle->getInternal();
557
558     ResourceRequest request(handle->firstRequest());
559     KURL url(request.url());
560     url.removeFragmentIdentifier();
561     request.setURL(url);
562
563     GOwnPtr<GError> error;
564     d->m_soupRequest = adoptPlatformRef(webkit_soup_requester_request(d->m_requester.get(), url.string().utf8().data(), session, &error.outPtr()));
565     if (error) {
566         d->m_soupRequest = 0;
567         return false;
568     }
569
570     g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", handle);
571
572     d->m_soupMessage = adoptPlatformRef(webkit_soup_request_http_get_message(WEBKIT_SOUP_REQUEST_HTTP(d->m_soupRequest.get())));
573     if (!d->m_soupMessage)
574         return false;
575
576     SoupMessage* soupMessage = d->m_soupMessage.get();
577     request.updateSoupMessage(soupMessage);
578
579     if (!handle->shouldContentSniff())
580         soup_message_disable_feature(soupMessage, SOUP_TYPE_CONTENT_SNIFFER);
581
582     g_signal_connect(soupMessage, "restarted", G_CALLBACK(restartedCallback), handle);
583     g_signal_connect(soupMessage, "got-headers", G_CALLBACK(gotHeadersCallback), handle);
584     g_signal_connect(soupMessage, "content-sniffed", G_CALLBACK(contentSniffedCallback), handle);
585     d->m_gotChunkHandler = g_signal_connect(soupMessage, "got-chunk", G_CALLBACK(gotChunkCallback), handle);
586
587 #ifdef HAVE_LIBSOUP_2_29_90
588     String firstPartyString = request.firstPartyForCookies().string();
589     if (!firstPartyString.isEmpty()) {
590         GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
591         soup_message_set_first_party(soupMessage, firstParty.get());
592     }
593 #endif
594
595     FormData* httpBody = d->m_firstRequest.httpBody();
596     if (httpBody && !httpBody->isEmpty()) {
597         size_t numElements = httpBody->elements().size();
598
599         // handle the most common case (i.e. no file upload)
600         if (numElements < 2) {
601             Vector<char> body;
602             httpBody->flatten(body);
603             soup_message_set_request(soupMessage, d->m_firstRequest.httpContentType().utf8().data(),
604                                      SOUP_MEMORY_COPY, body.data(), body.size());
605         } else {
606             /*
607              * we have more than one element to upload, and some may
608              * be (big) files, which we will want to mmap instead of
609              * copying into memory; TODO: support upload of non-local
610              * (think sftp://) files by using GIO?
611              */
612             soup_message_body_set_accumulate(soupMessage->request_body, FALSE);
613             for (size_t i = 0; i < numElements; i++) {
614                 const FormDataElement& element = httpBody->elements()[i];
615
616                 if (element.m_type == FormDataElement::data)
617                     soup_message_body_append(soupMessage->request_body, SOUP_MEMORY_TEMPORARY, element.m_data.data(), element.m_data.size());
618                 else {
619                     /*
620                      * mapping for uploaded files code inspired by technique used in
621                      * libsoup's simple-httpd test
622                      */
623                     GOwnPtr<GError> error;
624                     CString fileName = fileSystemRepresentation(element.m_filename);
625                     GMappedFile* fileMapping = g_mapped_file_new(fileName.data(), false, &error.outPtr());
626
627                     if (error) {
628                         g_signal_handlers_disconnect_matched(soupMessage, G_SIGNAL_MATCH_DATA,
629                                                              0, 0, 0, 0, handle);
630                         d->m_soupMessage.clear();
631
632                         return false;
633                     }
634
635                     SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping),
636                                                                         g_mapped_file_get_length(fileMapping),
637                                                                         fileMapping,
638                                                                         reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
639                     soup_message_body_append_buffer(soupMessage->request_body, soupBuffer);
640                     soup_buffer_free(soupBuffer);
641                 }
642             }
643         }
644     }
645
646     // balanced by a deref() in cleanupSoupRequestOperation, which should always run
647     handle->ref();
648
649     // Make sure we have an Accept header for subresources; some sites
650     // want this to serve some of their subresources
651     if (!soup_message_headers_get_one(soupMessage->request_headers, "Accept"))
652         soup_message_headers_append(soupMessage->request_headers, "Accept", "*/*");
653
654     d->m_cancellable = adoptPlatformRef(g_cancellable_new());
655     webkit_soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
656
657     return true;
658 }
659
660 bool ResourceHandle::start(NetworkingContext* context)
661 {
662     ASSERT(!d->m_soupMessage);
663
664     // The frame could be null if the ResourceHandle is not associated to any
665     // Frame, e.g. if we are downloading a file.
666     // If the frame is not null but the page is null this must be an attempted
667     // load from an unload handler, so let's just block it.
668     // If both the frame and the page are not null the context is valid.
669     if (context && !context->isValid())
670         return false;
671
672     KURL url = firstRequest().url();
673     String urlString = url.string();
674     String protocol = url.protocol();
675
676     // Used to set the authentication dialog toplevel; may be NULL
677     d->m_context = context;
678
679     if (equalIgnoringCase(protocol, "data"))
680         return startData(this, urlString);
681
682     if (equalIgnoringCase(protocol, "http") || equalIgnoringCase(protocol, "https")) {
683         if (startHttp(this))
684             return true;
685     }
686
687     if (equalIgnoringCase(protocol, "file") || equalIgnoringCase(protocol, "ftp") || equalIgnoringCase(protocol, "ftps")) {
688         // FIXME: should we be doing any other protocols here?
689         if (startGio(this, url))
690             return true;
691     }
692
693     // Error must not be reported immediately
694     this->scheduleFailure(InvalidURLFailure);
695
696     return true;
697 }
698
699 void ResourceHandle::cancel()
700 {
701     d->m_cancelled = true;
702     if (d->m_soupMessage)
703         soup_session_cancel_message(defaultSession(), d->m_soupMessage.get(), SOUP_STATUS_CANCELLED);
704     else if (d->m_cancellable)
705         g_cancellable_cancel(d->m_cancellable.get());
706 }
707
708 PassRefPtr<SharedBuffer> ResourceHandle::bufferedData()
709 {
710     ASSERT_NOT_REACHED();
711     return 0;
712 }
713
714 bool ResourceHandle::supportsBufferedData()
715 {
716     return false;
717 }
718
719 void ResourceHandle::platformSetDefersLoading(bool)
720 {
721     notImplemented();
722 }
723
724 bool ResourceHandle::loadsBlocked()
725 {
726     return false;
727 }
728
729 bool ResourceHandle::willLoadFromCache(ResourceRequest&, Frame*)
730 {
731     // Not having this function means that we'll ask the user about re-posting a form
732     // even when we go back to a page that's still in the cache.
733     notImplemented();
734     return false;
735 }
736
737 void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
738 {
739     WebCoreSynchronousLoader syncLoader(error, response, data);
740     // FIXME: we should use the ResourceHandle::create method here,
741     // but it makes us timeout in a couple of tests. See
742     // https://bugs.webkit.org/show_bug.cgi?id=41823
743     RefPtr<ResourceHandle> handle = adoptRef(new ResourceHandle(request, &syncLoader, true, false));
744     handle->start(context);
745
746     syncLoader.run();
747 }
748
749 static void closeCallback(GObject* source, GAsyncResult* res, gpointer)
750 {
751     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
752     if (!handle)
753         return;
754
755     ResourceHandleInternal* d = handle->getInternal();
756     ResourceHandleClient* client = handle->client();
757
758     g_input_stream_close_finish(d->m_inputStream.get(), res, 0);
759     cleanupSoupRequestOperation(handle.get());
760
761     // The load may have been cancelled, the client may have been
762     // destroyed already. In such cases calling didFinishLoading is a
763     // bad idea.
764     if (d->m_cancelled || !client)
765         return;
766
767     client->didFinishLoading(handle.get(), 0);
768 }
769
770 static void readCallback(GObject* source, GAsyncResult* asyncResult, gpointer data)
771 {
772     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
773     if (!handle)
774         return;
775
776     bool convertToUTF16 = static_cast<bool>(data);
777     ResourceHandleInternal* d = handle->getInternal();
778     ResourceHandleClient* client = handle->client();
779
780     if (d->m_cancelled || !client) {
781         cleanupSoupRequestOperation(handle.get());
782         return;
783     }
784
785     GOwnPtr<GError> error;
786
787     gssize bytesRead = g_input_stream_read_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
788     if (error) {
789         SoupURI* uri = webkit_soup_request_get_uri(d->m_soupRequest.get());
790         GOwnPtr<char> uriStr(soup_uri_to_string(uri, false));
791         ResourceError resourceError(g_quark_to_string(G_IO_ERROR), error->code, uriStr.get(),
792                                     error ? String::fromUTF8(error->message) : String());
793         cleanupSoupRequestOperation(handle.get());
794         client->didFail(handle.get(), resourceError);
795         return;
796     }
797
798     if (!bytesRead) {
799         g_input_stream_close_async(d->m_inputStream.get(), G_PRIORITY_DEFAULT,
800                                    0, closeCallback, 0);
801         return;
802     }
803
804     d->m_total += bytesRead;
805     if (G_LIKELY(!convertToUTF16))
806         client->didReceiveData(handle.get(), d->m_buffer, bytesRead, d->m_total);
807     else {
808         // We have to convert it to UTF-16 due to limitations in KURL
809         String data = String::fromUTF8(d->m_buffer, bytesRead);
810         client->didReceiveData(handle.get(), reinterpret_cast<const char*>(data.characters()), data.length() * sizeof(UChar), 0);
811     }
812
813     // didReceiveData may cancel the load, which may release the last reference.
814     if (d->m_cancelled || !client) {
815         cleanupSoupRequestOperation(handle.get());
816         return;
817     }
818
819     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE, G_PRIORITY_DEFAULT,
820                               d->m_cancellable.get(), readCallback, data);
821 }
822
823 static bool startGio(ResourceHandle* handle, KURL url)
824 {
825     ASSERT(handle);
826
827     if (handle->firstRequest().httpMethod() != "GET" && handle->firstRequest().httpMethod() != "POST")
828         return false;
829
830     SoupSession* session = handle->defaultSession();
831     ResourceHandleInternal* d = handle->getInternal();
832
833     // GIO doesn't know how to handle refs and queries, so remove them
834     // TODO: use KURL.fileSystemPath after KURLGtk and FileSystemGtk are
835     // using GIO internally, and providing URIs instead of file paths
836     url.removeFragmentIdentifier();
837     url.setQuery(String());
838     url.removePort();
839     CString urlStr = url.string().utf8();
840
841     GOwnPtr<GError> error;
842     d->m_soupRequest = adoptPlatformRef(webkit_soup_requester_request(d->m_requester.get(), urlStr.data(), session, &error.outPtr()));
843     if (error) {
844         d->m_soupRequest = 0;
845         return false;
846     }
847
848     g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", handle);
849
850     // balanced by a deref() in cleanupSoupRequestOperation, which should always run
851     handle->ref();
852
853     d->m_cancellable = adoptPlatformRef(g_cancellable_new());
854     webkit_soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
855
856     return true;
857 }
858
859 SoupSession* ResourceHandle::defaultSession()
860 {
861     static SoupSession* session = createSoupSession();
862
863     return session;
864 }
865
866 }