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