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