3c480523e3d3a9013fb96cb84375b4099cfbe01c
[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  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #include "config.h"
25 #include "ResourceHandle.h"
26
27 #include "Base64.h"
28 #include "CookieJarSoup.h"
29 #include "CString.h"
30 #include "DocLoader.h"
31 #include "Frame.h"
32 #include "HTTPParsers.h"
33 #include "MIMETypeRegistry.h"
34 #include "NotImplemented.h"
35 #include "ResourceError.h"
36 #include "ResourceHandleClient.h"
37 #include "ResourceHandleInternal.h"
38 #include "ResourceResponse.h"
39 #include "TextEncoding.h"
40
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <gio/gio.h>
44 #include <libsoup/soup.h>
45 #include <libsoup/soup-message.h>
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <unistd.h>
49
50 #if PLATFORM(GTK)
51     #if GLIB_CHECK_VERSION(2,12,0)
52         #define USE_GLIB_BASE64
53     #endif
54 #endif
55
56 namespace WebCore {
57
58 static SoupSession* session = 0;
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(NULL, 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 = NULL;
169     const char* value = NULL;
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->setSuggestedFilename(filenameFromHTTPContentDisposition(response->httpHeaderField("Content-Disposition")));
183 }
184
185 // Called each time the message is going to be sent again except the first time.
186 // It's used mostly to let webkit know about redirects.
187 static void restartedCallback(SoupMessage* msg, gpointer data)
188 {
189     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
190     if (!handle)
191         return;
192     ResourceHandleInternal* d = handle->getInternal();
193     if (d->m_cancelled)
194         return;
195
196     char* uri = soup_uri_to_string(soup_message_get_uri(msg), FALSE);
197     String location = String(uri);
198     g_free(uri);
199     KURL newURL = KURL(handle->request().url(), location);
200
201     ResourceRequest request = handle->request();
202     ResourceResponse response;
203     request.setURL(newURL);
204     fillResponseFromMessage(msg, &response);
205     if (d->client())
206         d->client()->willSendRequest(handle, request, response);
207
208     d->m_request.setURL(newURL);
209 }
210
211 static void gotHeadersCallback(SoupMessage* msg, gpointer data)
212 {
213     if (!SOUP_STATUS_IS_SUCCESSFUL(msg->status_code))
214         return;
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     ResourceHandleClient* client = handle->client();
223     if (!client)
224         return;
225
226     fillResponseFromMessage(msg, &d->m_response);
227     client->didReceiveResponse(handle, d->m_response);
228     soup_message_set_flags(msg, SOUP_MESSAGE_OVERWRITE_CHUNKS);
229 }
230
231 static void gotChunkCallback(SoupMessage* msg, SoupBuffer* chunk, gpointer data)
232 {
233     if (!SOUP_STATUS_IS_SUCCESSFUL(msg->status_code))
234         return;
235
236     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
237     if (!handle)
238         return;
239     ResourceHandleInternal* d = handle->getInternal();
240     if (d->m_cancelled)
241         return;
242     ResourceHandleClient* client = handle->client();
243     if (!client)
244         return;
245
246     client->didReceiveData(handle, chunk->data, chunk->length, false);
247 }
248
249 // Called at the end of the message, with all the necessary about the last informations.
250 // Doesn't get called for redirects.
251 static void finishedCallback(SoupSession *session, SoupMessage* msg, gpointer data)
252 {
253     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
254     // TODO: maybe we should run this code even if there's no client?
255     if (!handle)
256         return;
257
258     ResourceHandleInternal* d = handle->getInternal();
259
260     ResourceHandleClient* client = handle->client();
261     if (!client)
262         return;
263
264     if (d->m_cancelled)
265         return;
266
267     if (SOUP_STATUS_IS_TRANSPORT_ERROR(msg->status_code)) {
268         char* uri = soup_uri_to_string(soup_message_get_uri(msg), FALSE);
269         ResourceError error("webkit-network-error", ERROR_TRANSPORT, uri, String::fromUTF8(msg->reason_phrase));
270         g_free(uri);
271         client->didFail(handle, error);
272         return;
273     } else if (!SOUP_STATUS_IS_SUCCESSFUL(msg->status_code)) {
274         fillResponseFromMessage(msg, &d->m_response);
275         client->didReceiveResponse(handle, d->m_response);
276
277         // WebCore might have cancelled the job in the while
278         if (d->m_cancelled)
279             return;
280
281         if (msg->response_body->data)
282             client->didReceiveData(handle, msg->response_body->data, msg->response_body->length, true);
283     }
284
285     client->didFinishLoading(handle);
286 }
287
288 // parseDataUrl() is taken from the CURL http backend.
289 static gboolean parseDataUrl(gpointer callback_data)
290 {
291     ResourceHandle* handle = static_cast<ResourceHandle*>(callback_data);
292     ResourceHandleClient* client = handle->client();
293
294     handle->getInternal()->m_idleHandler = 0;
295
296     ASSERT(client);
297     if (!client)
298         return FALSE;
299
300     String url = handle->request().url().string();
301     ASSERT(url.startsWith("data:", false));
302
303     int index = url.find(',');
304     if (index == -1) {
305         client->cannotShowURL(handle);
306         return FALSE;
307     }
308
309     String mediaType = url.substring(5, index - 5);
310     String data = url.substring(index + 1);
311
312     bool base64 = mediaType.endsWith(";base64", false);
313     if (base64)
314         mediaType = mediaType.left(mediaType.length() - 7);
315
316     if (mediaType.isEmpty())
317         mediaType = "text/plain;charset=US-ASCII";
318
319     String mimeType = extractMIMETypeFromMediaType(mediaType);
320     String charset = extractCharsetFromMediaType(mediaType);
321
322     ResourceResponse response;
323     response.setMimeType(mimeType);
324
325     if (base64) {
326         data = decodeURLEscapeSequences(data);
327         response.setTextEncodingName(charset);
328         client->didReceiveResponse(handle, response);
329
330         // Use the GLib Base64 if available, since WebCore's decoder isn't
331         // general-purpose and fails on Acid3 test 97 (whitespace).
332 #ifdef USE_GLIB_BASE64
333         size_t outLength = 0;
334         char* outData = 0;
335         outData = reinterpret_cast<char*>(g_base64_decode(data.utf8().data(), &outLength));
336         if (outData && outLength > 0)
337             client->didReceiveData(handle, outData, outLength, 0);
338         g_free(outData);
339 #else
340         Vector<char> out;
341         if (base64Decode(data.latin1().data(), data.latin1().length(), out) && out.size() > 0)
342             client->didReceiveData(handle, out.data(), out.size(), 0);
343 #endif
344     } else {
345         // We have to convert to UTF-16 early due to limitations in KURL
346         data = decodeURLEscapeSequences(data, TextEncoding(charset));
347         response.setTextEncodingName("UTF-16");
348         client->didReceiveResponse(handle, response);
349         if (data.length() > 0)
350             client->didReceiveData(handle, reinterpret_cast<const char*>(data.characters()), data.length() * sizeof(UChar), 0);
351     }
352
353     client->didFinishLoading(handle);
354
355     return FALSE;
356 }
357
358 bool ResourceHandle::startData(String urlString)
359 {
360     ResourceHandleInternal* d = this->getInternal();
361
362     // If parseDataUrl is called synchronously the job is not yet effectively started
363     // and webkit won't never know that the data has been parsed even didFinishLoading is called.
364     d->m_idleHandler = g_idle_add(parseDataUrl, this);
365     return true;
366 }
367
368 bool ResourceHandle::startHttp(String urlString)
369 {
370     if (!session) {
371         session = soup_session_async_new();
372
373         soup_session_add_feature(session, SOUP_SESSION_FEATURE(getCookieJar()));
374
375         const char* soup_debug = g_getenv("WEBKIT_SOUP_LOGGING");
376         if (soup_debug) {
377             int soup_debug_level = atoi(soup_debug);
378
379             SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(soup_debug_level), -1);
380             soup_logger_attach(logger, session);
381             g_object_unref(logger);
382         }
383     }
384
385     SoupMessage* msg;
386     msg = soup_message_new(request().httpMethod().utf8().data(), urlString.utf8().data());
387     g_signal_connect(msg, "restarted", G_CALLBACK(restartedCallback), this);
388
389     g_signal_connect(msg, "got-headers", G_CALLBACK(gotHeadersCallback), this);
390     g_signal_connect(msg, "got-chunk", G_CALLBACK(gotChunkCallback), this);
391
392     HTTPHeaderMap customHeaders = d->m_request.httpHeaderFields();
393     if (!customHeaders.isEmpty()) {
394         HTTPHeaderMap::const_iterator end = customHeaders.end();
395         for (HTTPHeaderMap::const_iterator it = customHeaders.begin(); it != end; ++it)
396             soup_message_headers_append(msg->request_headers, it->first.string().utf8().data(), it->second.utf8().data());
397     }
398
399     FormData* httpBody = d->m_request.httpBody();
400     if (httpBody && !httpBody->isEmpty()) {
401         size_t numElements = httpBody->elements().size();
402
403         // handle the most common case (i.e. no file upload)
404         if (numElements < 2) {
405             Vector<char> body;
406             httpBody->flatten(body);
407             soup_message_set_request(msg, d->m_request.httpContentType().utf8().data(),
408                                      SOUP_MEMORY_COPY, body.data(), body.size());
409         } else {
410             /*
411              * we have more than one element to upload, and some may
412              * be (big) files, which we will want to mmap instead of
413              * copying into memory; TODO: support upload of non-local
414              * (think sftp://) files by using GIO?
415              *
416              * TODO: we can avoid appending all the buffers to the
417              * request_body variable with the following call, but we
418              * need to depend on libsoup > 2.25.4
419              *
420              * soup_message_body_set_accumulate(msg->request_body, FALSE);
421              */
422             for (size_t i = 0; i < numElements; i++) {
423                 const FormDataElement& element = httpBody->elements()[i];
424
425                 if (element.m_type == FormDataElement::data)
426                     soup_message_body_append(msg->request_body, SOUP_MEMORY_TEMPORARY, element.m_data.data(), element.m_data.size());
427                 else {
428                     /*
429                      * mapping for uploaded files code inspired by technique used in
430                      * libsoup's simple-httpd test
431                      */
432                     /* FIXME: Since Linux 2.6.23 we should also use O_CLOEXEC */
433                     int fd = open(element.m_filename.utf8().data(), O_RDONLY);
434
435                     if (fd == -1) {
436                         ResourceError error("webkit-network-error", ERROR_UNABLE_TO_OPEN_FILE, urlString, strerror(errno));
437                         d->client()->didFail(this, error);
438                         g_object_unref(msg);
439                         return false;
440                     }
441
442                     struct stat statBuf;
443                     fstat(fd, &statBuf);
444
445                     FileMapping* fileMapping = g_slice_new(FileMapping);
446
447                     fileMapping->ptr = mmap(NULL, statBuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
448                     if (fileMapping->ptr == MAP_FAILED) {
449                         ResourceError error("webkit-network-error", ERROR_UNABLE_TO_OPEN_FILE, urlString, strerror(errno));
450                         d->client()->didFail(this, error);
451                         freeFileMapping(fileMapping);
452                         g_object_unref(msg);
453                         close(fd);
454                         return false;
455                     }
456                     fileMapping->length = statBuf.st_size;
457
458                     close(fd);
459
460                     SoupBuffer* soupBuffer = soup_buffer_new_with_owner(fileMapping->ptr, fileMapping->length, fileMapping, freeFileMapping);
461                     soup_message_body_append_buffer(msg->request_body, soupBuffer);
462                     soup_buffer_free(soupBuffer);
463                 }
464             }
465         }
466     }
467
468     d->m_msg = static_cast<SoupMessage*>(g_object_ref(msg));
469     soup_session_queue_message(session, d->m_msg, finishedCallback, this);
470
471     return true;
472 }
473
474 bool ResourceHandle::start(Frame* frame)
475 {
476     ASSERT(!d->m_msg);
477
478     // If we are no longer attached to a Page, this must be an attempted load from an
479     // onUnload handler, so let's just block it.
480     if (!frame->page())
481         return false;
482
483     KURL url = request().url();
484     String urlString = url.string();
485     String protocol = url.protocol();
486
487     if (equalIgnoringCase(protocol, "data"))
488         return startData(urlString);
489     else if ((equalIgnoringCase(protocol, "http") || equalIgnoringCase(protocol, "https")) && SOUP_URI_VALID_FOR_HTTP(soup_uri_new(urlString.utf8().data())))
490         return startHttp(urlString);
491     else if (equalIgnoringCase(protocol, "file") || equalIgnoringCase(protocol, "ftp") || equalIgnoringCase(protocol, "ftps"))
492         // FIXME: should we be doing any other protocols here?
493         return startGio(url);
494     else {
495         // If we don't call didFail the job is not complete for webkit even false is returned.
496         if (d->client()) {
497             ResourceError error("webkit-network-error", ERROR_UNKNOWN_PROTOCOL, urlString, protocol);
498             d->client()->didFail(this, error);
499         }
500         return false;
501     }
502 }
503
504 void ResourceHandle::cancel()
505 {
506     d->m_cancelled = true;
507     if (d->m_msg) {
508         soup_session_cancel_message(session, d->m_msg, SOUP_STATUS_CANCELLED);
509         // For re-entrancy troubles we call didFinishLoading when the message hasn't been handled yet.
510         if (client())
511             client()->didFinishLoading(this);
512     } else if (d->m_cancellable) {
513         g_cancellable_cancel(d->m_cancellable);
514         if (client())
515             client()->didFinishLoading(this);
516     }
517 }
518
519 PassRefPtr<SharedBuffer> ResourceHandle::bufferedData()
520 {
521     ASSERT_NOT_REACHED();
522     return 0;
523 }
524
525 bool ResourceHandle::supportsBufferedData()
526 {
527     return false;
528 }
529
530 void ResourceHandle::setDefersLoading(bool defers)
531 {
532     d->m_defersLoading = defers;
533     notImplemented();
534 }
535
536 bool ResourceHandle::loadsBlocked()
537 {
538     return false;
539 }
540
541 bool ResourceHandle::willLoadFromCache(ResourceRequest&)
542 {
543     // Not having this function means that we'll ask the user about re-posting a form
544     // even when we go back to a page that's still in the cache.
545     notImplemented();
546     return false;
547 }
548
549 void ResourceHandle::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data, Frame* frame)
550 {
551     WebCoreSynchronousLoader syncLoader(error, response, data);
552     ResourceHandle handle(request, &syncLoader, true, false, true);
553
554     handle.start(frame);
555     syncLoader.run();
556 }
557
558 // GIO-based loader
559
560 static inline ResourceError networkErrorForFile(GFile* file, GError* error)
561 {
562     // FIXME: Map gio errors to a more detailed error code when we have it in WebKit.
563     gchar* uri = g_file_get_uri(file);
564     ResourceError resourceError("webkit-network-error", ERROR_TRANSPORT, uri, String::fromUTF8(error->message));
565     g_free(uri);
566     return resourceError;
567 }
568
569 static void cleanupGioOperation(ResourceHandleInternal* d)
570 {
571     if (d->m_gfile) {
572         g_object_set_data(G_OBJECT(d->m_gfile), "webkit-resource", 0);
573         g_object_unref(d->m_gfile);
574         d->m_gfile = NULL;
575     }
576     if (d->m_cancellable) {
577         g_object_unref(d->m_cancellable);
578         d->m_cancellable = NULL;
579     }
580     if (d->m_input_stream) {
581         g_object_set_data(G_OBJECT(d->m_input_stream), "webkit-resource", 0);
582         g_object_unref(d->m_input_stream);
583         d->m_input_stream = NULL;
584     }
585     if (d->m_buffer) {
586         g_free(d->m_buffer);
587         d->m_buffer = NULL;
588     }
589 }
590
591 static void closeCallback(GObject* source, GAsyncResult* res, gpointer)
592 {
593     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
594     if (!handle)
595         return;
596
597     ResourceHandleInternal* d = handle->getInternal();
598     ResourceHandleClient* client = handle->client();
599
600     g_input_stream_close_finish(d->m_input_stream, res, NULL);
601     cleanupGioOperation(d);
602     client->didFinishLoading(handle);
603 }
604
605 static void readCallback(GObject* source, GAsyncResult* res, gpointer)
606 {
607     // didReceiveData may cancel the load, which may release the last reference.
608     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
609     if (!handle)
610         return;
611
612     ResourceHandleInternal* d = handle->getInternal();
613     ResourceHandleClient* client = handle->client();
614
615     if (d->m_cancelled || !client) {
616         cleanupGioOperation(d);
617         return;
618     }
619
620     gssize nread;
621     GError *error = 0;
622
623     nread = g_input_stream_read_finish(d->m_input_stream, res, &error);
624     if (error) {
625         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
626         cleanupGioOperation(d);
627         client->didFail(handle.get(), resourceError);
628         return;
629     } else if (!nread) {
630         g_input_stream_close_async(d->m_input_stream, G_PRIORITY_DEFAULT,
631                                    NULL, closeCallback, NULL);
632         return;
633     }
634
635     d->m_total += nread;
636     client->didReceiveData(handle.get(), d->m_buffer, nread, d->m_total);
637
638     if (d->m_cancelled) {
639         cleanupGioOperation(d);
640         return;
641     }
642
643     g_input_stream_read_async(d->m_input_stream, d->m_buffer, d->m_bufsize,
644                               G_PRIORITY_DEFAULT, d->m_cancellable,
645                               readCallback, NULL);
646 }
647
648 static void openCallback(GObject* source, GAsyncResult* res, gpointer)
649 {
650     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
651     if (!handle)
652         return;
653
654     ResourceHandleInternal* d = handle->getInternal();
655     ResourceHandleClient* client = handle->client();
656
657     if (d->m_cancelled || !client) {
658         cleanupGioOperation(d);
659         return;
660     }
661
662     GFileInputStream* in;
663     GError *error = NULL;
664     in = g_file_read_finish(G_FILE(source), res, &error);
665     if (error) {
666         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
667         cleanupGioOperation(d);
668         client->didFail(handle, resourceError);
669         return;
670     }
671
672     d->m_input_stream = G_INPUT_STREAM(in);
673     d->m_bufsize = 8192;
674     d->m_buffer = static_cast<char*>(g_malloc(d->m_bufsize));
675     d->m_total = 0;
676     g_object_set_data(G_OBJECT(d->m_input_stream), "webkit-resource", handle);
677     g_input_stream_read_async(d->m_input_stream, d->m_buffer, d->m_bufsize,
678                               G_PRIORITY_DEFAULT, d->m_cancellable,
679                               readCallback, NULL);
680 }
681
682 static void queryInfoCallback(GObject* source, GAsyncResult* res, gpointer)
683 {
684     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
685     if (!handle)
686         return;
687
688     ResourceHandleInternal* d = handle->getInternal();
689     ResourceHandleClient* client = handle->client();
690
691     if (d->m_cancelled) {
692         cleanupGioOperation(d);
693         return;
694     }
695
696     ResourceResponse response;
697
698     char* uri = g_file_get_uri(d->m_gfile);
699     response.setUrl(KURL(uri));
700     g_free(uri);
701
702     GError *error = NULL;
703     GFileInfo* info = g_file_query_info_finish(d->m_gfile, res, &error);
704
705     if (error) {
706         // FIXME: to be able to handle ftp URIs properly, we must
707         // check if the error is G_IO_ERROR_NOT_MOUNTED, and if so,
708         // call g_file_mount_enclosing_volume() to mount the ftp
709         // server (and then keep track of the fact that we mounted it,
710         // and set a timeout to unmount it later after it's been idle
711         // for a while).
712
713         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
714         cleanupGioOperation(d);
715         client->didFail(handle, resourceError);
716         return;
717     }
718
719     if (g_file_info_get_file_type(info) != G_FILE_TYPE_REGULAR) {
720         // FIXME: what if the URI points to a directory? Should we
721         // generate a listing? How? What do other backends do here?
722
723         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
724         cleanupGioOperation(d);
725         client->didFail(handle, resourceError);
726         return;
727     }
728
729     response.setMimeType(g_file_info_get_content_type(info));
730     response.setExpectedContentLength(g_file_info_get_size(info));
731
732     GTimeVal tv;
733     g_file_info_get_modification_time(info, &tv);
734     response.setLastModifiedDate(tv.tv_sec);
735
736     client->didReceiveResponse(handle, response);
737
738     g_file_read_async(d->m_gfile, G_PRIORITY_DEFAULT, d->m_cancellable,
739                       openCallback, NULL);
740 }
741
742 bool ResourceHandle::startGio(KURL url)
743 {
744     if (request().httpMethod() != "GET" && request().httpMethod() != "POST") {
745         ResourceError error("webkit-network-error", ERROR_BAD_NON_HTTP_METHOD, url.string(), request().httpMethod());
746         d->client()->didFail(this, error);
747         return false;
748     }
749
750     // GIO doesn't know how to handle refs and queries, so remove them
751     // TODO: use KURL.fileSystemPath after KURLGtk and FileSystemGtk are
752     // using GIO internally, and providing URIs instead of file paths
753     url.removeRef();
754     url.setQuery(String());
755     url.setPort(0);
756
757     // we avoid the escaping for local files, because
758     // g_filename_from_uri (used internally by GFile) has problems
759     // decoding strings with arbitrary percent signs
760     if (url.isLocalFile())
761         d->m_gfile = g_file_new_for_path(url.prettyURL().utf8().data() + sizeof("file://") - 1);
762     else
763         d->m_gfile = g_file_new_for_uri(url.string().utf8().data());
764     g_object_set_data(G_OBJECT(d->m_gfile), "webkit-resource", this);
765     d->m_cancellable = g_cancellable_new();
766     g_file_query_info_async(d->m_gfile,
767                             G_FILE_ATTRIBUTE_STANDARD_TYPE ","
768                             G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
769                             G_FILE_ATTRIBUTE_STANDARD_SIZE,
770                             G_FILE_QUERY_INFO_NONE,
771                             G_PRIORITY_DEFAULT, d->m_cancellable,
772                             queryInfoCallback, NULL);
773     return true;
774 }
775
776 }
777