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