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