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