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