b723c4be39987f8910cd64f0013a50407be5217f
[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 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  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public License
21  * along with this library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 #include "config.h"
27 #include "ResourceHandle.h"
28
29 #include "Base64.h"
30 #include "CookieJarSoup.h"
31 #include "ChromeClient.h"
32 #include "CString.h"
33 #include "DocLoader.h"
34 #include "FileSystem.h"
35 #include "Frame.h"
36 #include "HTTPParsers.h"
37 #include "Logging.h"
38 #include "MIMETypeRegistry.h"
39 #include "NotImplemented.h"
40 #include "Page.h"
41 #include "ResourceError.h"
42 #include "ResourceHandleClient.h"
43 #include "ResourceHandleInternal.h"
44 #include "ResourceResponse.h"
45 #include "TextEncoding.h"
46
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <gio/gio.h>
50 #include <gtk/gtk.h>
51 #include <libsoup/soup.h>
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <unistd.h>
55
56 #if PLATFORM(GTK)
57 #define USE_GLIB_BASE64
58 #endif
59
60 namespace WebCore {
61
62 class WebCoreSynchronousLoader : public ResourceHandleClient, Noncopyable {
63 public:
64     WebCoreSynchronousLoader(ResourceError&, ResourceResponse &, Vector<char>&);
65     ~WebCoreSynchronousLoader();
66
67     virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
68     virtual void didReceiveData(ResourceHandle*, const char*, int, int lengthReceived);
69     virtual void didFinishLoading(ResourceHandle*);
70     virtual void didFail(ResourceHandle*, const ResourceError&);
71
72     void run();
73
74 private:
75     ResourceError& m_error;
76     ResourceResponse& m_response;
77     Vector<char>& m_data;
78     bool m_finished;
79     GMainLoop* m_mainLoop;
80 };
81
82 WebCoreSynchronousLoader::WebCoreSynchronousLoader(ResourceError& error, ResourceResponse& response, Vector<char>& data)
83     : m_error(error)
84     , m_response(response)
85     , m_data(data)
86     , m_finished(false)
87 {
88     m_mainLoop = g_main_loop_new(0, false);
89 }
90
91 WebCoreSynchronousLoader::~WebCoreSynchronousLoader()
92 {
93     g_main_loop_unref(m_mainLoop);
94 }
95
96 void WebCoreSynchronousLoader::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
97 {
98     m_response = response;
99 }
100
101 void WebCoreSynchronousLoader::didReceiveData(ResourceHandle*, const char* data, int length, int)
102 {
103     m_data.append(data, length);
104 }
105
106 void WebCoreSynchronousLoader::didFinishLoading(ResourceHandle*)
107 {
108     g_main_loop_quit(m_mainLoop);
109     m_finished = true;
110 }
111
112 void WebCoreSynchronousLoader::didFail(ResourceHandle* handle, const ResourceError& error)
113 {
114     m_error = error;
115     didFinishLoading(handle);
116 }
117
118 void WebCoreSynchronousLoader::run()
119 {
120     if (!m_finished)
121         g_main_loop_run(m_mainLoop);
122 }
123
124 enum
125 {
126     ERROR_TRANSPORT,
127     ERROR_UNKNOWN_PROTOCOL,
128     ERROR_BAD_NON_HTTP_METHOD,
129     ERROR_UNABLE_TO_OPEN_FILE,
130 };
131
132 static void cleanupGioOperation(ResourceHandleInternal* handle);
133
134 ResourceHandleInternal::~ResourceHandleInternal()
135 {
136     if (m_msg) {
137         g_object_unref(m_msg);
138         m_msg = 0;
139     }
140
141     cleanupGioOperation(this);
142
143     if (m_idleHandler) {
144         g_source_remove(m_idleHandler);
145         m_idleHandler = 0;
146     }
147 }
148
149 ResourceHandle::~ResourceHandle()
150 {
151 }
152
153 static void fillResponseFromMessage(SoupMessage* msg, ResourceResponse* response)
154 {
155     SoupMessageHeadersIter iter;
156     const char* name = 0;
157     const char* value = 0;
158     soup_message_headers_iter_init(&iter, msg->response_headers);
159     while (soup_message_headers_iter_next(&iter, &name, &value))
160         response->setHTTPHeaderField(name, value);
161
162     GHashTable* contentTypeParameters = 0;
163     String contentType = soup_message_headers_get_content_type(msg->response_headers, &contentTypeParameters);
164
165     // When the server sends multiple Content-Type headers, soup will
166     // give us their values concatenated with commas as a separator;
167     // we need to handle this and use only one value. We use the first
168     // value, and add all the parameters, afterwards, if any.
169     Vector<String> contentTypes;
170     contentType.split(',', true, contentTypes);
171     contentType = contentTypes[0];
172
173     if (contentTypeParameters) {
174         GHashTableIter hashTableIter;
175         gpointer hashKey;
176         gpointer hashValue;
177
178         g_hash_table_iter_init(&hashTableIter, contentTypeParameters);
179         while (g_hash_table_iter_next(&hashTableIter, &hashKey, &hashValue)) {
180             contentType += String("; ");
181             contentType += String(static_cast<char*>(hashKey));
182             contentType += String("=");
183             contentType += String(static_cast<char*>(hashValue));
184         }
185         g_hash_table_destroy(contentTypeParameters);
186     }
187
188     response->setMimeType(extractMIMETypeFromMediaType(contentType));
189
190     char* uri = soup_uri_to_string(soup_message_get_uri(msg), false);
191     response->setURL(KURL(KURL(), uri));
192     g_free(uri);
193     response->setTextEncodingName(extractCharsetFromMediaType(contentType));
194     response->setExpectedContentLength(soup_message_headers_get_content_length(msg->response_headers));
195     response->setHTTPStatusCode(msg->status_code);
196     response->setHTTPStatusText(msg->reason_phrase);
197     response->setSuggestedFilename(filenameFromHTTPContentDisposition(response->httpHeaderField("Content-Disposition")));
198 }
199
200 // Called each time the message is going to be sent again except the first time.
201 // It's used mostly to let webkit know about redirects.
202 static void restartedCallback(SoupMessage* msg, gpointer data)
203 {
204     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
205     if (!handle)
206         return;
207     ResourceHandleInternal* d = handle->getInternal();
208     if (d->m_cancelled)
209         return;
210
211     char* uri = soup_uri_to_string(soup_message_get_uri(msg), false);
212     String location = String(uri);
213     g_free(uri);
214     KURL newURL = KURL(handle->request().url(), location);
215
216     // FIXME: This is needed because some servers use broken URIs in
217     // their Location header, when redirecting, such as URIs with
218     // white spaces instead of %20; this should be fixed in soup, in
219     // the future, and this work-around removed.
220     // See http://bugzilla.gnome.org/show_bug.cgi?id=575378.
221     SoupURI* soup_uri = soup_uri_new(newURL.string().utf8().data());
222     soup_message_set_uri(msg, soup_uri);
223     soup_uri_free(soup_uri);
224
225     ResourceRequest request = handle->request();
226     ResourceResponse response;
227     request.setURL(newURL);
228     fillResponseFromMessage(msg, &response);
229     if (d->client())
230         d->client()->willSendRequest(handle, request, response);
231
232     d->m_request.setURL(newURL);
233 }
234
235 static void gotHeadersCallback(SoupMessage* msg, gpointer data)
236 {
237     // The 304 status code (SOUP_STATUS_NOT_MODIFIED) needs to be fed
238     // into WebCore, as opposed to other kinds of redirections, which
239     // are handled by soup directly, so we special-case it here and in
240     // gotChunk.
241     if (SOUP_STATUS_IS_TRANSPORT_ERROR(msg->status_code)
242         || (SOUP_STATUS_IS_REDIRECTION(msg->status_code) && (msg->status_code != SOUP_STATUS_NOT_MODIFIED)))
243         return;
244
245     // We still don't know anything about Content-Type, so we will try
246     // sniffing the contents of the file, and then report that we got
247     // headers; we will not do content sniffing for 304 responses,
248     // though, since they do not have a body.
249     if ((msg->status_code != SOUP_STATUS_NOT_MODIFIED)
250         && !soup_message_headers_get_content_type(msg->response_headers, NULL))
251         return;
252
253     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
254     if (!handle)
255         return;
256     ResourceHandleInternal* d = handle->getInternal();
257     if (d->m_cancelled)
258         return;
259     ResourceHandleClient* client = handle->client();
260     if (!client)
261         return;
262
263     fillResponseFromMessage(msg, &d->m_response);
264     client->didReceiveResponse(handle, d->m_response);
265     d->m_reportedHeaders = true;
266 }
267
268 static void gotChunkCallback(SoupMessage* msg, SoupBuffer* chunk, gpointer data)
269 {
270     if (SOUP_STATUS_IS_TRANSPORT_ERROR(msg->status_code)
271         || (SOUP_STATUS_IS_REDIRECTION(msg->status_code) && (msg->status_code != SOUP_STATUS_NOT_MODIFIED)))
272         return;
273
274     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
275     if (!handle)
276         return;
277     ResourceHandleInternal* d = handle->getInternal();
278     if (d->m_cancelled)
279         return;
280     ResourceHandleClient* client = handle->client();
281     if (!client)
282         return;
283
284     if (!d->m_reportedHeaders) {
285         gboolean uncertain;
286         char* contentType = g_content_type_guess(d->m_request.url().lastPathComponent().utf8().data(), reinterpret_cast<const guchar*>(chunk->data), chunk->length, &uncertain);
287         soup_message_headers_set_content_type(msg->response_headers, contentType, NULL);
288         g_free(contentType);
289
290         fillResponseFromMessage(msg, &d->m_response);
291         client->didReceiveResponse(handle, d->m_response);
292         d->m_reportedHeaders = true;
293     }
294
295     client->didReceiveData(handle, chunk->data, chunk->length, false);
296 }
297
298 // Called at the end of the message, with all the necessary about the last informations.
299 // Doesn't get called for redirects.
300 static void finishedCallback(SoupSession *session, SoupMessage* msg, gpointer data)
301 {
302     RefPtr<ResourceHandle>handle = adoptRef(static_cast<ResourceHandle*>(data));
303     // TODO: maybe we should run this code even if there's no client?
304     if (!handle)
305         return;
306
307     ResourceHandleInternal* d = handle->getInternal();
308
309     ResourceHandleClient* client = handle->client();
310     if (!client)
311         return;
312
313     if (d->m_cancelled)
314         return;
315
316     if (SOUP_STATUS_IS_TRANSPORT_ERROR(msg->status_code)) {
317         char* uri = soup_uri_to_string(soup_message_get_uri(msg), false);
318         ResourceError error("webkit-network-error", ERROR_TRANSPORT, uri, String::fromUTF8(msg->reason_phrase));
319         g_free(uri);
320         client->didFail(handle.get(), error);
321         return;
322     }
323
324     client->didFinishLoading(handle.get());
325 }
326
327 // parseDataUrl() is taken from the CURL http backend.
328 static gboolean parseDataUrl(gpointer callback_data)
329 {
330     ResourceHandle* handle = static_cast<ResourceHandle*>(callback_data);
331     ResourceHandleClient* client = handle->client();
332
333     handle->getInternal()->m_idleHandler = 0;
334
335     ASSERT(client);
336     if (!client)
337         return false;
338
339     String url = handle->request().url().string();
340     ASSERT(url.startsWith("data:", false));
341
342     int index = url.find(',');
343     if (index == -1) {
344         client->cannotShowURL(handle);
345         return false;
346     }
347
348     String mediaType = url.substring(5, index - 5);
349     String data = url.substring(index + 1);
350
351     bool isBase64 = mediaType.endsWith(";base64", false);
352     if (isBase64)
353         mediaType = mediaType.left(mediaType.length() - 7);
354
355     if (mediaType.isEmpty())
356         mediaType = "text/plain;charset=US-ASCII";
357
358     String mimeType = extractMIMETypeFromMediaType(mediaType);
359     String charset = extractCharsetFromMediaType(mediaType);
360
361     ResourceResponse response;
362     response.setMimeType(mimeType);
363
364     if (isBase64) {
365         data = decodeURLEscapeSequences(data);
366         response.setTextEncodingName(charset);
367         client->didReceiveResponse(handle, response);
368
369         // Use the GLib Base64 if available, since WebCore's decoder isn't
370         // general-purpose and fails on Acid3 test 97 (whitespace).
371 #ifdef USE_GLIB_BASE64
372         size_t outLength = 0;
373         char* outData = 0;
374         outData = reinterpret_cast<char*>(g_base64_decode(data.utf8().data(), &outLength));
375         if (outData && outLength > 0)
376             client->didReceiveData(handle, outData, outLength, 0);
377         g_free(outData);
378 #else
379         Vector<char> out;
380         if (base64Decode(data.latin1().data(), data.latin1().length(), out) && out.size() > 0)
381             client->didReceiveData(handle, out.data(), out.size(), 0);
382 #endif
383     } else {
384         // We have to convert to UTF-16 early due to limitations in KURL
385         data = decodeURLEscapeSequences(data, TextEncoding(charset));
386         response.setTextEncodingName("UTF-16");
387         client->didReceiveResponse(handle, response);
388         if (data.length() > 0)
389             client->didReceiveData(handle, reinterpret_cast<const char*>(data.characters()), data.length() * sizeof(UChar), 0);
390     }
391
392     client->didFinishLoading(handle);
393
394     return false;
395 }
396
397 bool ResourceHandle::startData(String urlString)
398 {
399     ResourceHandleInternal* d = this->getInternal();
400
401     // If parseDataUrl is called synchronously the job is not yet effectively started
402     // and webkit won't never know that the data has been parsed even didFinishLoading is called.
403     d->m_idleHandler = g_idle_add(parseDataUrl, this);
404     return true;
405 }
406
407 static SoupSession* createSoupSession()
408 {
409     return soup_session_async_new();
410 }
411
412 static void ensureSessionIsInitialized(SoupSession* session)
413 {
414     if (g_object_get_data(G_OBJECT(session), "webkit-init"))
415         return;
416
417     SoupCookieJar* jar = reinterpret_cast<SoupCookieJar*>(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
418     if (!jar)
419         soup_session_add_feature(session, SOUP_SESSION_FEATURE(defaultCookieJar()));
420     else
421         setDefaultCookieJar(jar);
422
423     if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
424         SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
425         soup_logger_attach(logger, session);
426         g_object_unref(logger);
427     }
428
429     g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
430 }
431
432 bool ResourceHandle::startHttp(String urlString)
433 {
434     SoupSession* session = defaultSession();
435     ensureSessionIsInitialized(session);
436
437     SoupMessage* msg;
438     msg = soup_message_new(request().httpMethod().utf8().data(), urlString.utf8().data());
439     g_signal_connect(msg, "restarted", G_CALLBACK(restartedCallback), this);
440     g_signal_connect(msg, "got-headers", G_CALLBACK(gotHeadersCallback), this);
441     g_signal_connect(msg, "got-chunk", G_CALLBACK(gotChunkCallback), this);
442
443     g_object_set_data(G_OBJECT(msg), "resourceHandle", reinterpret_cast<void*>(this));
444
445     HTTPHeaderMap customHeaders = d->m_request.httpHeaderFields();
446     if (!customHeaders.isEmpty()) {
447         HTTPHeaderMap::const_iterator end = customHeaders.end();
448         for (HTTPHeaderMap::const_iterator it = customHeaders.begin(); it != end; ++it)
449             soup_message_headers_append(msg->request_headers, it->first.string().utf8().data(), it->second.utf8().data());
450     }
451
452     FormData* httpBody = d->m_request.httpBody();
453     if (httpBody && !httpBody->isEmpty()) {
454         size_t numElements = httpBody->elements().size();
455
456         // handle the most common case (i.e. no file upload)
457         if (numElements < 2) {
458             Vector<char> body;
459             httpBody->flatten(body);
460             soup_message_set_request(msg, d->m_request.httpContentType().utf8().data(),
461                                      SOUP_MEMORY_COPY, body.data(), body.size());
462         } else {
463             /*
464              * we have more than one element to upload, and some may
465              * be (big) files, which we will want to mmap instead of
466              * copying into memory; TODO: support upload of non-local
467              * (think sftp://) files by using GIO?
468              */
469             soup_message_body_set_accumulate(msg->request_body, FALSE);
470             for (size_t i = 0; i < numElements; i++) {
471                 const FormDataElement& element = httpBody->elements()[i];
472
473                 if (element.m_type == FormDataElement::data)
474                     soup_message_body_append(msg->request_body, SOUP_MEMORY_TEMPORARY, element.m_data.data(), element.m_data.size());
475                 else {
476                     /*
477                      * mapping for uploaded files code inspired by technique used in
478                      * libsoup's simple-httpd test
479                      */
480                     GError* error = 0;
481                     gchar* fileName = filenameFromString(element.m_filename);
482                     GMappedFile* fileMapping = g_mapped_file_new(fileName, false, &error);
483
484                     g_free(fileName);
485
486                     if (error) {
487                         ResourceError resourceError("webkit-network-error", ERROR_UNABLE_TO_OPEN_FILE, urlString, error->message);
488                         g_error_free(error);
489
490                         d->client()->didFail(this, resourceError);
491
492                         g_object_unref(msg);
493                         return false;
494                     }
495
496                     SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping),
497                                                                         g_mapped_file_get_length(fileMapping),
498                                                                         fileMapping, reinterpret_cast<GDestroyNotify>(g_mapped_file_free));
499                     soup_message_body_append_buffer(msg->request_body, soupBuffer);
500                     soup_buffer_free(soupBuffer);
501                 }
502             }
503         }
504     }
505
506     d->m_msg = static_cast<SoupMessage*>(g_object_ref(msg));
507     // balanced by a deref() in finishedCallback, which should always run
508     ref();
509
510     // We handle each chunk ourselves, and we don't need msg->response_body
511     // to contain all of the data we got, when we finish downloading.
512     soup_message_body_set_accumulate(msg->response_body, FALSE);
513     soup_session_queue_message(session, d->m_msg, finishedCallback, this);
514
515     return true;
516 }
517
518 static gboolean reportUnknownProtocolError(gpointer callback_data)
519 {
520     ResourceHandle* handle = static_cast<ResourceHandle*>(callback_data);
521     ResourceHandleInternal* d = handle->getInternal();
522     ResourceHandleClient* client = handle->client();
523
524     if (d->m_cancelled || !client) {
525         handle->deref();
526         return false;
527     }
528
529     KURL url = handle->request().url();
530     ResourceError error("webkit-network-error", ERROR_UNKNOWN_PROTOCOL, url.string(), url.protocol());
531     client->didFail(handle, error);
532
533     handle->deref();
534     return false;
535 }
536
537 bool ResourceHandle::start(Frame* frame)
538 {
539     ASSERT(!d->m_msg);
540
541
542     // The frame could be null if the ResourceHandle is not associated to any
543     // Frame, e.g. if we are downloading a file.
544     // If the frame is not null but the page is null this must be an attempted
545     // load from an onUnload handler, so let's just block it.
546     if (frame && !frame->page())
547         return false;
548
549     KURL url = request().url();
550     String urlString = url.string();
551     String protocol = url.protocol();
552
553     // Used to set the authentication dialog toplevel; may be NULL
554     d->m_frame = frame;
555
556     if (equalIgnoringCase(protocol, "data"))
557         return startData(urlString);
558
559     if ((equalIgnoringCase(protocol, "http") || equalIgnoringCase(protocol, "https")) && SOUP_URI_VALID_FOR_HTTP(soup_uri_new(urlString.utf8().data())))
560         return startHttp(urlString);
561
562     if (equalIgnoringCase(protocol, "file") || equalIgnoringCase(protocol, "ftp") || equalIgnoringCase(protocol, "ftps"))
563         // FIXME: should we be doing any other protocols here?
564         return startGio(url);
565
566     // Error must not be reported immediately, but through an idle function.
567     // Despite error, we should return true so a proper handle is created,
568     // to which this failure can be reported.
569     ref();
570     d->m_idleHandler = g_idle_add(reportUnknownProtocolError, this);
571     return true;
572 }
573
574 void ResourceHandle::cancel()
575 {
576     d->m_cancelled = true;
577     if (d->m_msg)
578         soup_session_cancel_message(defaultSession(), d->m_msg, SOUP_STATUS_CANCELLED);
579     else if (d->m_cancellable)
580         g_cancellable_cancel(d->m_cancellable);
581 }
582
583 PassRefPtr<SharedBuffer> ResourceHandle::bufferedData()
584 {
585     ASSERT_NOT_REACHED();
586     return 0;
587 }
588
589 bool ResourceHandle::supportsBufferedData()
590 {
591     return false;
592 }
593
594 void ResourceHandle::setDefersLoading(bool defers)
595 {
596     d->m_defersLoading = defers;
597     notImplemented();
598 }
599
600 bool ResourceHandle::loadsBlocked()
601 {
602     return false;
603 }
604
605 bool ResourceHandle::willLoadFromCache(ResourceRequest&)
606 {
607     // Not having this function means that we'll ask the user about re-posting a form
608     // even when we go back to a page that's still in the cache.
609     notImplemented();
610     return false;
611 }
612
613 void ResourceHandle::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data, Frame* frame)
614 {
615     WebCoreSynchronousLoader syncLoader(error, response, data);
616     ResourceHandle handle(request, &syncLoader, true, false, true);
617
618     handle.start(frame);
619     syncLoader.run();
620 }
621
622 // GIO-based loader
623
624 static inline ResourceError networkErrorForFile(GFile* file, GError* error)
625 {
626     // FIXME: Map gio errors to a more detailed error code when we have it in WebKit.
627     gchar* uri = g_file_get_uri(file);
628     ResourceError resourceError("webkit-network-error", ERROR_TRANSPORT, uri, error ? String::fromUTF8(error->message) : String());
629     g_free(uri);
630     return resourceError;
631 }
632
633 static void cleanupGioOperation(ResourceHandleInternal* d)
634 {
635     if (d->m_gfile) {
636         g_object_set_data(G_OBJECT(d->m_gfile), "webkit-resource", 0);
637         g_object_unref(d->m_gfile);
638         d->m_gfile = 0;
639     }
640
641     if (d->m_cancellable) {
642         g_object_unref(d->m_cancellable);
643         d->m_cancellable = 0;
644     }
645
646     if (d->m_inputStream) {
647         g_object_set_data(G_OBJECT(d->m_inputStream), "webkit-resource", 0);
648         g_object_unref(d->m_inputStream);
649         d->m_inputStream = 0;
650     }
651
652     if (d->m_buffer) {
653         g_free(d->m_buffer);
654         d->m_buffer = 0;
655     }
656 }
657
658 static void closeCallback(GObject* source, GAsyncResult* res, gpointer)
659 {
660     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
661     if (!handle)
662         return;
663
664     ResourceHandleInternal* d = handle->getInternal();
665     ResourceHandleClient* client = handle->client();
666
667     g_input_stream_close_finish(d->m_inputStream, res, 0);
668     cleanupGioOperation(d);
669     client->didFinishLoading(handle);
670 }
671
672 static void readCallback(GObject* source, GAsyncResult* res, gpointer)
673 {
674     // didReceiveData may cancel the load, which may release the last reference.
675     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
676     if (!handle)
677         return;
678
679     ResourceHandleInternal* d = handle->getInternal();
680     ResourceHandleClient* client = handle->client();
681
682     if (d->m_cancelled || !client) {
683         cleanupGioOperation(d);
684         return;
685     }
686
687     GError *error = 0;
688
689     gssize bytesRead = g_input_stream_read_finish(d->m_inputStream, res, &error);
690     if (error) {
691         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
692         g_error_free(error);
693         cleanupGioOperation(d);
694         client->didFail(handle.get(), resourceError);
695         return;
696     }
697
698     if (!bytesRead) {
699         g_input_stream_close_async(d->m_inputStream, G_PRIORITY_DEFAULT,
700                                    0, closeCallback, 0);
701         return;
702     }
703
704     d->m_total += bytesRead;
705     client->didReceiveData(handle.get(), d->m_buffer, bytesRead, d->m_total);
706
707     if (d->m_cancelled) {
708         cleanupGioOperation(d);
709         return;
710     }
711
712     g_input_stream_read_async(d->m_inputStream, d->m_buffer, d->m_bufferSize,
713                               G_PRIORITY_DEFAULT, d->m_cancellable,
714                               readCallback, 0);
715 }
716
717 static void openCallback(GObject* source, GAsyncResult* res, gpointer)
718 {
719     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
720     if (!handle)
721         return;
722
723     ResourceHandleInternal* d = handle->getInternal();
724     ResourceHandleClient* client = handle->client();
725
726     if (d->m_cancelled || !client) {
727         cleanupGioOperation(d);
728         return;
729     }
730
731     GError *error = 0;
732     GFileInputStream* in = g_file_read_finish(G_FILE(source), res, &error);
733     if (error) {
734         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
735         g_error_free(error);
736         cleanupGioOperation(d);
737         client->didFail(handle, resourceError);
738         return;
739     }
740
741     d->m_inputStream = G_INPUT_STREAM(in);
742     d->m_bufferSize = 8192;
743     d->m_buffer = static_cast<char*>(g_malloc(d->m_bufferSize));
744     d->m_total = 0;
745     g_object_set_data(G_OBJECT(d->m_inputStream), "webkit-resource", handle);
746     g_input_stream_read_async(d->m_inputStream, d->m_buffer, d->m_bufferSize,
747                               G_PRIORITY_DEFAULT, d->m_cancellable,
748                               readCallback, 0);
749 }
750
751 static void queryInfoCallback(GObject* source, GAsyncResult* res, gpointer)
752 {
753     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
754     if (!handle)
755         return;
756
757     ResourceHandleInternal* d = handle->getInternal();
758     ResourceHandleClient* client = handle->client();
759
760     if (d->m_cancelled) {
761         cleanupGioOperation(d);
762         return;
763     }
764
765     ResourceResponse response;
766
767     char* uri = g_file_get_uri(d->m_gfile);
768     response.setURL(KURL(KURL(), uri));
769     g_free(uri);
770
771     GError *error = 0;
772     GFileInfo* info = g_file_query_info_finish(d->m_gfile, res, &error);
773
774     if (error) {
775         // FIXME: to be able to handle ftp URIs properly, we must
776         // check if the error is G_IO_ERROR_NOT_MOUNTED, and if so,
777         // call g_file_mount_enclosing_volume() to mount the ftp
778         // server (and then keep track of the fact that we mounted it,
779         // and set a timeout to unmount it later after it's been idle
780         // for a while).
781
782         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
783         g_error_free(error);
784         cleanupGioOperation(d);
785         client->didFail(handle, resourceError);
786         return;
787     }
788
789     if (g_file_info_get_file_type(info) != G_FILE_TYPE_REGULAR) {
790         // FIXME: what if the URI points to a directory? Should we
791         // generate a listing? How? What do other backends do here?
792
793         ResourceError resourceError = networkErrorForFile(d->m_gfile, 0);
794         cleanupGioOperation(d);
795         client->didFail(handle, resourceError);
796         return;
797     }
798
799     response.setMimeType(g_file_info_get_content_type(info));
800     response.setExpectedContentLength(g_file_info_get_size(info));
801
802     GTimeVal tv;
803     g_file_info_get_modification_time(info, &tv);
804     response.setLastModifiedDate(tv.tv_sec);
805
806     client->didReceiveResponse(handle, response);
807
808     g_file_read_async(d->m_gfile, G_PRIORITY_DEFAULT, d->m_cancellable,
809                       openCallback, 0);
810 }
811
812 bool ResourceHandle::startGio(KURL url)
813 {
814     if (request().httpMethod() != "GET" && request().httpMethod() != "POST") {
815         ResourceError error("webkit-network-error", ERROR_BAD_NON_HTTP_METHOD, url.string(), request().httpMethod());
816         d->client()->didFail(this, error);
817         return false;
818     }
819
820     // GIO doesn't know how to handle refs and queries, so remove them
821     // TODO: use KURL.fileSystemPath after KURLGtk and FileSystemGtk are
822     // using GIO internally, and providing URIs instead of file paths
823     url.removeRef();
824     url.setQuery(String());
825     url.setPort(0);
826
827     // we avoid the escaping for local files, because
828     // g_filename_from_uri (used internally by GFile) has problems
829     // decoding strings with arbitrary percent signs
830     if (url.isLocalFile())
831         d->m_gfile = g_file_new_for_path(url.prettyURL().utf8().data() + sizeof("file://") - 1);
832     else
833         d->m_gfile = g_file_new_for_uri(url.string().utf8().data());
834     g_object_set_data(G_OBJECT(d->m_gfile), "webkit-resource", this);
835     d->m_cancellable = g_cancellable_new();
836     g_file_query_info_async(d->m_gfile,
837                             G_FILE_ATTRIBUTE_STANDARD_TYPE ","
838                             G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
839                             G_FILE_ATTRIBUTE_STANDARD_SIZE,
840                             G_FILE_QUERY_INFO_NONE,
841                             G_PRIORITY_DEFAULT, d->m_cancellable,
842                             queryInfoCallback, 0);
843     return true;
844 }
845
846 SoupSession* ResourceHandle::defaultSession()
847 {
848     static SoupSession* session = createSoupSession();;
849
850     return session;
851 }
852
853 }
854