[GLIB] Use GUniquePtr instead of GOwnPtr
[WebKit-https.git] / Source / WebCore / platform / network / soup / ResourceHandleSoup.cpp
index a64a430..7a6776e 100644 (file)
@@ -4,7 +4,7 @@
  * Copyright (C) 2008 Xan Lopez <xan@gnome.org>
  * Copyright (C) 2008, 2010 Collabora Ltd.
  * Copyright (C) 2009 Holger Hans Peter Freyther
- * Copyright (C) 2009 Gustavo Noronha Silva <gns@gnome.org>
+ * Copyright (C) 2009, 2013 Gustavo Noronha Silva <gns@gnome.org>
  * Copyright (C) 2009 Christian Dywan <christian@imendio.com>
  * Copyright (C) 2009, 2010, 2011, 2012 Igalia S.L.
  * Copyright (C) 2009 John Kjellberg <john.kjellberg@power.alstom.com>
 #include "config.h"
 #include "ResourceHandle.h"
 
-#include "CachedResourceLoader.h"
-#include "ChromeClient.h"
 #include "CookieJarSoup.h"
 #include "CredentialStorage.h"
 #include "FileSystem.h"
-#include "Frame.h"
 #include "GOwnPtrSoup.h"
 #include "HTTPParsers.h"
 #include "LocalizedStrings.h"
-#include "Logging.h"
 #include "MIMETypeRegistry.h"
 #include "NetworkingContext.h"
 #include "NotImplemented.h"
-#include "Page.h"
 #include "ResourceError.h"
 #include "ResourceHandleClient.h"
 #include "ResourceHandleInternal.h"
 #include "ResourceResponse.h"
 #include "SharedBuffer.h"
+#include "SoupNetworkSession.h"
 #include "SoupURIUtils.h"
 #include "TextEncoding.h"
 #include <errno.h>
 #include <fcntl.h>
 #include <gio/gio.h>
 #include <glib.h>
-#define LIBSOUP_USE_UNSTABLE_REQUEST_API
-#include <libsoup/soup-multipart-input-stream.h>
-#include <libsoup/soup-request-http.h>
-#include <libsoup/soup-requester.h>
 #include <libsoup/soup.h>
 #include <sys/stat.h>
 #include <sys/types.h>
 #include <unistd.h>
+#include <wtf/CurrentTime.h>
 #include <wtf/SHA1.h>
+#include <wtf/gobject/GOwnPtr.h>
 #include <wtf/gobject/GRefPtr.h>
 #include <wtf/text/Base64.h>
 #include <wtf/text/CString.h>
 
 namespace WebCore {
 
-#define READ_BUFFER_SIZE 8192
-
-inline static void soupLogPrinter(SoupLogger*, SoupLoggerLogLevel, char direction, const char* data, gpointer)
-{
-#if LOG_DISABLED
-    UNUSED_PARAM(direction);
-    UNUSED_PARAM(data);
-#endif
-    LOG(Network, "%c %s", direction, data);
-}
-
 static bool loadingSynchronousRequest = false;
+static const size_t gDefaultReadBufferSize = 8192;
 
 class WebCoreSynchronousLoader : public ResourceHandleClient {
     WTF_MAKE_NONCOPYABLE(WebCoreSynchronousLoader);
@@ -117,7 +101,12 @@ public:
     ~WebCoreSynchronousLoader()
     {
         adjustMaxConnections(-1);
-        g_main_context_pop_thread_default(g_main_context_get_thread_default());
+
+        GMainContext* context = g_main_context_get_thread_default();
+        while (g_main_context_pending(context))
+            g_main_context_iteration(context, FALSE);
+
+        g_main_context_pop_thread_default(context);
         loadingSynchronousRequest = false;
     }
 
@@ -147,9 +136,20 @@ public:
         m_response = response;
     }
 
-    virtual void didReceiveData(ResourceHandle*, const char* data, int length, int)
+    virtual void didReceiveData(ResourceHandle*, const char* /* data */, unsigned /* length */, int)
     {
-        m_data.append(data, length);
+        ASSERT_NOT_REACHED();
+    }
+
+    virtual void didReceiveBuffer(ResourceHandle*, PassRefPtr<SharedBuffer> buffer, int /* encodedLength */)
+    {
+        // This pattern is suggested by SharedBuffer.h.
+        const char* segment;
+        unsigned position = 0;
+        while (unsigned length = buffer->getSomeData(segment, position)) {
+            m_data.append(segment, length);
+            position += length;
+        }
     }
 
     virtual void didFinishLoading(ResourceHandle*, double)
@@ -203,20 +203,18 @@ public:
 private:
     static String computeCertificateHash(GTlsCertificate* certificate)
     {
-        GByteArray* data = 0;
-        g_object_get(G_OBJECT(certificate), "certificate", &data, NULL);
-        if (!data)
+        GRefPtr<GByteArray> certificateData;
+        g_object_get(G_OBJECT(certificate), "certificate", &certificateData.outPtr(), NULL);
+        if (!certificateData)
             return String();
 
-        static const size_t sha1HashSize = 20;
-        GRefPtr<GByteArray> certificateData = adoptGRef(data);
         SHA1 sha1;
         sha1.addBytes(certificateData->data, certificateData->len);
 
-        Vector<uint8_t, sha1HashSize> digest;
+        SHA1::Digest digest;
         sha1.computeHash(digest);
 
-        return base64Encode(reinterpret_cast<const char*>(digest.data()), sha1HashSize);
+        return base64Encode(reinterpret_cast<const char*>(digest.data()), SHA1::hashSize);
     }
 
     HashSet<String> m_certificates;
@@ -226,11 +224,11 @@ static bool createSoupRequestAndMessageForHandle(ResourceHandle*, const Resource
 static void cleanupSoupRequestOperation(ResourceHandle*, bool isDestroying = false);
 static void sendRequestCallback(GObject*, GAsyncResult*, gpointer);
 static void readCallback(GObject*, GAsyncResult*, gpointer);
-static void closeCallback(GObject*, GAsyncResult*, gpointer);
 static gboolean requestTimeoutCallback(void*);
 #if ENABLE(WEB_TIMING)
 static int  milisecondsSinceRequest(double requestTime);
 #endif
+static void continueAfterDidReceiveResponse(ResourceHandle*);
 
 static bool gIgnoreSSLErrors = false;
 
@@ -253,7 +251,9 @@ ResourceHandleInternal::~ResourceHandleInternal()
 
 static SoupSession* sessionFromContext(NetworkingContext* context)
 {
-    return (context && context->isValid()) ? context->soupSession() : ResourceHandle::defaultSession();
+    if (!context || !context->isValid())
+        return SoupNetworkSession::defaultSession().soupSession();
+    return context->storageSession().soupNetworkSession().soupSession();
 }
 
 ResourceHandle::~ResourceHandle()
@@ -261,42 +261,37 @@ ResourceHandle::~ResourceHandle()
     cleanupSoupRequestOperation(this, true);
 }
 
-static void ensureSessionIsInitialized(SoupSession* session)
+SoupSession* ResourceHandleInternal::soupSession()
 {
-    if (g_object_get_data(G_OBJECT(session), "webkit-init"))
-        return;
-
-    if (session == ResourceHandle::defaultSession()) {
-        SoupCookieJar* jar = SOUP_COOKIE_JAR(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
-        if (!jar)
-            soup_session_add_feature(session, SOUP_SESSION_FEATURE(soupCookieJar()));
-        else
-            setSoupCookieJar(jar);
-    }
-
-#if !LOG_DISABLED
-    if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
-        SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
-        soup_session_add_feature(session, SOUP_SESSION_FEATURE(logger));
-        soup_logger_set_printer(logger, soupLogPrinter, 0, 0);
-        g_object_unref(logger);
-    }
-#endif // !LOG_DISABLED
+    return sessionFromContext(m_context.get());
+}
 
-    if (!soup_session_get_feature(session, SOUP_TYPE_REQUESTER)) {
-        SoupRequester* requester = soup_requester_new();
-        soup_session_add_feature(session, SOUP_SESSION_FEATURE(requester));
-        g_object_unref(requester);
-    }
+bool ResourceHandle::cancelledOrClientless()
+{
+    if (!client())
+        return true;
 
-    g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
+    return getInternal()->m_cancelled;
 }
 
-SoupSession* ResourceHandleInternal::soupSession()
+void ResourceHandle::ensureReadBuffer()
 {
-    SoupSession* session = sessionFromContext(m_context.get());
-    ensureSessionIsInitialized(session);
-    return session;
+    ResourceHandleInternal* d = getInternal();
+
+    if (d->m_soupBuffer)
+        return;
+
+    // Non-NetworkProcess clients are able to give a buffer to the ResourceHandle to avoid expensive copies. If
+    // we do get a buffer from the client, we want the client to free it, so we create the soup buffer with
+    // SOUP_MEMORY_TEMPORARY.
+    size_t bufferSize;
+    char* bufferFromClient = client()->getOrCreateReadBuffer(gDefaultReadBufferSize, bufferSize);
+    if (bufferFromClient)
+        d->m_soupBuffer.reset(soup_buffer_new(SOUP_MEMORY_TEMPORARY, bufferFromClient, bufferSize));
+    else
+        d->m_soupBuffer.reset(soup_buffer_new(SOUP_MEMORY_TAKE, static_cast<char*>(g_malloc(gDefaultReadBufferSize)), gDefaultReadBufferSize));
+
+    ASSERT(d->m_soupBuffer);
 }
 
 static bool isAuthenticationFailureStatusCode(int httpStatusCode)
@@ -307,11 +302,10 @@ static bool isAuthenticationFailureStatusCode(int httpStatusCode)
 static void gotHeadersCallback(SoupMessage* message, gpointer data)
 {
     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
-    if (!handle)
+    if (!handle || handle->cancelledOrClientless())
         return;
+
     ResourceHandleInternal* d = handle->getInternal();
-    if (d->m_cancelled)
-        return;
 
 #if ENABLE(WEB_TIMING)
     if (d->m_response.resourceLoadTiming())
@@ -332,9 +326,7 @@ static void gotHeadersCallback(SoupMessage* message, gpointer data)
 
     // The original response will be needed later to feed to willSendRequest in
     // doRedirect() in case we are redirected. For this reason, we store it here.
-    ResourceResponse response;
-    response.updateFromSoupMessage(message);
-    d->m_response = response;
+    d->m_response.updateFromSoupMessage(message);
 }
 
 static void applyAuthenticationToRequest(ResourceHandle* handle, ResourceRequest& request, bool redirect)
@@ -367,29 +359,27 @@ static void applyAuthenticationToRequest(ResourceHandle* handle, ResourceRequest
     // We always put the credentials into the URL. In the CFNetwork-port HTTP family credentials are applied in
     // the didReceiveAuthenticationChallenge callback, but libsoup requires us to use this method to override
     // any previously remembered credentials. It has its own per-session credential storage.
-    KURL urlWithCredentials(request.url());
+    URL urlWithCredentials(request.url());
     urlWithCredentials.setUser(user);
     urlWithCredentials.setPass(password);
     request.setURL(urlWithCredentials);
 }
 
+#if ENABLE(WEB_TIMING)
 // Called each time the message is going to be sent again except the first time.
 // This happens when libsoup handles HTTP authentication.
 static void restartedCallback(SoupMessage*, gpointer data)
 {
     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
-    if (!handle)
-        return;
-    ResourceHandleInternal* d = handle->getInternal();
-    if (d->m_cancelled)
+    if (!handle || handle->cancelledOrClientless())
         return;
 
-#if ENABLE(WEB_TIMING)
+    ResourceHandleInternal* d = handle->getInternal();
     ResourceResponse& redirectResponse = d->m_response;
     redirectResponse.setResourceLoadTiming(ResourceLoadTiming::create());
     redirectResponse.resourceLoadTiming()->requestTime = monotonicallyIncreasingTime();
-#endif
 }
+#endif
 
 static bool shouldRedirect(ResourceHandle* handle)
 {
@@ -406,9 +396,9 @@ static bool shouldRedirect(ResourceHandle* handle)
     return true;
 }
 
-static bool shouldRedirectAsGET(SoupMessage* message, KURL& newURL, bool crossOrigin)
+static bool shouldRedirectAsGET(SoupMessage* message, URL& newURL, bool crossOrigin)
 {
-    if (message->method == SOUP_METHOD_GET)
+    if (message->method == SOUP_METHOD_GET || message->method == SOUP_METHOD_HEAD)
         return false;
 
     if (!newURL.protocolIsInHTTPFamily())
@@ -430,6 +420,25 @@ static bool shouldRedirectAsGET(SoupMessage* message, KURL& newURL, bool crossOr
     return false;
 }
 
+static void continueAfterWillSendRequest(ResourceHandle* handle, const ResourceRequest& request)
+{
+    // willSendRequest might cancel the load.
+    if (handle->cancelledOrClientless())
+        return;
+
+    ResourceRequest newRequest(request);
+    ResourceHandleInternal* d = handle->getInternal();
+    if (protocolHostAndPortAreEqual(newRequest.url(), d->m_response.url()))
+        applyAuthenticationToRequest(handle, newRequest, true);
+
+    if (!createSoupRequestAndMessageForHandle(handle, newRequest, true)) {
+        d->client()->cannotShowURL(handle);
+        return;
+    }
+
+    handle->sendPendingRequest();
+}
+
 static void doRedirect(ResourceHandle* handle)
 {
     ResourceHandleInternal* d = handle->getInternal();
@@ -441,92 +450,78 @@ static void doRedirect(ResourceHandle* handle)
         return;
     }
 
-    ResourceRequest request = handle->firstRequest();
+    ResourceRequest newRequest = handle->firstRequest();
     SoupMessage* message = d->m_soupMessage.get();
     const char* location = soup_message_headers_get_one(message->response_headers, "Location");
-    KURL newURL = KURL(soupURIToKURL(soup_message_get_uri(message)), location);
-    bool crossOrigin = !protocolHostAndPortAreEqual(request.url(), newURL);
-    request.setURL(newURL);
-
-    if (shouldRedirectAsGET(message, newURL, crossOrigin)) {
-        request.setHTTPMethod("GET");
-        request.setHTTPBody(0);
-        request.clearHTTPContentType();
+    URL newURL = URL(soupURIToKURL(soup_message_get_uri(message)), location);
+    bool crossOrigin = !protocolHostAndPortAreEqual(handle->firstRequest().url(), newURL);
+    newRequest.setURL(newURL);
+    newRequest.setFirstPartyForCookies(newURL);
+
+    if (newRequest.httpMethod() != "GET") {
+        // Change newRequest method to GET if change was made during a previous redirection
+        // or if current redirection says so
+        if (message->method == SOUP_METHOD_GET || shouldRedirectAsGET(message, newURL, crossOrigin)) {
+            newRequest.setHTTPMethod("GET");
+            newRequest.setHTTPBody(0);
+            newRequest.clearHTTPContentType();
+        }
     }
 
     // Should not set Referer after a redirect from a secure resource to non-secure one.
-    if (!newURL.protocolIs("https") && protocolIs(request.httpReferrer(), "https"))
-        request.clearHTTPReferrer();
+    if (!newURL.protocolIs("https") && protocolIs(newRequest.httpReferrer(), "https") && handle->context()->shouldClearReferrerOnHTTPSToHTTPRedirect())
+        newRequest.clearHTTPReferrer();
 
     d->m_user = newURL.user();
     d->m_pass = newURL.pass();
-    request.removeCredentials();
+    newRequest.removeCredentials();
 
     if (crossOrigin) {
         // If the network layer carries over authentication headers from the original request
         // in a cross-origin redirect, we want to clear those headers here. 
-        request.clearHTTPAuthorization();
+        newRequest.clearHTTPAuthorization();
 
         // TODO: We are losing any username and password specified in the redirect URL, as this is the 
         // same behavior as the CFNet port. We should investigate if this is really what we want.
-    } else
-        applyAuthenticationToRequest(handle, request, true);
-
-    cleanupSoupRequestOperation(handle);
-    if (!createSoupRequestAndMessageForHandle(handle, request, true)) {
-        d->client()->cannotShowURL(handle);
-        return;
     }
 
-    // If we sent credentials with this request's URL, we don't want the response to carry them to
-    // the WebKit layer. They were only placed in the URL for the benefit of libsoup.
-    request.removeCredentials();
-
-    d->client()->willSendRequest(handle, request, d->m_response);
-    handle->sendPendingRequest();
-}
-
-static void redirectCloseCallback(GObject*, GAsyncResult* result, gpointer data)
-{
-    RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
-    ResourceHandleInternal* d = handle->getInternal();
+    cleanupSoupRequestOperation(handle);
 
-    if (d->m_cancelled || !handle->client()) {
-        cleanupSoupRequestOperation(handle.get());
-        return;
+    if (d->client()->usesAsyncCallbacks())
+        d->client()->willSendRequestAsync(handle, newRequest, d->m_response);
+    else {
+        d->client()->willSendRequest(handle, newRequest, d->m_response);
+        continueAfterWillSendRequest(handle, newRequest);
     }
 
-    g_input_stream_close_finish(d->m_inputStream.get(), result, 0);
-    doRedirect(handle.get());
 }
 
 static void redirectSkipCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
 {
     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
 
-    ResourceHandleInternal* d = handle->getInternal();
-    ResourceHandleClient* client = handle->client();
-
-    if (d->m_cancelled || !client) {
+    if (handle->cancelledOrClientless()) {
         cleanupSoupRequestOperation(handle.get());
         return;
     }
 
     GOwnPtr<GError> error;
+    ResourceHandleInternal* d = handle->getInternal();
     gssize bytesSkipped = g_input_stream_skip_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
     if (error) {
-        client->didFail(handle.get(), ResourceError::genericIOError(error.get(), d->m_soupRequest.get()));
+        handle->client()->didFail(handle.get(), ResourceError::genericGError(error.get(), d->m_soupRequest.get()));
         cleanupSoupRequestOperation(handle.get());
         return;
     }
 
     if (bytesSkipped > 0) {
-        g_input_stream_skip_async(d->m_inputStream.get(), G_MAXSSIZE, G_PRIORITY_DEFAULT,
+        g_input_stream_skip_async(d->m_inputStream.get(), gDefaultReadBufferSize, G_PRIORITY_DEFAULT,
             d->m_cancellable.get(), redirectSkipCallback, handle.get());
         return;
     }
 
-    g_input_stream_close_async(d->m_inputStream.get(), G_PRIORITY_DEFAULT, 0, redirectCloseCallback, handle.get());
+    g_input_stream_close(d->m_inputStream.get(), 0, 0);
+    doRedirect(handle.get());
 }
 
 static void wroteBodyDataCallback(SoupMessage*, SoupBuffer* buffer, gpointer data)
@@ -536,16 +531,13 @@ static void wroteBodyDataCallback(SoupMessage*, SoupBuffer* buffer, gpointer dat
         return;
 
     ASSERT(buffer);
-    ResourceHandleInternal* internal = handle->getInternal();
-    internal->m_bodyDataSent += buffer->length;
+    ResourceHandleInternal* d = handle->getInternal();
+    d->m_bodyDataSent += buffer->length;
 
-    if (internal->m_cancelled)
-        return;
-    ResourceHandleClient* client = handle->client();
-    if (!client)
+    if (handle->cancelledOrClientless())
         return;
 
-    client->didSendData(handle.get(), internal->m_bodyDataSent, internal->m_bodySize);
+    handle->client()->didSendData(handle.get(), d->m_bodyDataSent, d->m_bodySize);
 }
 
 static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroying)
@@ -556,6 +548,7 @@ static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroyin
     d->m_inputStream.clear();
     d->m_multipartInputStream.clear();
     d->m_cancellable.clear();
+    d->m_soupBuffer.reset();
 
     if (d->m_soupMessage) {
         g_signal_handlers_disconnect_matched(d->m_soupMessage.get(), G_SIGNAL_MATCH_DATA,
@@ -564,11 +557,6 @@ static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroyin
         d->m_soupMessage.clear();
     }
 
-    if (d->m_buffer) {
-        g_slice_free1(READ_BUFFER_SIZE, d->m_buffer);
-        d->m_buffer = 0;
-    }
-
     if (d->m_timeoutSource) {
         g_source_destroy(d->m_timeoutSource.get());
         d->m_timeoutSource.clear();
@@ -599,30 +587,41 @@ static bool handleUnignoredTLSErrors(ResourceHandle* handle)
     return true;
 }
 
+size_t ResourceHandle::currentStreamPosition() const
+{
+    GInputStream* baseStream = d->m_inputStream.get();
+    while (!G_IS_SEEKABLE(baseStream) && G_IS_FILTER_INPUT_STREAM(baseStream))
+        baseStream = g_filter_input_stream_get_base_stream(G_FILTER_INPUT_STREAM(baseStream));
+
+    if (!G_IS_SEEKABLE(baseStream))
+        return 0;
+
+    return g_seekable_tell(G_SEEKABLE(baseStream));
+}
+
 static void nextMultipartResponsePartCallback(GObject* /*source*/, GAsyncResult* result, gpointer data)
 {
     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
 
-    ResourceHandleInternal* d = handle->getInternal();
-    ResourceHandleClient* client = handle->client();
-
-    if (d->m_cancelled || !client) {
+    if (handle->cancelledOrClientless()) {
         cleanupSoupRequestOperation(handle.get());
         return;
     }
 
+    ResourceHandleInternal* d = handle->getInternal();
     ASSERT(!d->m_inputStream);
 
     GOwnPtr<GError> error;
     d->m_inputStream = adoptGRef(soup_multipart_input_stream_next_part_finish(d->m_multipartInputStream.get(), result, &error.outPtr()));
+
     if (error) {
-        client->didFail(handle.get(), ResourceError::httpError(d->m_soupMessage.get(), error.get(), d->m_soupRequest.get()));
+        handle->client()->didFail(handle.get(), ResourceError::httpError(d->m_soupMessage.get(), error.get(), d->m_soupRequest.get()));
         cleanupSoupRequestOperation(handle.get());
         return;
     }
 
     if (!d->m_inputStream) {
-        client->didFinishLoading(handle.get(), 0);
+        handle->client()->didFinishLoading(handle.get(), 0);
         cleanupSoupRequestOperation(handle.get());
         return;
     }
@@ -631,30 +630,29 @@ static void nextMultipartResponsePartCallback(GObject* /*source*/, GAsyncResult*
     d->m_response.setURL(handle->firstRequest().url());
     d->m_response.updateFromSoupMessageHeaders(soup_multipart_input_stream_get_headers(d->m_multipartInputStream.get()));
 
-    client->didReceiveResponse(handle.get(), d->m_response);
+    d->m_previousPosition = 0;
 
-    if (d->m_cancelled || !client) {
-        cleanupSoupRequestOperation(handle.get());
-        return;
+    if (handle->client()->usesAsyncCallbacks())
+        handle->client()->didReceiveResponseAsync(handle.get(), d->m_response);
+    else {
+        handle->client()->didReceiveResponse(handle.get(), d->m_response);
+        continueAfterDidReceiveResponse(handle.get());
     }
-
-    g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
-        G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, handle.get());
 }
 
 static void sendRequestCallback(GObject*, GAsyncResult* result, gpointer data)
 {
     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
 
-    ResourceHandleInternal* d = handle->getInternal();
-    ResourceHandleClient* client = handle->client();
-    SoupMessage* soupMessage = d->m_soupMessage.get();
-
-    if (d->m_cancelled || !client) {
+    if (handle->cancelledOrClientless()) {
         cleanupSoupRequestOperation(handle.get());
         return;
     }
 
+    ResourceHandleInternal* d = handle->getInternal();
+    SoupMessage* soupMessage = d->m_soupMessage.get();
+
+
     if (d->m_defersLoading) {
         d->m_deferredResult = result;
         return;
@@ -663,7 +661,7 @@ static void sendRequestCallback(GObject*, GAsyncResult* result, gpointer data)
     GOwnPtr<GError> error;
     GRefPtr<GInputStream> inputStream = adoptGRef(soup_request_send_finish(d->m_soupRequest.get(), result, &error.outPtr()));
     if (error) {
-        client->didFail(handle.get(), ResourceError::httpError(soupMessage, error.get(), d->m_soupRequest.get()));
+        handle->client()->didFail(handle.get(), ResourceError::httpError(soupMessage, error.get(), d->m_soupRequest.get()));
         cleanupSoupRequestOperation(handle.get());
         return;
     }
@@ -671,7 +669,7 @@ static void sendRequestCallback(GObject*, GAsyncResult* result, gpointer data)
     if (soupMessage) {
         if (SOUP_STATUS_IS_REDIRECTION(soupMessage->status_code) && shouldRedirect(handle.get())) {
             d->m_inputStream = inputStream;
-            g_input_stream_skip_async(d->m_inputStream.get(), G_MAXSSIZE, G_PRIORITY_DEFAULT,
+            g_input_stream_skip_async(d->m_inputStream.get(), gDefaultReadBufferSize, G_PRIORITY_DEFAULT,
                 d->m_cancellable.get(), redirectSkipCallback, handle.get());
             return;
         }
@@ -695,25 +693,37 @@ static void sendRequestCallback(GObject*, GAsyncResult* result, gpointer data)
         d->m_response.setExpectedContentLength(soup_request_get_content_length(d->m_soupRequest.get()));
     }
 
-    client->didReceiveResponse(handle.get(), d->m_response);
+    if (soupMessage && d->m_response.isMultipart())
+        d->m_multipartInputStream = adoptGRef(soup_multipart_input_stream_new(soupMessage, inputStream.get()));
+    else
+        d->m_inputStream = inputStream;
 
-    if (d->m_cancelled) {
-        cleanupSoupRequestOperation(handle.get());
-        return;
+    if (d->client()->usesAsyncCallbacks())
+        handle->client()->didReceiveResponseAsync(handle.get(), d->m_response);
+    else {
+        handle->client()->didReceiveResponse(handle.get(), d->m_response);
+        continueAfterDidReceiveResponse(handle.get());
     }
+}
 
-    d->m_buffer = static_cast<char*>(g_slice_alloc(READ_BUFFER_SIZE));
+static void continueAfterDidReceiveResponse(ResourceHandle* handle)
+{
+    if (handle->cancelledOrClientless()) {
+        cleanupSoupRequestOperation(handle);
+        return;
+    }
 
-    if (soupMessage && d->m_response.isMultipart()) {
-        d->m_multipartInputStream = adoptGRef(soup_multipart_input_stream_new(soupMessage, inputStream.get()));
+    ResourceHandleInternal* d = handle->getInternal();
+    if (d->m_soupMessage && d->m_multipartInputStream && !d->m_inputStream) {
         soup_multipart_input_stream_next_part_async(d->m_multipartInputStream.get(), G_PRIORITY_DEFAULT,
-            d->m_cancellable.get(), nextMultipartResponsePartCallback, handle.get());
+            d->m_cancellable.get(), nextMultipartResponsePartCallback, handle);
         return;
     }
 
-    d->m_inputStream = inputStream;
-    g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
-                              G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, handle.get());
+    ASSERT(d->m_inputStream);
+    handle->ensureReadBuffer();
+    g_input_stream_read_async(d->m_inputStream.get(), const_cast<char*>(d->m_soupBuffer->data), d->m_soupBuffer->length,
+        G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, handle);
 }
 
 static bool addFileToSoupMessageBody(SoupMessage* message, const String& fileNameString, size_t offset, size_t lengthToSend, unsigned long& totalBodySize)
@@ -774,7 +784,7 @@ static void addEncodedBlobItemToSoupMessageBody(SoupMessage* message, const Blob
 
 static void addEncodedBlobToSoupMessageBody(SoupMessage* message, const FormDataElement& element, unsigned long& totalBodySize)
 {
-    RefPtr<BlobStorageData> blobData = static_cast<BlobRegistryImpl&>(blobRegistry()).getBlobDataFromURL(KURL(ParsedURLString, element.m_url));
+    RefPtr<BlobStorageData> blobData = static_cast<BlobRegistryImpl&>(blobRegistry()).getBlobDataFromURL(URL(ParsedURLString, element.m_url));
     if (!blobData)
         return;
 
@@ -834,13 +844,9 @@ static void wroteBodyCallback(SoupMessage*, gpointer data)
     d->m_response.resourceLoadTiming()->sendEnd = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
 }
 
-static void requestStartedCallback(SoupSession*, SoupMessage* soupMessage, SoupSocket*, gpointer)
+void ResourceHandle::didStartRequest()
 {
-    RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(G_OBJECT(soupMessage), "handle"));
-    if (!handle)
-        return;
-
-    ResourceHandleInternal* d = handle->getInternal();
+    ResourceHandleInternal* d = getInternal();
     if (!d->m_response.resourceLoadTiming())
         return;
 
@@ -861,10 +867,11 @@ static void networkEventCallback(SoupMessage*, GSocketClientEvent event, GIOStre
     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
     if (!handle)
         return;
-    ResourceHandleInternal* d = handle->getInternal();
-    if (d->m_cancelled)
+
+    if (handle->cancelledOrClientless())
         return;
 
+    ResourceHandleInternal* d = handle->getInternal();
     int deltaTime = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
     switch (event) {
     case G_SOCKET_CLIENT_RESOLVING:
@@ -940,12 +947,6 @@ static bool createSoupMessageForHandleAndRequest(ResourceHandle* handle, const R
     if (!handle->shouldContentSniff())
         soup_message_disable_feature(soupMessage, SOUP_TYPE_CONTENT_SNIFFER);
 
-    String firstPartyString = request.firstPartyForCookies().string();
-    if (!firstPartyString.isEmpty()) {
-        GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
-        soup_message_set_first_party(soupMessage, firstParty.get());
-    }
-
     FormData* httpBody = request.httpBody();
     CString contentType = request.httpContentType().utf8().data();
     if (httpBody && !httpBody->isEmpty() && !addFormElementsToSoupMessage(soupMessage, contentType.data(), httpBody, d->m_bodySize)) {
@@ -968,7 +969,6 @@ static bool createSoupMessageForHandleAndRequest(ResourceHandle* handle, const R
         soup_message_headers_set_content_length(soupMessage->request_headers, 0);
 
     g_signal_connect(d->m_soupMessage.get(), "got-headers", G_CALLBACK(gotHeadersCallback), handle);
-    g_signal_connect(d->m_soupMessage.get(), "restarted", G_CALLBACK(restartedCallback), handle);
     g_signal_connect(d->m_soupMessage.get(), "wrote-body-data", G_CALLBACK(wroteBodyDataCallback), handle);
 
     soup_message_set_flags(d->m_soupMessage.get(), static_cast<SoupMessageFlags>(soup_message_get_flags(d->m_soupMessage.get()) | SOUP_MESSAGE_NO_REDIRECT));
@@ -976,24 +976,28 @@ static bool createSoupMessageForHandleAndRequest(ResourceHandle* handle, const R
 #if ENABLE(WEB_TIMING)
     d->m_response.setResourceLoadTiming(ResourceLoadTiming::create());
     g_signal_connect(d->m_soupMessage.get(), "network-event", G_CALLBACK(networkEventCallback), handle);
+    g_signal_connect(d->m_soupMessage.get(), "restarted", G_CALLBACK(restartedCallback), handle);
     g_signal_connect(d->m_soupMessage.get(), "wrote-body", G_CALLBACK(wroteBodyCallback), handle);
 #endif
 
+#if SOUP_CHECK_VERSION(2, 43, 1)
+    soup_message_set_priority(d->m_soupMessage.get(), toSoupMessagePriority(request.priority()));
+#endif
+
     return true;
 }
 
 static bool createSoupRequestAndMessageForHandle(ResourceHandle* handle, const ResourceRequest& request, bool isHTTPFamilyRequest)
 {
     ResourceHandleInternal* d = handle->getInternal();
-    SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(d->soupSession(), SOUP_TYPE_REQUESTER));
 
     GOwnPtr<GError> error;
 
-    GOwnPtr<SoupURI> soupURI(request.soupURI());
+    GUniquePtr<SoupURI> soupURI(request.soupURI());
     if (!soupURI)
         return false;
 
-    d->m_soupRequest = adoptGRef(soup_requester_request_uri(requester, soupURI.get(), &error.outPtr()));
+    d->m_soupRequest = adoptGRef(soup_session_request_uri(d->soupSession(), soupURI.get(), &error.outPtr()));
     if (error) {
         d->m_soupRequest.clear();
         return false;
@@ -1005,10 +1009,12 @@ static bool createSoupRequestAndMessageForHandle(ResourceHandle* handle, const R
         return false;
     }
 
+    setSoupRequestInitiatingPageIDFromNetworkingContext(d->m_soupRequest.get(), d->m_context.get());
+
     return true;
 }
 
-bool ResourceHandle::start(NetworkingContext* context)
+bool ResourceHandle::start()
 {
     ASSERT(!d->m_soupMessage);
 
@@ -1017,12 +1023,9 @@ bool ResourceHandle::start(NetworkingContext* context)
     // If the frame is not null but the page is null this must be an attempted
     // load from an unload handler, so let's just block it.
     // If both the frame and the page are not null the context is valid.
-    if (context && !context->isValid())
+    if (d->m_context && !d->m_context->isValid())
         return false;
 
-    // Used to set the keep track of custom SoupSessions for ports that support it (EFL).
-    d->m_context = context;
-
     // Only allow the POST and GET methods for non-HTTP requests.
     const ResourceRequest& request = firstRequest();
     bool isHTTPFamilyRequest = request.url().protocolIsInHTTPFamily();
@@ -1038,8 +1041,6 @@ bool ResourceHandle::start(NetworkingContext* context)
         return true;
     }
 
-    setSoupRequestInitiatingPageIDFromNetworkingContext(d->m_soupRequest.get(), context);
-
     // Send the request only if it's not been explicitly deferred.
     if (!d->m_defersLoading)
         sendPendingRequest();
@@ -1223,6 +1224,13 @@ void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challen
     if (challenge != d->m_currentWebChallenge)
         return;
 
+    if (cancelledOrClientless()) {
+        clearAuthentication();
+        return;
+    }
+
+    ASSERT(challenge.soupSession());
+    ASSERT(challenge.soupMessage());
     soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
 
     if (client())
@@ -1241,7 +1249,7 @@ static bool waitingToSendRequest(ResourceHandle* handle)
 
 void ResourceHandle::platformSetDefersLoading(bool defersLoading)
 {
-    if (d->m_cancelled)
+    if (cancelledOrClientless())
         return;
 
     // Except when canceling a possible timeout timer, we only need to take action here to UN-defer loading.
@@ -1273,15 +1281,8 @@ bool ResourceHandle::loadsBlocked()
     return false;
 }
 
-void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
+void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
 {
-#if ENABLE(BLOB)
-    if (request.url().protocolIs("blob")) {
-        blobRegistry().loadResourceSynchronously(request, error, response, data);
-        return;
-    }
-#endif
     ASSERT(!loadingSynchronousRequest);
     if (loadingSynchronousRequest) // In practice this cannot happen, but if for some reason it does,
         return;                    // we want to avoid accidentally going into an infinite loop of requests.
@@ -1298,32 +1299,16 @@ void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const
     syncLoader.run();
 }
 
-static void closeCallback(GObject*, GAsyncResult* res, gpointer data)
-{
-    RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
-    ResourceHandleInternal* d = handle->getInternal();
-
-    g_input_stream_close_finish(d->m_inputStream.get(), res, 0);
-
-    ResourceHandleClient* client = handle->client();
-    if (client && loadingSynchronousRequest)
-        client->didFinishLoading(handle.get(), 0);
-
-    cleanupSoupRequestOperation(handle.get());
-}
-
 static void readCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
 {
     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
 
-    ResourceHandleInternal* d = handle->getInternal();
-    ResourceHandleClient* client = handle->client();
-
-    if (d->m_cancelled || !client) {
+    if (handle->cancelledOrClientless()) {
         cleanupSoupRequestOperation(handle.get());
         return;
     }
 
+    ResourceHandleInternal* d = handle->getInternal();
     if (d->m_defersLoading) {
         d->m_deferredResult = asyncResult;
         return;
@@ -1331,8 +1316,9 @@ static void readCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
 
     GOwnPtr<GError> error;
     gssize bytesRead = g_input_stream_read_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
+
     if (error) {
-        client->didFail(handle.get(), ResourceError::genericIOError(error.get(), d->m_soupRequest.get()));
+        handle->client()->didFail(handle.get(), ResourceError::genericGError(error.get(), d->m_soupRequest.get()));
         cleanupSoupRequestOperation(handle.get());
         return;
     }
@@ -1346,79 +1332,64 @@ static void readCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
             return;
         }
 
-        // We inform WebCore of load completion now instead of waiting for the input
-        // stream to close because the input stream is closed asynchronously. If this
-        // is a synchronous request, we wait until the closeCallback, because we don't
-        // want to halt the internal main loop before the input stream closes.
-        if (client && !loadingSynchronousRequest) {
-            client->didFinishLoading(handle.get(), 0);
-            handle->setClient(0); // Unset the client so that we do not try to access th
-                                  // client in the closeCallback.
-        }
-        g_input_stream_close_async(d->m_inputStream.get(), G_PRIORITY_DEFAULT, 0, closeCallback, handle.get());
+        g_input_stream_close(d->m_inputStream.get(), 0, 0);
+
+        handle->client()->didFinishLoading(handle.get(), 0);
+        cleanupSoupRequestOperation(handle.get());
         return;
     }
 
     // It's mandatory to have sent a response before sending data
     ASSERT(!d->m_response.isNull());
 
-    client->didReceiveData(handle.get(), d->m_buffer, bytesRead, bytesRead);
+    size_t currentPosition = handle->currentStreamPosition();
+    size_t encodedDataLength = currentPosition ? currentPosition - d->m_previousPosition : bytesRead;
+
+    ASSERT(d->m_soupBuffer);
+    d->m_soupBuffer->length = bytesRead; // The buffer might be larger than the number of bytes read. SharedBuffer looks at the length property.
+    handle->client()->didReceiveBuffer(handle.get(), SharedBuffer::wrapSoupBuffer(d->m_soupBuffer.release()), encodedDataLength);
+
+    d->m_previousPosition = currentPosition;
 
-    // didReceiveData may cancel the load, which may release the last reference.
-    if (d->m_cancelled || !client) {
+    // didReceiveBuffer may cancel the load, which may release the last reference.
+    if (handle->cancelledOrClientless()) {
         cleanupSoupRequestOperation(handle.get());
         return;
     }
 
-    g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE, G_PRIORITY_DEFAULT,
-                              d->m_cancellable.get(), readCallback, handle.get());
+    handle->ensureReadBuffer();
+    g_input_stream_read_async(d->m_inputStream.get(), const_cast<char*>(d->m_soupBuffer->data), d->m_soupBuffer->length, G_PRIORITY_DEFAULT,
+        d->m_cancellable.get(), readCallback, handle.get());
 }
 
-static gboolean requestTimeoutCallback(gpointer data)
+void ResourceHandle::continueWillSendRequest(const ResourceRequest& request)
 {
-    RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
-    handle->client()->didFail(handle.get(), ResourceError::timeoutError(handle->getInternal()->m_firstRequest.url().string()));
-    handle->cancel();
-
-    return FALSE;
+    ASSERT(client());
+    ASSERT(client()->usesAsyncCallbacks());
+    continueAfterWillSendRequest(this, request);
 }
 
-static void authenticateCallback(SoupSession* session, SoupMessage* soupMessage, SoupAuth* soupAuth, gboolean retrying)
+void ResourceHandle::continueDidReceiveResponse()
 {
-    RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(G_OBJECT(soupMessage), "handle"));
-    if (!handle)
-        return;
-    handle->didReceiveAuthenticationChallenge(AuthenticationChallenge(session, soupMessage, soupAuth, retrying, handle.get()));
+    ASSERT(client());
+    ASSERT(client()->usesAsyncCallbacks());
+    continueAfterDidReceiveResponse(this);
 }
 
-SoupSession* ResourceHandle::defaultSession()
+void ResourceHandle::continueShouldUseCredentialStorage(bool)
 {
-    static SoupSession* session = 0;
-    // Values taken from http://www.browserscope.org/  following
-    // the rule "Do What Every Other Modern Browser Is Doing". They seem
-    // to significantly improve page loading time compared to soup's
-    // default values.
-    static const int maxConnections = 35;
-    static const int maxConnectionsPerHost = 6;
-
-    if (!session) {
-        session = soup_session_async_new();
-        g_object_set(session,
-                     SOUP_SESSION_MAX_CONNS, maxConnections,
-                     SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
-                     SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_DECODER,
-                     SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_SNIFFER,
-                     SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
-                     SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
-                     NULL);
-        g_signal_connect(session, "authenticate", G_CALLBACK(authenticateCallback), 0);
+    ASSERT(client());
+    ASSERT(client()->usesAsyncCallbacks());
+    // FIXME: Implement this method if needed: https://bugs.webkit.org/show_bug.cgi?id=126114.
+}
 
-#if ENABLE(WEB_TIMING)
-        g_signal_connect(session, "request-started", G_CALLBACK(requestStartedCallback), 0);
-#endif
-    }
+static gboolean requestTimeoutCallback(gpointer data)
+{
+    RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
+    handle->client()->didFail(handle.get(), ResourceError::timeoutError(handle->getInternal()->m_firstRequest.url().string()));
+    handle->cancel();
 
-    return session;
+    return FALSE;
 }
 
 uint64_t ResourceHandle::getSoupRequestInitiatingPageID(SoupRequest* request)