82ed14241b618701fb8107345d4117f9fbf4bded
[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     else if (d->m_cancellable)
557         g_cancellable_cancel(d->m_cancellable);
558 }
559
560 PassRefPtr<SharedBuffer> ResourceHandle::bufferedData()
561 {
562     ASSERT_NOT_REACHED();
563     return 0;
564 }
565
566 bool ResourceHandle::supportsBufferedData()
567 {
568     return false;
569 }
570
571 void ResourceHandle::setDefersLoading(bool defers)
572 {
573     d->m_defersLoading = defers;
574     notImplemented();
575 }
576
577 bool ResourceHandle::loadsBlocked()
578 {
579     return false;
580 }
581
582 bool ResourceHandle::willLoadFromCache(ResourceRequest&)
583 {
584     // Not having this function means that we'll ask the user about re-posting a form
585     // even when we go back to a page that's still in the cache.
586     notImplemented();
587     return false;
588 }
589
590 void ResourceHandle::loadResourceSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data, Frame* frame)
591 {
592     WebCoreSynchronousLoader syncLoader(error, response, data);
593     ResourceHandle handle(request, &syncLoader, true, false, true);
594
595     handle.start(frame);
596     syncLoader.run();
597 }
598
599 // GIO-based loader
600
601 static inline ResourceError networkErrorForFile(GFile* file, GError* error)
602 {
603     // FIXME: Map gio errors to a more detailed error code when we have it in WebKit.
604     gchar* uri = g_file_get_uri(file);
605     ResourceError resourceError("webkit-network-error", ERROR_TRANSPORT, uri, error ? String::fromUTF8(error->message) : String());
606     g_free(uri);
607     return resourceError;
608 }
609
610 static void cleanupGioOperation(ResourceHandleInternal* d)
611 {
612     if (d->m_gfile) {
613         g_object_set_data(G_OBJECT(d->m_gfile), "webkit-resource", 0);
614         g_object_unref(d->m_gfile);
615         d->m_gfile = 0;
616     }
617
618     if (d->m_cancellable) {
619         g_object_unref(d->m_cancellable);
620         d->m_cancellable = 0;
621     }
622
623     if (d->m_inputStream) {
624         g_object_set_data(G_OBJECT(d->m_inputStream), "webkit-resource", 0);
625         g_object_unref(d->m_inputStream);
626         d->m_inputStream = 0;
627     }
628
629     if (d->m_buffer) {
630         g_free(d->m_buffer);
631         d->m_buffer = 0;
632     }
633 }
634
635 static void closeCallback(GObject* source, GAsyncResult* res, gpointer)
636 {
637     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
638     if (!handle)
639         return;
640
641     ResourceHandleInternal* d = handle->getInternal();
642     ResourceHandleClient* client = handle->client();
643
644     g_input_stream_close_finish(d->m_inputStream, res, 0);
645     cleanupGioOperation(d);
646     client->didFinishLoading(handle);
647 }
648
649 static void readCallback(GObject* source, GAsyncResult* res, gpointer)
650 {
651     // didReceiveData may cancel the load, which may release the last reference.
652     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
653     if (!handle)
654         return;
655
656     ResourceHandleInternal* d = handle->getInternal();
657     ResourceHandleClient* client = handle->client();
658
659     if (d->m_cancelled || !client) {
660         cleanupGioOperation(d);
661         return;
662     }
663
664     GError *error = 0;
665
666     gssize bytesRead = g_input_stream_read_finish(d->m_inputStream, res, &error);
667     if (error) {
668         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
669         g_error_free(error);
670         cleanupGioOperation(d);
671         client->didFail(handle.get(), resourceError);
672         return;
673     }
674
675     if (!bytesRead) {
676         g_input_stream_close_async(d->m_inputStream, G_PRIORITY_DEFAULT,
677                                    0, closeCallback, 0);
678         return;
679     }
680
681     d->m_total += bytesRead;
682     client->didReceiveData(handle.get(), d->m_buffer, bytesRead, d->m_total);
683
684     if (d->m_cancelled) {
685         cleanupGioOperation(d);
686         return;
687     }
688
689     g_input_stream_read_async(d->m_inputStream, d->m_buffer, d->m_bufferSize,
690                               G_PRIORITY_DEFAULT, d->m_cancellable,
691                               readCallback, 0);
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     GError *error = 0;
709     GFileInputStream* in = g_file_read_finish(G_FILE(source), res, &error);
710     if (error) {
711         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
712         g_error_free(error);
713         cleanupGioOperation(d);
714         client->didFail(handle, resourceError);
715         return;
716     }
717
718     d->m_inputStream = G_INPUT_STREAM(in);
719     d->m_bufferSize = 8192;
720     d->m_buffer = static_cast<char*>(g_malloc(d->m_bufferSize));
721     d->m_total = 0;
722     g_object_set_data(G_OBJECT(d->m_inputStream), "webkit-resource", handle);
723     g_input_stream_read_async(d->m_inputStream, d->m_buffer, d->m_bufferSize,
724                               G_PRIORITY_DEFAULT, d->m_cancellable,
725                               readCallback, 0);
726 }
727
728 static void queryInfoCallback(GObject* source, GAsyncResult* res, gpointer)
729 {
730     ResourceHandle* handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
731     if (!handle)
732         return;
733
734     ResourceHandleInternal* d = handle->getInternal();
735     ResourceHandleClient* client = handle->client();
736
737     if (d->m_cancelled) {
738         cleanupGioOperation(d);
739         return;
740     }
741
742     ResourceResponse response;
743
744     char* uri = g_file_get_uri(d->m_gfile);
745     response.setUrl(KURL(uri));
746     g_free(uri);
747
748     GError *error = 0;
749     GFileInfo* info = g_file_query_info_finish(d->m_gfile, res, &error);
750
751     if (error) {
752         // FIXME: to be able to handle ftp URIs properly, we must
753         // check if the error is G_IO_ERROR_NOT_MOUNTED, and if so,
754         // call g_file_mount_enclosing_volume() to mount the ftp
755         // server (and then keep track of the fact that we mounted it,
756         // and set a timeout to unmount it later after it's been idle
757         // for a while).
758
759         ResourceError resourceError = networkErrorForFile(d->m_gfile, error);
760         g_error_free(error);
761         cleanupGioOperation(d);
762         client->didFail(handle, resourceError);
763         return;
764     }
765
766     if (g_file_info_get_file_type(info) != G_FILE_TYPE_REGULAR) {
767         // FIXME: what if the URI points to a directory? Should we
768         // generate a listing? How? What do other backends do here?
769
770         ResourceError resourceError = networkErrorForFile(d->m_gfile, 0);
771         cleanupGioOperation(d);
772         client->didFail(handle, resourceError);
773         return;
774     }
775
776     response.setMimeType(g_file_info_get_content_type(info));
777     response.setExpectedContentLength(g_file_info_get_size(info));
778
779     GTimeVal tv;
780     g_file_info_get_modification_time(info, &tv);
781     response.setLastModifiedDate(tv.tv_sec);
782
783     client->didReceiveResponse(handle, response);
784
785     g_file_read_async(d->m_gfile, G_PRIORITY_DEFAULT, d->m_cancellable,
786                       openCallback, 0);
787 }
788
789 bool ResourceHandle::startGio(KURL url)
790 {
791     if (request().httpMethod() != "GET" && request().httpMethod() != "POST") {
792         ResourceError error("webkit-network-error", ERROR_BAD_NON_HTTP_METHOD, url.string(), request().httpMethod());
793         d->client()->didFail(this, error);
794         return false;
795     }
796
797     // GIO doesn't know how to handle refs and queries, so remove them
798     // TODO: use KURL.fileSystemPath after KURLGtk and FileSystemGtk are
799     // using GIO internally, and providing URIs instead of file paths
800     url.removeRef();
801     url.setQuery(String());
802     url.setPort(0);
803
804     // we avoid the escaping for local files, because
805     // g_filename_from_uri (used internally by GFile) has problems
806     // decoding strings with arbitrary percent signs
807     if (url.isLocalFile())
808         d->m_gfile = g_file_new_for_path(url.prettyURL().utf8().data() + sizeof("file://") - 1);
809     else
810         d->m_gfile = g_file_new_for_uri(url.string().utf8().data());
811     g_object_set_data(G_OBJECT(d->m_gfile), "webkit-resource", this);
812     d->m_cancellable = g_cancellable_new();
813     g_file_query_info_async(d->m_gfile,
814                             G_FILE_ATTRIBUTE_STANDARD_TYPE ","
815                             G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
816                             G_FILE_ATTRIBUTE_STANDARD_SIZE,
817                             G_FILE_QUERY_INFO_NONE,
818                             G_PRIORITY_DEFAULT, d->m_cancellable,
819                             queryInfoCallback, 0);
820     return true;
821 }
822
823 SoupSession* ResourceHandle::defaultSession()
824 {
825     static SoupSession* session = createSoupSession();;
826
827     return session;
828 }
829
830 }
831