2011-02-10 Martin Robinson <mrobinson@igalia.com>
[WebKit.git] / Source / 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 "TextEncoding.h"
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <gio/gio.h>
52 #include <glib.h>
53 #define LIBSOUP_USE_UNSTABLE_REQUEST_API
54 #include <libsoup/soup-request-http.h>
55 #include <libsoup/soup-requester.h>
56 #include <libsoup/soup.h>
57 #include <sys/stat.h>
58 #include <sys/types.h>
59 #include <unistd.h>
60
61 namespace WebCore {
62
63 #define READ_BUFFER_SIZE 8192
64
65 class WebCoreSynchronousLoader : public ResourceHandleClient {
66     WTF_MAKE_NONCOPYABLE(WebCoreSynchronousLoader);
67 public:
68     WebCoreSynchronousLoader(ResourceError&, ResourceResponse &, Vector<char>&);
69     ~WebCoreSynchronousLoader();
70
71     virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
72     virtual void didReceiveData(ResourceHandle*, const char*, int, int lengthReceived);
73     virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
74     virtual void didFail(ResourceHandle*, const ResourceError&);
75
76     void run();
77
78 private:
79     ResourceError& m_error;
80     ResourceResponse& m_response;
81     Vector<char>& m_data;
82     bool m_finished;
83     GMainLoop* m_mainLoop;
84 };
85
86 WebCoreSynchronousLoader::WebCoreSynchronousLoader(ResourceError& error, ResourceResponse& response, Vector<char>& data)
87     : m_error(error)
88     , m_response(response)
89     , m_data(data)
90     , m_finished(false)
91 {
92     m_mainLoop = g_main_loop_new(0, false);
93 }
94
95 WebCoreSynchronousLoader::~WebCoreSynchronousLoader()
96 {
97     g_main_loop_unref(m_mainLoop);
98 }
99
100 void WebCoreSynchronousLoader::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
101 {
102     m_response = response;
103 }
104
105 void WebCoreSynchronousLoader::didReceiveData(ResourceHandle*, const char* data, int length, int)
106 {
107     m_data.append(data, length);
108 }
109
110 void WebCoreSynchronousLoader::didFinishLoading(ResourceHandle*, double)
111 {
112     g_main_loop_quit(m_mainLoop);
113     m_finished = true;
114 }
115
116 void WebCoreSynchronousLoader::didFail(ResourceHandle* handle, const ResourceError& error)
117 {
118     m_error = error;
119     didFinishLoading(handle, 0);
120 }
121
122 void WebCoreSynchronousLoader::run()
123 {
124     if (!m_finished)
125         g_main_loop_run(m_mainLoop);
126 }
127
128 static void cleanupSoupRequestOperation(ResourceHandle*, bool isDestroying);
129 static void sendRequestCallback(GObject*, GAsyncResult*, gpointer);
130 static void readCallback(GObject*, GAsyncResult*, gpointer);
131 static void closeCallback(GObject*, GAsyncResult*, gpointer);
132 static bool startNonHTTPRequest(ResourceHandle*, KURL);
133
134 ResourceHandleInternal::~ResourceHandleInternal()
135 {
136     if (m_soupRequest)
137         g_object_set_data(G_OBJECT(m_soupRequest.get()), "webkit-resource", 0);
138
139     if (m_idleHandler) {
140         g_source_remove(m_idleHandler);
141         m_idleHandler = 0;
142     }
143 }
144
145 ResourceHandle::~ResourceHandle()
146 {
147     cleanupSoupRequestOperation(this, true);
148 }
149
150 static void ensureSessionIsInitialized(SoupSession* session)
151 {
152     // Values taken from http://stevesouders.com/ua/index.php following
153     // the rule "Do What Every Other Modern Browser Is Doing". They seem
154     // to significantly improve page loading time compared to soup's
155     // default values.
156     static const int maxConnections = 60;
157     static const int maxConnectionsPerHost = 6;
158
159     if (g_object_get_data(G_OBJECT(session), "webkit-init"))
160         return;
161
162     SoupCookieJar* jar = SOUP_COOKIE_JAR(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
163     if (!jar)
164         soup_session_add_feature(session, SOUP_SESSION_FEATURE(defaultCookieJar()));
165     else
166         setDefaultCookieJar(jar);
167
168     if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
169         SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
170         soup_session_add_feature(session, SOUP_SESSION_FEATURE(logger));
171         g_object_unref(logger);
172     }
173
174     SoupRequester* requester = soup_requester_new();
175     soup_session_add_feature(session, SOUP_SESSION_FEATURE(requester));
176     g_object_unref(requester);
177
178     g_object_set(session,
179                  SOUP_SESSION_MAX_CONNS, maxConnections,
180                  SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
181                  NULL);
182
183     g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
184 }
185
186 void ResourceHandle::prepareForURL(const KURL &url)
187 {
188     GOwnPtr<SoupURI> soupURI(soup_uri_new(url.prettyURL().utf8().data()));
189     if (!soupURI)
190         return;
191     soup_session_prepare_for_uri(ResourceHandle::defaultSession(), soupURI.get());
192 }
193
194 // All other kinds of redirections, except for the *304* status code
195 // (SOUP_STATUS_NOT_MODIFIED) which needs to be fed into WebCore, will be
196 // handled by soup directly.
197 static gboolean statusWillBeHandledBySoup(guint statusCode)
198 {
199     if (SOUP_STATUS_IS_TRANSPORT_ERROR(statusCode)
200         || (SOUP_STATUS_IS_REDIRECTION(statusCode) && (statusCode != SOUP_STATUS_NOT_MODIFIED))
201         || (statusCode == SOUP_STATUS_UNAUTHORIZED))
202         return true;
203
204     return false;
205 }
206
207 static void fillResponseFromMessage(SoupMessage* msg, ResourceResponse* response)
208 {
209     response->updateFromSoupMessage(msg);
210 }
211
212 // Called each time the message is going to be sent again except the first time.
213 // It's used mostly to let webkit know about redirects.
214 static void restartedCallback(SoupMessage* msg, gpointer data)
215 {
216     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
217     if (!handle)
218         return;
219     ResourceHandleInternal* d = handle->getInternal();
220     if (d->m_cancelled)
221         return;
222
223     GOwnPtr<char> uri(soup_uri_to_string(soup_message_get_uri(msg), false));
224     String location = String::fromUTF8(uri.get());
225     KURL newURL = KURL(handle->firstRequest().url(), location);
226
227     ResourceRequest request = handle->firstRequest();
228     ResourceResponse response;
229     request.setURL(newURL);
230     request.setHTTPMethod(msg->method);
231     fillResponseFromMessage(msg, &response);
232
233     // Should not set Referer after a redirect from a secure resource to non-secure one.
234     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https")) {
235         request.clearHTTPReferrer();
236         soup_message_headers_remove(msg->request_headers, "Referer");
237     }
238
239     if (d->client())
240         d->client()->willSendRequest(handle, request, response);
241
242     if (d->m_cancelled)
243         return;
244
245     // Update the first party in case the base URL changed with the redirect
246     String firstPartyString = request.firstPartyForCookies().string();
247     if (!firstPartyString.isEmpty()) {
248         GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
249         soup_message_set_first_party(d->m_soupMessage.get(), firstParty.get());
250     }
251 }
252
253 static void contentSniffedCallback(SoupMessage*, const char*, GHashTable*, gpointer);
254
255 static void gotHeadersCallback(SoupMessage* msg, gpointer data)
256 {
257     // For 401, we will accumulate the resource body, and only use it
258     // in case authentication with the soup feature doesn't happen.
259     // For 302 we accumulate the body too because it could be used by
260     // some servers to redirect with a clunky http-equiv=REFRESH
261     if (statusWillBeHandledBySoup(msg->status_code)) {
262         soup_message_body_set_accumulate(msg->response_body, TRUE);
263         return;
264     }
265
266     // For all the other responses, we handle each chunk ourselves,
267     // and we don't need msg->response_body to contain all of the data
268     // we got, when we finish downloading.
269     soup_message_body_set_accumulate(msg->response_body, FALSE);
270
271     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
272
273     // The content-sniffed callback will handle the response if WebCore
274     // require us to sniff.
275     if (!handle || statusWillBeHandledBySoup(msg->status_code))
276         return;
277
278     if (handle->shouldContentSniff()) {
279         // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
280         if (msg->status_code == SOUP_STATUS_NOT_MODIFIED) {
281             soup_message_disable_feature(msg, SOUP_TYPE_CONTENT_SNIFFER);
282             g_signal_handlers_disconnect_by_func(msg, reinterpret_cast<gpointer>(contentSniffedCallback), handle.get());
283         } else
284             return;
285     }
286
287     ResourceHandleInternal* d = handle->getInternal();
288     if (d->m_cancelled)
289         return;
290     ResourceHandleClient* client = handle->client();
291     if (!client)
292         return;
293
294     ASSERT(d->m_response.isNull());
295
296     fillResponseFromMessage(msg, &d->m_response);
297     client->didReceiveResponse(handle.get(), d->m_response);
298 }
299
300 static void wroteBodyDataCallback(SoupMessage*, SoupBuffer* buffer, gpointer data)
301 {
302     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
303     if (!handle)
304         return;
305
306     ASSERT(buffer);
307     ResourceHandleInternal* internal = handle->getInternal();
308     internal->m_bodyDataSent += buffer->length;
309
310     if (internal->m_cancelled)
311         return;
312     ResourceHandleClient* client = handle->client();
313     if (!client)
314         return;
315
316     client->didSendData(handle.get(), internal->m_bodyDataSent, internal->m_bodySize);
317 }
318
319 // This callback will not be called if the content sniffer is disabled in startHTTPRequest.
320 static void contentSniffedCallback(SoupMessage* msg, const char* sniffedType, GHashTable *params, gpointer data)
321 {
322     if (sniffedType) {
323         const char* officialType = soup_message_headers_get_one(msg->response_headers, "Content-Type");
324
325         if (!officialType || strcmp(officialType, sniffedType))
326             soup_message_headers_set_content_type(msg->response_headers, sniffedType, params);
327     }
328
329     if (statusWillBeHandledBySoup(msg->status_code))
330         return;
331
332     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
333     if (!handle)
334         return;
335     ResourceHandleInternal* d = handle->getInternal();
336     if (d->m_cancelled)
337         return;
338     ResourceHandleClient* client = handle->client();
339     if (!client)
340         return;
341
342     ASSERT(d->m_response.isNull());
343
344     fillResponseFromMessage(msg, &d->m_response);
345     client->didReceiveResponse(handle.get(), d->m_response);
346 }
347
348 static void gotChunkCallback(SoupMessage* msg, SoupBuffer* chunk, gpointer data)
349 {
350     if (statusWillBeHandledBySoup(msg->status_code))
351         return;
352
353     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
354     if (!handle)
355         return;
356     ResourceHandleInternal* d = handle->getInternal();
357     if (d->m_cancelled)
358         return;
359     ResourceHandleClient* client = handle->client();
360     if (!client)
361         return;
362
363     ASSERT(!d->m_response.isNull());
364
365     client->didReceiveData(handle.get(), chunk->data, chunk->length, false);
366 }
367
368 static SoupSession* createSoupSession()
369 {
370     return soup_session_async_new();
371 }
372
373 static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroying = false)
374 {
375     ResourceHandleInternal* d = handle->getInternal();
376
377     if (d->m_soupRequest) {
378         g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", 0);
379         d->m_soupRequest.clear();
380     }
381
382     if (d->m_inputStream) {
383         g_object_set_data(G_OBJECT(d->m_inputStream.get()), "webkit-resource", 0);
384         d->m_inputStream.clear();
385     }
386
387     d->m_cancellable.clear();
388
389     if (d->m_soupMessage) {
390         g_signal_handlers_disconnect_matched(d->m_soupMessage.get(), G_SIGNAL_MATCH_DATA,
391                                              0, 0, 0, 0, handle);
392         d->m_soupMessage.clear();
393     }
394
395     if (d->m_buffer) {
396         g_slice_free1(READ_BUFFER_SIZE, d->m_buffer);
397         d->m_buffer = 0;
398     }
399
400     if (!isDestroying)
401         handle->deref();
402 }
403
404 static void sendRequestCallback(GObject* source, GAsyncResult* res, gpointer userData)
405 {
406     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
407     if (!handle)
408         return;
409
410     ResourceHandleInternal* d = handle->getInternal();
411     ResourceHandleClient* client = handle->client();
412
413     if (d->m_gotChunkHandler) {
414         // No need to call gotChunkHandler anymore. Received data will
415         // be reported by readCallback
416         if (g_signal_handler_is_connected(d->m_soupMessage.get(), d->m_gotChunkHandler))
417             g_signal_handler_disconnect(d->m_soupMessage.get(), d->m_gotChunkHandler);
418     }
419
420     if (d->m_cancelled || !client) {
421         cleanupSoupRequestOperation(handle.get());
422         return;
423     }
424
425     GOwnPtr<GError> error;
426     GInputStream* in = soup_request_send_finish(d->m_soupRequest.get(), res, &error.outPtr());
427
428     if (error) {
429         SoupMessage* soupMsg = d->m_soupMessage.get();
430         gboolean isTransportError = d->m_soupMessage && SOUP_STATUS_IS_TRANSPORT_ERROR(soupMsg->status_code);
431
432         if (isTransportError || (error->domain == G_IO_ERROR)) {
433             SoupURI* uri = soup_request_get_uri(d->m_soupRequest.get());
434             GOwnPtr<char> uriStr(soup_uri_to_string(uri, false));
435             gint errorCode = isTransportError ? static_cast<gint>(soupMsg->status_code) : error->code;
436             const gchar* errorMsg = isTransportError ? soupMsg->reason_phrase : error->message;
437             const gchar* quarkStr = isTransportError ? g_quark_to_string(SOUP_HTTP_ERROR) : g_quark_to_string(G_IO_ERROR);
438             ResourceError resourceError(quarkStr, errorCode, uriStr.get(), String::fromUTF8(errorMsg));
439
440             cleanupSoupRequestOperation(handle.get());
441             client->didFail(handle.get(), resourceError);
442             return;
443         }
444
445         if (d->m_soupMessage && statusWillBeHandledBySoup(d->m_soupMessage->status_code)) {
446             ASSERT(d->m_response.isNull());
447
448             fillResponseFromMessage(soupMsg, &d->m_response);
449             client->didReceiveResponse(handle.get(), d->m_response);
450
451             // WebCore might have cancelled the job in the while. We
452             // must check for response_body->length and not
453             // response_body->data as libsoup always creates the
454             // SoupBuffer for the body even if the length is 0
455             if (!d->m_cancelled && soupMsg->response_body->length)
456                 client->didReceiveData(handle.get(), soupMsg->response_body->data, soupMsg->response_body->length, true);
457         }
458
459         // didReceiveData above might have cancelled it
460         if (d->m_cancelled || !client) {
461             cleanupSoupRequestOperation(handle.get());
462             return;
463         }
464
465         client->didFinishLoading(handle.get(), 0);
466         return;
467     }
468
469     if (d->m_cancelled) {
470         cleanupSoupRequestOperation(handle.get());
471         return;
472     }
473
474     d->m_inputStream = adoptGRef(in);
475     d->m_buffer = static_cast<char*>(g_slice_alloc0(READ_BUFFER_SIZE));
476     d->m_total = 0;
477
478     // readCallback needs it
479     g_object_set_data(G_OBJECT(d->m_inputStream.get()), "webkit-resource", handle.get());
480
481     // If not using SoupMessage we need to call didReceiveResponse now.
482     // (This will change later when SoupRequest supports content sniffing.)
483     if (!d->m_soupMessage) {
484         d->m_response.setURL(handle->firstRequest().url());
485         const gchar* contentType = soup_request_get_content_type(d->m_soupRequest.get());
486         d->m_response.setMimeType(extractMIMETypeFromMediaType(contentType));
487         d->m_response.setTextEncodingName(extractCharsetFromMediaType(contentType));
488         d->m_response.setExpectedContentLength(soup_request_get_content_length(d->m_soupRequest.get()));
489         client->didReceiveResponse(handle.get(), d->m_response);
490
491         if (d->m_cancelled) {
492             cleanupSoupRequestOperation(handle.get());
493             return;
494         }
495     }
496
497     if (d->m_defersLoading)
498          soup_session_pause_message(handle->defaultSession(), d->m_soupMessage.get());
499
500     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
501                               G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, 0);
502 }
503
504 static bool addFormElementsToSoupMessage(SoupMessage* message, const char* contentType, FormData* httpBody, unsigned long& totalBodySize)
505 {
506     size_t numElements = httpBody->elements().size();
507     if (numElements < 2) { // No file upload is the most common case.
508         Vector<char> body;
509         httpBody->flatten(body);
510         totalBodySize = body.size();
511         soup_message_set_request(message, contentType, SOUP_MEMORY_COPY, body.data(), body.size());
512         return true;
513     }
514
515     // We have more than one element to upload, and some may be large files,
516     // which we will want to mmap instead of copying into memory
517     soup_message_body_set_accumulate(message->request_body, FALSE);
518     for (size_t i = 0; i < numElements; i++) {
519         const FormDataElement& element = httpBody->elements()[i];
520
521         if (element.m_type == FormDataElement::data) {
522             totalBodySize += element.m_data.size();
523             soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
524                                      element.m_data.data(), element.m_data.size());
525             continue;
526         }
527
528         // This technique is inspired by libsoup's simple-httpd test.
529         GOwnPtr<GError> error;
530         CString fileName = fileSystemRepresentation(element.m_filename);
531         GMappedFile* fileMapping = g_mapped_file_new(fileName.data(), false, &error.outPtr());
532         if (error)
533             return false;
534
535         gsize mappedFileSize = g_mapped_file_get_length(fileMapping);
536         totalBodySize += mappedFileSize;
537         SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping),
538                                                             mappedFileSize, fileMapping,
539                                                             reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
540         soup_message_body_append_buffer(message->request_body, soupBuffer);
541         soup_buffer_free(soupBuffer);
542     }
543
544     return true;
545 }
546
547 static bool startHTTPRequest(ResourceHandle* handle)
548 {
549     ASSERT(handle);
550
551     SoupSession* session = handle->defaultSession();
552     ensureSessionIsInitialized(session);
553     SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(session, SOUP_TYPE_REQUESTER));
554
555     ResourceHandleInternal* d = handle->getInternal();
556
557     ResourceRequest request(handle->firstRequest());
558     KURL url(request.url());
559     url.removeFragmentIdentifier();
560     request.setURL(url);
561
562     GOwnPtr<GError> error;
563     d->m_soupRequest = adoptGRef(soup_requester_request(requester, url.string().utf8().data(), &error.outPtr()));
564     if (error) {
565         d->m_soupRequest = 0;
566         return false;
567     }
568
569     g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", handle);
570
571     d->m_soupMessage = adoptGRef(soup_request_http_get_message(SOUP_REQUEST_HTTP(d->m_soupRequest.get())));
572     if (!d->m_soupMessage)
573         return false;
574
575     SoupMessage* soupMessage = d->m_soupMessage.get();
576     request.updateSoupMessage(soupMessage);
577
578     if (!handle->shouldContentSniff())
579         soup_message_disable_feature(soupMessage, SOUP_TYPE_CONTENT_SNIFFER);
580     else
581         g_signal_connect(soupMessage, "content-sniffed", G_CALLBACK(contentSniffedCallback), handle);
582
583     g_signal_connect(soupMessage, "restarted", G_CALLBACK(restartedCallback), handle);
584     g_signal_connect(soupMessage, "got-headers", G_CALLBACK(gotHeadersCallback), handle);
585     g_signal_connect(soupMessage, "wrote-body-data", G_CALLBACK(wroteBodyDataCallback), handle);
586     d->m_gotChunkHandler = g_signal_connect(soupMessage, "got-chunk", G_CALLBACK(gotChunkCallback), handle);
587
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
594     FormData* httpBody = d->m_firstRequest.httpBody();
595     CString contentType = d->m_firstRequest.httpContentType().utf8().data();
596     if (httpBody && !httpBody->isEmpty()
597         && !addFormElementsToSoupMessage(soupMessage, contentType.data(), httpBody, d->m_bodySize)) {
598         // We failed to prepare the body data, so just fail this load.
599         g_signal_handlers_disconnect_matched(soupMessage, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, handle);
600         d->m_soupMessage.clear();
601         return false;
602     }
603
604     // balanced by a deref() in cleanupSoupRequestOperation, which should always run
605     handle->ref();
606
607     // Make sure we have an Accept header for subresources; some sites
608     // want this to serve some of their subresources
609     if (!soup_message_headers_get_one(soupMessage->request_headers, "Accept"))
610         soup_message_headers_append(soupMessage->request_headers, "Accept", "*/*");
611
612     // Send the request only if it's not been explicitely deferred.
613     if (!d->m_defersLoading) {
614         d->m_cancellable = adoptGRef(g_cancellable_new());
615         soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
616     }
617
618     return true;
619 }
620
621 bool ResourceHandle::start(NetworkingContext* context)
622 {
623     ASSERT(!d->m_soupMessage);
624
625     // The frame could be null if the ResourceHandle is not associated to any
626     // Frame, e.g. if we are downloading a file.
627     // If the frame is not null but the page is null this must be an attempted
628     // load from an unload handler, so let's just block it.
629     // If both the frame and the page are not null the context is valid.
630     if (context && !context->isValid())
631         return false;
632
633     if (!(d->m_user.isEmpty() || d->m_pass.isEmpty())) {
634         // If credentials were specified for this request, add them to the url,
635         // so that they will be passed to NetworkRequest.
636         KURL urlWithCredentials(firstRequest().url());
637         urlWithCredentials.setUser(d->m_user);
638         urlWithCredentials.setPass(d->m_pass);
639         d->m_firstRequest.setURL(urlWithCredentials);
640     }
641
642     KURL url = firstRequest().url();
643     String urlString = url.string();
644     String protocol = url.protocol();
645
646     // Used to set the authentication dialog toplevel; may be NULL
647     d->m_context = context;
648
649     if (equalIgnoringCase(protocol, "http") || equalIgnoringCase(protocol, "https")) {
650         if (startHTTPRequest(this))
651             return true;
652     }
653
654     if (startNonHTTPRequest(this, url))
655         return true;
656
657     // Error must not be reported immediately
658     this->scheduleFailure(InvalidURLFailure);
659
660     return true;
661 }
662
663 void ResourceHandle::cancel()
664 {
665     d->m_cancelled = true;
666     if (d->m_soupMessage)
667         soup_session_cancel_message(defaultSession(), d->m_soupMessage.get(), SOUP_STATUS_CANCELLED);
668     else if (d->m_cancellable)
669         g_cancellable_cancel(d->m_cancellable.get());
670 }
671
672 PassRefPtr<SharedBuffer> ResourceHandle::bufferedData()
673 {
674     ASSERT_NOT_REACHED();
675     return 0;
676 }
677
678 bool ResourceHandle::supportsBufferedData()
679 {
680     return false;
681 }
682
683 void ResourceHandle::platformSetDefersLoading(bool defersLoading)
684 {
685     // Initial implementation of this method was required for bug #44157.
686
687     if (d->m_cancelled)
688         return;
689
690     if (!defersLoading && !d->m_cancellable && d->m_soupRequest.get()) {
691         d->m_cancellable = adoptGRef(g_cancellable_new());
692         soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
693         return;
694     }
695
696     // Only supported for http(s) transfers. Something similar would
697     // probably be needed for data transfers done with GIO.
698     if (!d->m_soupMessage)
699         return;
700
701     if (defersLoading)
702         soup_session_pause_message(defaultSession(), d->m_soupMessage.get());
703     else
704         soup_session_unpause_message(defaultSession(), d->m_soupMessage.get());
705 }
706
707 bool ResourceHandle::loadsBlocked()
708 {
709     return false;
710 }
711
712 bool ResourceHandle::willLoadFromCache(ResourceRequest&, Frame*)
713 {
714     // Not having this function means that we'll ask the user about re-posting a form
715     // even when we go back to a page that's still in the cache.
716     notImplemented();
717     return false;
718 }
719
720 void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
721 {
722     WebCoreSynchronousLoader syncLoader(error, response, data);
723     RefPtr<ResourceHandle> handle = create(context, request, &syncLoader, false /*defersLoading*/, false /*shouldContentSniff*/);
724     if (!handle)
725         return;
726
727     // If the request has already failed, do not run the main loop, or else we'll block indefinitely.
728     if (handle->d->m_scheduledFailureType != NoFailure)
729         return;
730
731     syncLoader.run();
732 }
733
734 static void closeCallback(GObject* source, GAsyncResult* res, gpointer)
735 {
736     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
737     if (!handle)
738         return;
739
740     ResourceHandleInternal* d = handle->getInternal();
741     g_input_stream_close_finish(d->m_inputStream.get(), res, 0);
742     cleanupSoupRequestOperation(handle.get());
743 }
744
745 static void readCallback(GObject* source, GAsyncResult* asyncResult, gpointer data)
746 {
747     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
748     if (!handle)
749         return;
750
751     bool convertToUTF16 = static_cast<bool>(data);
752     ResourceHandleInternal* d = handle->getInternal();
753     ResourceHandleClient* client = handle->client();
754
755     if (d->m_cancelled || !client) {
756         cleanupSoupRequestOperation(handle.get());
757         return;
758     }
759
760     GOwnPtr<GError> error;
761
762     gssize bytesRead = g_input_stream_read_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
763     if (error) {
764         SoupURI* uri = soup_request_get_uri(d->m_soupRequest.get());
765         GOwnPtr<char> uriStr(soup_uri_to_string(uri, false));
766         ResourceError resourceError(g_quark_to_string(G_IO_ERROR), error->code, uriStr.get(),
767                                     error ? String::fromUTF8(error->message) : String());
768         cleanupSoupRequestOperation(handle.get());
769         client->didFail(handle.get(), resourceError);
770         return;
771     }
772
773     if (!bytesRead) {
774         // Finish the load. We do not wait for the stream to
775         // close. Instead we better notify WebCore as soon as possible
776         client->didFinishLoading(handle.get(), 0);
777
778         g_input_stream_close_async(d->m_inputStream.get(), G_PRIORITY_DEFAULT,
779                                    0, closeCallback, 0);
780         return;
781     }
782
783     // It's mandatory to have sent a response before sending data
784     ASSERT(!d->m_response.isNull());
785
786     d->m_total += bytesRead;
787     if (G_LIKELY(!convertToUTF16))
788         client->didReceiveData(handle.get(), d->m_buffer, bytesRead, d->m_total);
789     else {
790         // We have to convert it to UTF-16 due to limitations in KURL
791         String data = String::fromUTF8(d->m_buffer, bytesRead);
792         client->didReceiveData(handle.get(), reinterpret_cast<const char*>(data.characters()), data.length() * sizeof(UChar), 0);
793     }
794
795     // didReceiveData may cancel the load, which may release the last reference.
796     if (d->m_cancelled || !client) {
797         cleanupSoupRequestOperation(handle.get());
798         return;
799     }
800
801     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE, G_PRIORITY_DEFAULT,
802                               d->m_cancellable.get(), readCallback, data);
803 }
804
805 static bool startNonHTTPRequest(ResourceHandle* handle, KURL url)
806 {
807     ASSERT(handle);
808
809     if (handle->firstRequest().httpMethod() != "GET" && handle->firstRequest().httpMethod() != "POST")
810         return false;
811
812     SoupSession* session = handle->defaultSession();
813     ensureSessionIsInitialized(session);
814     SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(session, SOUP_TYPE_REQUESTER));
815     ResourceHandleInternal* d = handle->getInternal();
816
817     CString urlStr = url.string().utf8();
818
819     GOwnPtr<GError> error;
820     d->m_soupRequest = adoptGRef(soup_requester_request(requester, urlStr.data(), &error.outPtr()));
821     if (error) {
822         d->m_soupRequest = 0;
823         return false;
824     }
825
826     g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", handle);
827
828     // balanced by a deref() in cleanupSoupRequestOperation, which should always run
829     handle->ref();
830
831     d->m_cancellable = adoptGRef(g_cancellable_new());
832     soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
833
834     return true;
835 }
836
837 SoupSession* ResourceHandle::defaultSession()
838 {
839     static SoupSession* session = createSoupSession();
840
841     return session;
842 }
843
844 }