2 * Copyright (C) 2008 Alp Toker <alp@atoker.com>
3 * Copyright (C) 2008 Xan Lopez <xan@gnome.org>
4 * Copyright (C) 2008, 2010 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, 2010, 2011 Igalia S.L.
9 * Copyright (C) 2009 John Kjellberg <john.kjellberg@power.alstom.com>
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
28 #include "ResourceHandle.h"
31 #include "ChromeClient.h"
32 #include "CookieJarSoup.h"
33 #include "CachedResourceLoader.h"
34 #include "FileSystem.h"
36 #include "GOwnPtrSoup.h"
37 #include "HTTPParsers.h"
39 #include "MIMETypeRegistry.h"
40 #include "NotImplemented.h"
42 #include "ResourceError.h"
43 #include "ResourceHandleClient.h"
44 #include "ResourceHandleInternal.h"
45 #include "ResourceResponse.h"
46 #include "SharedBuffer.h"
47 #include "TextEncoding.h"
52 #define LIBSOUP_USE_UNSTABLE_REQUEST_API
53 #include <libsoup/soup-request-http.h>
54 #include <libsoup/soup-requester.h>
55 #include <libsoup/soup.h>
57 #include <sys/types.h>
59 #include <wtf/text/CString.h>
63 #define READ_BUFFER_SIZE 8192
65 class WebCoreSynchronousLoader : public ResourceHandleClient {
66 WTF_MAKE_NONCOPYABLE(WebCoreSynchronousLoader);
68 WebCoreSynchronousLoader(ResourceError&, ResourceResponse &, Vector<char>&);
69 ~WebCoreSynchronousLoader();
71 virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
72 virtual void didReceiveData(ResourceHandle*, const char*, int, int encodedDataLength);
73 virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
74 virtual void didFail(ResourceHandle*, const ResourceError&);
79 ResourceError& m_error;
80 ResourceResponse& m_response;
83 GMainLoop* m_mainLoop;
86 WebCoreSynchronousLoader::WebCoreSynchronousLoader(ResourceError& error, ResourceResponse& response, Vector<char>& data)
88 , m_response(response)
92 m_mainLoop = g_main_loop_new(0, false);
95 WebCoreSynchronousLoader::~WebCoreSynchronousLoader()
97 g_main_loop_unref(m_mainLoop);
100 void WebCoreSynchronousLoader::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
102 m_response = response;
105 void WebCoreSynchronousLoader::didReceiveData(ResourceHandle*, const char* data, int length, int)
107 m_data.append(data, length);
110 void WebCoreSynchronousLoader::didFinishLoading(ResourceHandle*, double)
112 g_main_loop_quit(m_mainLoop);
116 void WebCoreSynchronousLoader::didFail(ResourceHandle* handle, const ResourceError& error)
119 didFinishLoading(handle, 0);
122 void WebCoreSynchronousLoader::run()
125 g_main_loop_run(m_mainLoop);
128 static void cleanupSoupRequestOperation(ResourceHandle*, bool isDestroying);
129 static void sendRequestCallback(GObject*, GAsyncResult*, gpointer);
130 static void readCallback(GObject*, GAsyncResult*, gpointer);
131 static void closeCallback(GObject*, GAsyncResult*, gpointer);
132 static bool startNonHTTPRequest(ResourceHandle*, KURL);
134 ResourceHandleInternal::~ResourceHandleInternal()
137 g_object_set_data(G_OBJECT(m_soupRequest.get()), "webkit-resource", 0);
140 ResourceHandle::~ResourceHandle()
142 cleanupSoupRequestOperation(this, true);
145 static void ensureSessionIsInitialized(SoupSession* session)
147 if (g_object_get_data(G_OBJECT(session), "webkit-init"))
150 SoupCookieJar* jar = SOUP_COOKIE_JAR(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
152 soup_session_add_feature(session, SOUP_SESSION_FEATURE(defaultCookieJar()));
154 setDefaultCookieJar(jar);
156 if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
157 SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
158 soup_session_add_feature(session, SOUP_SESSION_FEATURE(logger));
159 g_object_unref(logger);
162 if (!soup_session_get_feature(session, SOUP_TYPE_REQUESTER)) {
163 SoupRequester* requester = soup_requester_new();
164 soup_session_add_feature(session, SOUP_SESSION_FEATURE(requester));
165 g_object_unref(requester);
168 g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
171 void ResourceHandle::prepareForURL(const KURL& url)
173 GOwnPtr<SoupURI> soupURI(soup_uri_new(url.string().utf8().data()));
176 soup_session_prepare_for_uri(ResourceHandle::defaultSession(), soupURI.get());
179 // All other kinds of redirections, except for the *304* status code
180 // (SOUP_STATUS_NOT_MODIFIED) which needs to be fed into WebCore, will be
181 // handled by soup directly.
182 static gboolean statusWillBeHandledBySoup(guint statusCode)
184 if (SOUP_STATUS_IS_TRANSPORT_ERROR(statusCode)
185 || (SOUP_STATUS_IS_REDIRECTION(statusCode) && (statusCode != SOUP_STATUS_NOT_MODIFIED))
186 || (statusCode == SOUP_STATUS_UNAUTHORIZED))
192 // Called each time the message is going to be sent again except the first time.
193 // It's used mostly to let webkit know about redirects.
194 static void restartedCallback(SoupMessage* msg, gpointer data)
196 ResourceHandle* handle = static_cast<ResourceHandle*>(data);
199 ResourceHandleInternal* d = handle->getInternal();
203 GOwnPtr<char> uri(soup_uri_to_string(soup_message_get_uri(msg), false));
204 String location = String::fromUTF8(uri.get());
205 KURL newURL = KURL(handle->firstRequest().url(), location);
207 ResourceRequest request = handle->firstRequest();
208 ResourceResponse response;
209 request.setURL(newURL);
210 request.setHTTPMethod(msg->method);
211 response.updateFromSoupMessage(msg);
213 // Should not set Referer after a redirect from a secure resource to non-secure one.
214 if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https")) {
215 request.clearHTTPReferrer();
216 soup_message_headers_remove(msg->request_headers, "Referer");
220 d->client()->willSendRequest(handle, request, response);
225 // Update the first party in case the base URL changed with the redirect
226 String firstPartyString = request.firstPartyForCookies().string();
227 if (!firstPartyString.isEmpty()) {
228 GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
229 soup_message_set_first_party(d->m_soupMessage.get(), firstParty.get());
233 static void contentSniffedCallback(SoupMessage*, const char*, GHashTable*, gpointer);
235 static void gotHeadersCallback(SoupMessage* msg, gpointer data)
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 // For 302 we accumulate the body too because it could be used by
240 // some servers to redirect with a clunky http-equiv=REFRESH
241 if (statusWillBeHandledBySoup(msg->status_code)) {
242 soup_message_body_set_accumulate(msg->response_body, TRUE);
246 // For all the other responses, we handle each chunk ourselves,
247 // and we don't need msg->response_body to contain all of the data
248 // we got, when we finish downloading.
249 soup_message_body_set_accumulate(msg->response_body, FALSE);
251 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
253 // The content-sniffed callback will handle the response if WebCore
254 // require us to sniff.
255 if (!handle || statusWillBeHandledBySoup(msg->status_code))
258 if (handle->shouldContentSniff()) {
259 // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
260 if (msg->status_code == SOUP_STATUS_NOT_MODIFIED) {
261 soup_message_disable_feature(msg, SOUP_TYPE_CONTENT_SNIFFER);
262 g_signal_handlers_disconnect_by_func(msg, reinterpret_cast<gpointer>(contentSniffedCallback), handle.get());
267 ResourceHandleInternal* d = handle->getInternal();
270 ResourceHandleClient* client = handle->client();
274 ASSERT(d->m_response.isNull());
276 d->m_response.updateFromSoupMessage(msg);
277 client->didReceiveResponse(handle.get(), d->m_response);
280 static void wroteBodyDataCallback(SoupMessage*, SoupBuffer* buffer, gpointer data)
282 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
287 ResourceHandleInternal* internal = handle->getInternal();
288 internal->m_bodyDataSent += buffer->length;
290 if (internal->m_cancelled)
292 ResourceHandleClient* client = handle->client();
296 client->didSendData(handle.get(), internal->m_bodyDataSent, internal->m_bodySize);
299 // This callback will not be called if the content sniffer is disabled in startHTTPRequest.
300 static void contentSniffedCallback(SoupMessage* msg, const char* sniffedType, GHashTable *params, gpointer data)
303 if (statusWillBeHandledBySoup(msg->status_code))
306 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
309 ResourceHandleInternal* d = handle->getInternal();
312 ResourceHandleClient* client = handle->client();
316 ASSERT(d->m_response.isNull());
319 const char* officialType = soup_message_headers_get_one(msg->response_headers, "Content-Type");
320 if (!officialType || strcmp(officialType, sniffedType)) {
321 GString* str = g_string_new(sniffedType);
325 g_hash_table_iter_init(&iter, params);
326 while (g_hash_table_iter_next(&iter, &key, &value)) {
327 g_string_append(str, "; ");
328 soup_header_g_string_append_param(str, static_cast<const char*>(key), static_cast<const char*>(value));
331 d->m_response.setSniffedContentType(str->str);
332 g_string_free(str, TRUE);
336 d->m_response.updateFromSoupMessage(msg);
337 client->didReceiveResponse(handle.get(), d->m_response);
340 static void gotChunkCallback(SoupMessage* msg, SoupBuffer* chunk, gpointer data)
342 if (statusWillBeHandledBySoup(msg->status_code))
345 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
348 ResourceHandleInternal* d = handle->getInternal();
351 ResourceHandleClient* client = handle->client();
355 ASSERT(!d->m_response.isNull());
357 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793
358 // -1 means we do not provide any data about transfer size to inspector so it would use
359 // Content-Length headers or content size to show transfer size.
360 client->didReceiveData(handle.get(), chunk->data, chunk->length, -1);
363 static void finishedCallback(SoupMessage* msg, gpointer data)
365 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
368 handle->getInternal()->m_finished = true;
371 static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroying = false)
373 ResourceHandleInternal* d = handle->getInternal();
375 if (d->m_soupRequest) {
376 g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", 0);
377 d->m_soupRequest.clear();
380 if (d->m_inputStream) {
381 g_object_set_data(G_OBJECT(d->m_inputStream.get()), "webkit-resource", 0);
382 d->m_inputStream.clear();
385 d->m_cancellable.clear();
387 if (d->m_soupMessage) {
388 g_signal_handlers_disconnect_matched(d->m_soupMessage.get(), G_SIGNAL_MATCH_DATA,
390 d->m_soupMessage.clear();
394 g_slice_free1(READ_BUFFER_SIZE, d->m_buffer);
402 static bool soupErrorShouldCauseLoadFailure(GError* error, SoupMessage* message)
404 // Libsoup treats some non-error conditions as errors, including redirects and 304 Not Modified responses.
405 return message && SOUP_STATUS_IS_TRANSPORT_ERROR(message->status_code) || error->domain == G_IO_ERROR;
408 static ResourceError convertSoupErrorToResourceError(GError* error, SoupRequest* request, SoupMessage* message = 0)
413 GOwnPtr<char> uri(soup_uri_to_string(soup_request_get_uri(request), FALSE));
414 if (message && SOUP_STATUS_IS_TRANSPORT_ERROR(message->status_code)) {
415 return ResourceError(g_quark_to_string(SOUP_HTTP_ERROR),
416 static_cast<gint>(message->status_code),
418 String::fromUTF8(message->reason_phrase));
421 // Non-transport errors are handled differently.
422 return ResourceError(g_quark_to_string(G_IO_ERROR),
425 String::fromUTF8(error->message));
428 static void sendRequestCallback(GObject* source, GAsyncResult* res, gpointer userData)
430 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
434 ResourceHandleInternal* d = handle->getInternal();
435 ResourceHandleClient* client = handle->client();
437 if (d->m_gotChunkHandler) {
438 // No need to call gotChunkHandler anymore. Received data will
439 // be reported by readCallback
440 if (g_signal_handler_is_connected(d->m_soupMessage.get(), d->m_gotChunkHandler))
441 g_signal_handler_disconnect(d->m_soupMessage.get(), d->m_gotChunkHandler);
444 if (d->m_cancelled || !client) {
445 cleanupSoupRequestOperation(handle.get());
449 GOwnPtr<GError> error;
450 GInputStream* in = soup_request_send_finish(d->m_soupRequest.get(), res, &error.outPtr());
452 SoupMessage* soupMessage = d->m_soupMessage.get();
454 if (soupErrorShouldCauseLoadFailure(error.get(), soupMessage)) {
455 client->didFail(handle.get(), convertSoupErrorToResourceError(error.get(), d->m_soupRequest.get(), soupMessage));
456 cleanupSoupRequestOperation(handle.get());
460 if (soupMessage && statusWillBeHandledBySoup(soupMessage->status_code)) {
461 ASSERT(d->m_response.isNull());
463 d->m_response.updateFromSoupMessage(soupMessage);
464 client->didReceiveResponse(handle.get(), d->m_response);
466 // WebCore might have cancelled the job in the while. We
467 // must check for response_body->length and not
468 // response_body->data as libsoup always creates the
469 // SoupBuffer for the body even if the length is 0
470 if (!d->m_cancelled && soupMessage->response_body->length)
471 client->didReceiveData(handle.get(), soupMessage->response_body->data,
472 soupMessage->response_body->length, soupMessage->response_body->length);
475 // didReceiveData above might have canceled this operation. If not, inform the client we've finished loading.
476 if (!d->m_cancelled && client)
477 client->didFinishLoading(handle.get(), 0);
479 cleanupSoupRequestOperation(handle.get());
483 if (d->m_cancelled) {
484 cleanupSoupRequestOperation(handle.get());
488 d->m_inputStream = adoptGRef(in);
489 d->m_buffer = static_cast<char*>(g_slice_alloc0(READ_BUFFER_SIZE));
491 // readCallback needs it
492 g_object_set_data(G_OBJECT(d->m_inputStream.get()), "webkit-resource", handle.get());
494 // If not using SoupMessage we need to call didReceiveResponse now.
495 // (This will change later when SoupRequest supports content sniffing.)
496 if (!d->m_soupMessage) {
497 d->m_response.setURL(handle->firstRequest().url());
498 const gchar* contentType = soup_request_get_content_type(d->m_soupRequest.get());
499 d->m_response.setMimeType(extractMIMETypeFromMediaType(contentType));
500 d->m_response.setTextEncodingName(extractCharsetFromMediaType(contentType));
501 d->m_response.setExpectedContentLength(soup_request_get_content_length(d->m_soupRequest.get()));
502 client->didReceiveResponse(handle.get(), d->m_response);
504 if (d->m_cancelled) {
505 cleanupSoupRequestOperation(handle.get());
510 if (d->m_defersLoading)
511 soup_session_pause_message(handle->defaultSession(), d->m_soupMessage.get());
513 g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
514 G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, 0);
517 static bool addFormElementsToSoupMessage(SoupMessage* message, const char* contentType, FormData* httpBody, unsigned long& totalBodySize)
519 size_t numElements = httpBody->elements().size();
520 if (numElements < 2) { // No file upload is the most common case.
522 httpBody->flatten(body);
523 totalBodySize = body.size();
524 soup_message_set_request(message, contentType, SOUP_MEMORY_COPY, body.data(), body.size());
528 // We have more than one element to upload, and some may be large files,
529 // which we will want to mmap instead of copying into memory
530 soup_message_body_set_accumulate(message->request_body, FALSE);
531 for (size_t i = 0; i < numElements; i++) {
532 const FormDataElement& element = httpBody->elements()[i];
534 if (element.m_type == FormDataElement::data) {
535 totalBodySize += element.m_data.size();
536 soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
537 element.m_data.data(), element.m_data.size());
541 // This technique is inspired by libsoup's simple-httpd test.
542 GOwnPtr<GError> error;
543 CString fileName = fileSystemRepresentation(element.m_filename);
544 GMappedFile* fileMapping = g_mapped_file_new(fileName.data(), false, &error.outPtr());
548 gsize mappedFileSize = g_mapped_file_get_length(fileMapping);
549 totalBodySize += mappedFileSize;
550 SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping),
551 mappedFileSize, fileMapping,
552 reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
553 soup_message_body_append_buffer(message->request_body, soupBuffer);
554 soup_buffer_free(soupBuffer);
560 static bool startHTTPRequest(ResourceHandle* handle)
564 SoupSession* session = handle->defaultSession();
565 ensureSessionIsInitialized(session);
566 SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(session, SOUP_TYPE_REQUESTER));
568 ResourceHandleInternal* d = handle->getInternal();
570 ResourceRequest request(handle->firstRequest());
571 KURL url(request.url());
572 url.removeFragmentIdentifier();
575 d->m_finished = false;
577 GOwnPtr<GError> error;
578 d->m_soupRequest = adoptGRef(soup_requester_request(requester, url.string().utf8().data(), &error.outPtr()));
580 d->m_soupRequest = 0;
584 g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", handle);
586 d->m_soupMessage = adoptGRef(soup_request_http_get_message(SOUP_REQUEST_HTTP(d->m_soupRequest.get())));
587 if (!d->m_soupMessage)
590 SoupMessage* soupMessage = d->m_soupMessage.get();
591 request.updateSoupMessage(soupMessage);
593 if (!handle->shouldContentSniff())
594 soup_message_disable_feature(soupMessage, SOUP_TYPE_CONTENT_SNIFFER);
596 g_signal_connect(soupMessage, "content-sniffed", G_CALLBACK(contentSniffedCallback), handle);
598 g_signal_connect(soupMessage, "restarted", G_CALLBACK(restartedCallback), handle);
599 g_signal_connect(soupMessage, "got-headers", G_CALLBACK(gotHeadersCallback), handle);
600 g_signal_connect(soupMessage, "wrote-body-data", G_CALLBACK(wroteBodyDataCallback), handle);
601 d->m_gotChunkHandler = g_signal_connect(soupMessage, "got-chunk", G_CALLBACK(gotChunkCallback), handle);
602 d->m_finishedHandler = g_signal_connect(soupMessage, "finished", G_CALLBACK(finishedCallback), handle);
604 String firstPartyString = request.firstPartyForCookies().string();
605 if (!firstPartyString.isEmpty()) {
606 GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
607 soup_message_set_first_party(soupMessage, firstParty.get());
610 FormData* httpBody = d->m_firstRequest.httpBody();
611 CString contentType = d->m_firstRequest.httpContentType().utf8().data();
612 if (httpBody && !httpBody->isEmpty()
613 && !addFormElementsToSoupMessage(soupMessage, contentType.data(), httpBody, d->m_bodySize)) {
614 // We failed to prepare the body data, so just fail this load.
615 g_signal_handlers_disconnect_matched(soupMessage, G_SIGNAL_MATCH_DATA, 0, 0, 0, 0, handle);
616 d->m_soupMessage.clear();
620 // balanced by a deref() in cleanupSoupRequestOperation, which should always run
623 // Make sure we have an Accept header for subresources; some sites
624 // want this to serve some of their subresources
625 if (!soup_message_headers_get_one(soupMessage->request_headers, "Accept"))
626 soup_message_headers_append(soupMessage->request_headers, "Accept", "*/*");
628 // Send the request only if it's not been explicitely deferred.
629 if (!d->m_defersLoading) {
630 d->m_cancellable = adoptGRef(g_cancellable_new());
631 soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
637 bool ResourceHandle::start(NetworkingContext* context)
639 ASSERT(!d->m_soupMessage);
641 // The frame could be null if the ResourceHandle is not associated to any
642 // Frame, e.g. if we are downloading a file.
643 // If the frame is not null but the page is null this must be an attempted
644 // load from an unload handler, so let's just block it.
645 // If both the frame and the page are not null the context is valid.
646 if (context && !context->isValid())
649 if (!(d->m_user.isEmpty() || d->m_pass.isEmpty())) {
650 // If credentials were specified for this request, add them to the url,
651 // so that they will be passed to NetworkRequest.
652 KURL urlWithCredentials(firstRequest().url());
653 urlWithCredentials.setUser(d->m_user);
654 urlWithCredentials.setPass(d->m_pass);
655 d->m_firstRequest.setURL(urlWithCredentials);
658 KURL url = firstRequest().url();
659 String urlString = url.string();
660 String protocol = url.protocol();
662 // Used to set the authentication dialog toplevel; may be NULL
663 d->m_context = context;
665 if (equalIgnoringCase(protocol, "http") || equalIgnoringCase(protocol, "https")) {
666 if (startHTTPRequest(this))
670 if (startNonHTTPRequest(this, url))
673 // Error must not be reported immediately
674 this->scheduleFailure(InvalidURLFailure);
679 void ResourceHandle::cancel()
681 d->m_cancelled = true;
682 if (d->m_soupMessage)
683 soup_session_cancel_message(defaultSession(), d->m_soupMessage.get(), SOUP_STATUS_CANCELLED);
684 else if (d->m_cancellable)
685 g_cancellable_cancel(d->m_cancellable.get());
688 void ResourceHandle::platformSetDefersLoading(bool defersLoading)
690 // Initial implementation of this method was required for bug #44157.
695 if (!defersLoading && !d->m_cancellable && d->m_soupRequest.get()) {
696 d->m_cancellable = adoptGRef(g_cancellable_new());
697 soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
701 // Only supported for http(s) transfers. Something similar would
702 // probably be needed for data transfers done with GIO.
703 if (!d->m_soupMessage)
706 // Avoid any operation on not yet started messages and completed messages.
707 SoupMessage* soupMessage = d->m_soupMessage.get();
708 if (d->m_finished || soupMessage->status_code == SOUP_STATUS_NONE)
712 soup_session_pause_message(defaultSession(), soupMessage);
714 soup_session_unpause_message(defaultSession(), soupMessage);
717 bool ResourceHandle::loadsBlocked()
722 bool ResourceHandle::willLoadFromCache(ResourceRequest&, Frame*)
724 // Not having this function means that we'll ask the user about re-posting a form
725 // even when we go back to a page that's still in the cache.
730 void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
732 WebCoreSynchronousLoader syncLoader(error, response, data);
733 RefPtr<ResourceHandle> handle = create(context, request, &syncLoader, false /*defersLoading*/, false /*shouldContentSniff*/);
737 // If the request has already failed, do not run the main loop, or else we'll block indefinitely.
738 if (handle->d->m_scheduledFailureType != NoFailure)
744 static void closeCallback(GObject* source, GAsyncResult* res, gpointer)
746 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
750 ResourceHandleInternal* d = handle->getInternal();
751 g_input_stream_close_finish(d->m_inputStream.get(), res, 0);
752 cleanupSoupRequestOperation(handle.get());
755 static void readCallback(GObject* source, GAsyncResult* asyncResult, gpointer data)
757 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(source, "webkit-resource"));
761 bool convertToUTF16 = static_cast<bool>(data);
762 ResourceHandleInternal* d = handle->getInternal();
763 ResourceHandleClient* client = handle->client();
765 if (d->m_cancelled || !client) {
766 cleanupSoupRequestOperation(handle.get());
770 GOwnPtr<GError> error;
771 gssize bytesRead = g_input_stream_read_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
773 client->didFail(handle.get(), convertSoupErrorToResourceError(error.get(), d->m_soupRequest.get()));
774 cleanupSoupRequestOperation(handle.get());
779 // We inform WebCore of load completion now instead of waiting for the input
780 // stream to close because the input stream is closed asynchronously.
781 client->didFinishLoading(handle.get(), 0);
782 g_input_stream_close_async(d->m_inputStream.get(), G_PRIORITY_DEFAULT, 0, closeCallback, 0);
786 // It's mandatory to have sent a response before sending data
787 ASSERT(!d->m_response.isNull());
789 if (G_LIKELY(!convertToUTF16))
790 client->didReceiveData(handle.get(), d->m_buffer, bytesRead, bytesRead);
792 // We have to convert it to UTF-16 due to limitations in KURL
793 String data = String::fromUTF8(d->m_buffer, bytesRead);
794 client->didReceiveData(handle.get(), reinterpret_cast<const char*>(data.characters()), data.length() * sizeof(UChar), bytesRead);
797 // didReceiveData may cancel the load, which may release the last reference.
798 if (d->m_cancelled || !client) {
799 cleanupSoupRequestOperation(handle.get());
803 g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE, G_PRIORITY_DEFAULT,
804 d->m_cancellable.get(), readCallback, data);
807 static bool startNonHTTPRequest(ResourceHandle* handle, KURL url)
811 if (handle->firstRequest().httpMethod() != "GET" && handle->firstRequest().httpMethod() != "POST")
814 SoupSession* session = handle->defaultSession();
815 ensureSessionIsInitialized(session);
816 SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(session, SOUP_TYPE_REQUESTER));
817 ResourceHandleInternal* d = handle->getInternal();
819 CString urlStr = url.string().utf8();
821 GOwnPtr<GError> error;
822 d->m_soupRequest = adoptGRef(soup_requester_request(requester, urlStr.data(), &error.outPtr()));
824 d->m_soupRequest = 0;
828 g_object_set_data(G_OBJECT(d->m_soupRequest.get()), "webkit-resource", handle);
830 // balanced by a deref() in cleanupSoupRequestOperation, which should always run
833 d->m_cancellable = adoptGRef(g_cancellable_new());
834 soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, 0);
839 SoupSession* ResourceHandle::defaultSession()
841 static SoupSession* session = 0;
842 // Values taken from http://www.browserscope.org/ following
843 // the rule "Do What Every Other Modern Browser Is Doing". They seem
844 // to significantly improve page loading time compared to soup's
846 static const int maxConnections = 35;
847 static const int maxConnectionsPerHost = 6;
850 session = soup_session_async_new();
851 g_object_set(session,
852 SOUP_SESSION_MAX_CONNS, maxConnections,
853 SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,