2 * Copyright (C) 2004, 2005, 2006, 2007, 2009, 2010, 2011 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Alp Toker <alp@atoker.com>
4 * Copyright (C) 2008 Xan Lopez <xan@gnome.org>
5 * Copyright (C) 2008, 2010 Collabora Ltd.
6 * Copyright (C) 2009 Holger Hans Peter Freyther
7 * Copyright (C) 2009, 2013 Gustavo Noronha Silva <gns@gnome.org>
8 * Copyright (C) 2009 Christian Dywan <christian@imendio.com>
9 * Copyright (C) 2009, 2010, 2011, 2012 Igalia S.L.
10 * Copyright (C) 2009 John Kjellberg <john.kjellberg@power.alstom.com>
11 * Copyright (C) 2012 Intel Corporation
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Library General Public
15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Library General Public License for more details.
23 * You should have received a copy of the GNU Library General Public License
24 * along with this library; see the file COPYING.LIB. If not, write to
25 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 * Boston, MA 02110-1301, USA.
30 #include "ResourceHandle.h"
32 #include "CookieJarSoup.h"
33 #include "CredentialStorage.h"
34 #include "FileSystem.h"
35 #include "GOwnPtrSoup.h"
36 #include "HTTPParsers.h"
37 #include "LocalizedStrings.h"
39 #include "MIMETypeRegistry.h"
40 #include "NetworkingContext.h"
41 #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 "SoupURIUtils.h"
48 #include "TextEncoding.h"
53 #include <libsoup/soup.h>
55 #include <sys/types.h>
57 #include <wtf/CurrentTime.h>
59 #include <wtf/gobject/GRefPtr.h>
60 #include <wtf/text/Base64.h>
61 #include <wtf/text/CString.h>
65 #include "BlobRegistryImpl.h"
66 #include "BlobStorageData.h"
70 #include "CredentialBackingStore.h"
75 inline static void soupLogPrinter(SoupLogger*, SoupLoggerLogLevel, char direction, const char* data, gpointer)
78 UNUSED_PARAM(direction);
81 LOG(Network, "%c %s", direction, data);
84 static bool loadingSynchronousRequest = false;
85 static const size_t gDefaultReadBufferSize = 8192;
87 class WebCoreSynchronousLoader : public ResourceHandleClient {
88 WTF_MAKE_NONCOPYABLE(WebCoreSynchronousLoader);
91 WebCoreSynchronousLoader(ResourceError& error, ResourceResponse& response, SoupSession* session, Vector<char>& data)
93 , m_response(response)
98 // We don't want any timers to fire while we are doing our synchronous load
99 // so we replace the thread default main context. The main loop iterations
100 // will only process GSources associated with this inner context.
101 loadingSynchronousRequest = true;
102 GRefPtr<GMainContext> innerMainContext = adoptGRef(g_main_context_new());
103 g_main_context_push_thread_default(innerMainContext.get());
104 m_mainLoop = adoptGRef(g_main_loop_new(innerMainContext.get(), false));
106 adjustMaxConnections(1);
109 ~WebCoreSynchronousLoader()
111 adjustMaxConnections(-1);
113 GMainContext* context = g_main_context_get_thread_default();
114 while (g_main_context_pending(context))
115 g_main_context_iteration(context, FALSE);
117 g_main_context_pop_thread_default(context);
118 loadingSynchronousRequest = false;
121 void adjustMaxConnections(int adjustment)
123 int maxConnections, maxConnectionsPerHost;
124 g_object_get(m_session,
125 SOUP_SESSION_MAX_CONNS, &maxConnections,
126 SOUP_SESSION_MAX_CONNS_PER_HOST, &maxConnectionsPerHost,
128 maxConnections += adjustment;
129 maxConnectionsPerHost += adjustment;
130 g_object_set(m_session,
131 SOUP_SESSION_MAX_CONNS, maxConnections,
132 SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
137 virtual bool isSynchronousClient()
142 virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
144 m_response = response;
147 virtual void didReceiveData(ResourceHandle*, const char* /* data */, int /* length */, int)
149 ASSERT_NOT_REACHED();
152 virtual void didReceiveBuffer(ResourceHandle*, PassRefPtr<SharedBuffer> buffer, int /* encodedLength */)
154 // This pattern is suggested by SharedBuffer.h.
156 unsigned position = 0;
157 while (unsigned length = buffer->getSomeData(segment, position)) {
158 m_data.append(segment, length);
163 virtual void didFinishLoading(ResourceHandle*, double)
165 if (g_main_loop_is_running(m_mainLoop.get()))
166 g_main_loop_quit(m_mainLoop.get());
170 virtual void didFail(ResourceHandle* handle, const ResourceError& error)
173 didFinishLoading(handle, 0);
176 virtual void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge& challenge)
178 // We do not handle authentication for synchronous XMLHttpRequests.
179 challenge.authenticationClient()->receivedRequestToContinueWithoutCredential(challenge);
185 g_main_loop_run(m_mainLoop.get());
189 ResourceError& m_error;
190 ResourceResponse& m_response;
191 SoupSession* m_session;
192 Vector<char>& m_data;
194 GRefPtr<GMainLoop> m_mainLoop;
197 class HostTLSCertificateSet {
199 void add(GTlsCertificate* certificate)
201 String certificateHash = computeCertificateHash(certificate);
202 if (!certificateHash.isEmpty())
203 m_certificates.add(certificateHash);
206 bool contains(GTlsCertificate* certificate)
208 return m_certificates.contains(computeCertificateHash(certificate));
212 static String computeCertificateHash(GTlsCertificate* certificate)
214 GRefPtr<GByteArray> certificateData;
215 g_object_get(G_OBJECT(certificate), "certificate", &certificateData.outPtr(), NULL);
216 if (!certificateData)
220 sha1.addBytes(certificateData->data, certificateData->len);
223 sha1.computeHash(digest);
225 return base64Encode(reinterpret_cast<const char*>(digest.data()), SHA1::hashSize);
228 HashSet<String> m_certificates;
231 static bool createSoupRequestAndMessageForHandle(ResourceHandle*, const ResourceRequest&, bool isHTTPFamilyRequest);
232 static void cleanupSoupRequestOperation(ResourceHandle*, bool isDestroying = false);
233 static void sendRequestCallback(GObject*, GAsyncResult*, gpointer);
234 static void readCallback(GObject*, GAsyncResult*, gpointer);
235 static gboolean requestTimeoutCallback(void*);
236 #if ENABLE(WEB_TIMING)
237 static int milisecondsSinceRequest(double requestTime);
239 static void continueAfterDidReceiveResponse(ResourceHandle*);
241 static bool gIgnoreSSLErrors = false;
243 static HashSet<String>& allowsAnyHTTPSCertificateHosts()
245 DEFINE_STATIC_LOCAL(HashSet<String>, hosts, ());
249 typedef HashMap<String, HostTLSCertificateSet> CertificatesMap;
250 static CertificatesMap& clientCertificates()
252 DEFINE_STATIC_LOCAL(CertificatesMap, certificates, ());
256 ResourceHandleInternal::~ResourceHandleInternal()
260 static SoupSession* sessionFromContext(NetworkingContext* context)
262 if (!context || !context->isValid())
263 return ResourceHandle::defaultSession();
264 return context->storageSession().soupSession();
267 ResourceHandle::~ResourceHandle()
269 cleanupSoupRequestOperation(this, true);
272 static void ensureSessionIsInitialized(SoupSession* session)
274 if (g_object_get_data(G_OBJECT(session), "webkit-init"))
277 if (session == ResourceHandle::defaultSession()) {
278 SoupCookieJar* jar = SOUP_COOKIE_JAR(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
280 soup_session_add_feature(session, SOUP_SESSION_FEATURE(soupCookieJar()));
282 setSoupCookieJar(jar);
286 if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
287 SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
288 soup_session_add_feature(session, SOUP_SESSION_FEATURE(logger));
289 soup_logger_set_printer(logger, soupLogPrinter, 0, 0);
290 g_object_unref(logger);
292 #endif // !LOG_DISABLED
294 g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
297 SoupSession* ResourceHandleInternal::soupSession()
299 SoupSession* session = sessionFromContext(m_context.get());
300 ensureSessionIsInitialized(session);
304 bool ResourceHandle::cancelledOrClientless()
309 return getInternal()->m_cancelled;
312 void ResourceHandle::ensureReadBuffer()
314 ResourceHandleInternal* d = getInternal();
319 // Non-NetworkProcess clients are able to give a buffer to the ResourceHandle to avoid expensive copies. If
320 // we do get a buffer from the client, we want the client to free it, so we create the soup buffer with
321 // SOUP_MEMORY_TEMPORARY.
323 char* bufferFromClient = client()->getOrCreateReadBuffer(gDefaultReadBufferSize, bufferSize);
324 if (bufferFromClient)
325 d->m_soupBuffer.set(soup_buffer_new(SOUP_MEMORY_TEMPORARY, bufferFromClient, bufferSize));
327 d->m_soupBuffer.set(soup_buffer_new(SOUP_MEMORY_TAKE, static_cast<char*>(g_malloc(gDefaultReadBufferSize)), gDefaultReadBufferSize));
329 ASSERT(d->m_soupBuffer);
332 static bool isAuthenticationFailureStatusCode(int httpStatusCode)
334 return httpStatusCode == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED || httpStatusCode == SOUP_STATUS_UNAUTHORIZED;
337 static void gotHeadersCallback(SoupMessage* message, gpointer data)
339 ResourceHandle* handle = static_cast<ResourceHandle*>(data);
340 if (!handle || handle->cancelledOrClientless())
343 ResourceHandleInternal* d = handle->getInternal();
345 #if ENABLE(WEB_TIMING)
346 if (d->m_response.resourceLoadTiming())
347 d->m_response.resourceLoadTiming()->receiveHeadersEnd = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
351 // We are a bit more conservative with the persistent credential storage than the session store,
352 // since we are waiting until we know that this authentication succeeded before actually storing.
353 // This is because we want to avoid hitting the disk twice (once to add and once to remove) for
354 // incorrect credentials or polluting the keychain with invalid credentials.
355 if (!isAuthenticationFailureStatusCode(message->status_code) && message->status_code < 500 && !d->m_credentialDataToSaveInPersistentStore.credential.isEmpty()) {
356 credentialBackingStore().storeCredentialsForChallenge(
357 d->m_credentialDataToSaveInPersistentStore.challenge,
358 d->m_credentialDataToSaveInPersistentStore.credential);
362 // The original response will be needed later to feed to willSendRequest in
363 // doRedirect() in case we are redirected. For this reason, we store it here.
364 d->m_response.updateFromSoupMessage(message);
367 static void applyAuthenticationToRequest(ResourceHandle* handle, ResourceRequest& request, bool redirect)
369 // m_user/m_pass are credentials given manually, for instance, by the arguments passed to XMLHttpRequest.open().
370 ResourceHandleInternal* d = handle->getInternal();
372 if (handle->shouldUseCredentialStorage()) {
373 if (d->m_user.isEmpty() && d->m_pass.isEmpty())
374 d->m_initialCredential = CredentialStorage::get(request.url());
375 else if (!redirect) {
376 // If there is already a protection space known for the URL, update stored credentials
377 // before sending a request. This makes it possible to implement logout by sending an
378 // XMLHttpRequest with known incorrect credentials, and aborting it immediately (so that
379 // an authentication dialog doesn't pop up).
380 CredentialStorage::set(Credential(d->m_user, d->m_pass, CredentialPersistenceNone), request.url());
384 String user = d->m_user;
385 String password = d->m_pass;
386 if (!d->m_initialCredential.isEmpty()) {
387 user = d->m_initialCredential.user();
388 password = d->m_initialCredential.password();
391 if (user.isEmpty() && password.isEmpty())
394 // We always put the credentials into the URL. In the CFNetwork-port HTTP family credentials are applied in
395 // the didReceiveAuthenticationChallenge callback, but libsoup requires us to use this method to override
396 // any previously remembered credentials. It has its own per-session credential storage.
397 URL urlWithCredentials(request.url());
398 urlWithCredentials.setUser(user);
399 urlWithCredentials.setPass(password);
400 request.setURL(urlWithCredentials);
403 #if ENABLE(WEB_TIMING)
404 // Called each time the message is going to be sent again except the first time.
405 // This happens when libsoup handles HTTP authentication.
406 static void restartedCallback(SoupMessage*, gpointer data)
408 ResourceHandle* handle = static_cast<ResourceHandle*>(data);
409 if (!handle || handle->cancelledOrClientless())
412 ResourceHandleInternal* d = handle->getInternal();
413 ResourceResponse& redirectResponse = d->m_response;
414 redirectResponse.setResourceLoadTiming(ResourceLoadTiming::create());
415 redirectResponse.resourceLoadTiming()->requestTime = monotonicallyIncreasingTime();
419 static bool shouldRedirect(ResourceHandle* handle)
421 ResourceHandleInternal* d = handle->getInternal();
422 SoupMessage* message = d->m_soupMessage.get();
424 // Some 3xx status codes aren't actually redirects.
425 if (message->status_code == 300 || message->status_code == 304 || message->status_code == 305 || message->status_code == 306)
428 if (!soup_message_headers_get_one(message->response_headers, "Location"))
434 static bool shouldRedirectAsGET(SoupMessage* message, URL& newURL, bool crossOrigin)
436 if (message->method == SOUP_METHOD_GET || message->method == SOUP_METHOD_HEAD)
439 if (!newURL.protocolIsInHTTPFamily())
442 switch (message->status_code) {
443 case SOUP_STATUS_SEE_OTHER:
445 case SOUP_STATUS_FOUND:
446 case SOUP_STATUS_MOVED_PERMANENTLY:
447 if (message->method == SOUP_METHOD_POST)
452 if (crossOrigin && message->method == SOUP_METHOD_DELETE)
458 static void continueAfterWillSendRequest(ResourceHandle* handle, const ResourceRequest& newRequest)
460 // willSendRequest might cancel the load.
461 if (handle->cancelledOrClientless())
464 if (!createSoupRequestAndMessageForHandle(handle, newRequest, true)) {
465 handle->getInternal()->client()->cannotShowURL(handle);
469 handle->sendPendingRequest();
472 static void doRedirect(ResourceHandle* handle)
474 ResourceHandleInternal* d = handle->getInternal();
475 static const int maxRedirects = 20;
477 if (d->m_redirectCount++ > maxRedirects) {
478 d->client()->didFail(handle, ResourceError::transportError(d->m_soupRequest.get(), SOUP_STATUS_TOO_MANY_REDIRECTS, "Too many redirects"));
479 cleanupSoupRequestOperation(handle);
483 ResourceRequest newRequest = handle->firstRequest();
484 SoupMessage* message = d->m_soupMessage.get();
485 const char* location = soup_message_headers_get_one(message->response_headers, "Location");
486 URL newURL = URL(soupURIToKURL(soup_message_get_uri(message)), location);
487 bool crossOrigin = !protocolHostAndPortAreEqual(handle->firstRequest().url(), newURL);
488 newRequest.setURL(newURL);
489 newRequest.setFirstPartyForCookies(newURL);
491 if (newRequest.httpMethod() != "GET") {
492 // Change newRequest method to GET if change was made during a previous redirection
493 // or if current redirection says so
494 if (message->method == SOUP_METHOD_GET || shouldRedirectAsGET(message, newURL, crossOrigin)) {
495 newRequest.setHTTPMethod("GET");
496 newRequest.setHTTPBody(0);
497 newRequest.clearHTTPContentType();
501 // Should not set Referer after a redirect from a secure resource to non-secure one.
502 if (!newURL.protocolIs("https") && protocolIs(newRequest.httpReferrer(), "https") && handle->context()->shouldClearReferrerOnHTTPSToHTTPRedirect())
503 newRequest.clearHTTPReferrer();
505 d->m_user = newURL.user();
506 d->m_pass = newURL.pass();
507 newRequest.removeCredentials();
510 // If the network layer carries over authentication headers from the original request
511 // in a cross-origin redirect, we want to clear those headers here.
512 newRequest.clearHTTPAuthorization();
514 // TODO: We are losing any username and password specified in the redirect URL, as this is the
515 // same behavior as the CFNet port. We should investigate if this is really what we want.
517 applyAuthenticationToRequest(handle, newRequest, true);
519 // If we sent credentials with this request's URL, we don't want the response to carry them to
520 // the WebKit layer. They were only placed in the URL for the benefit of libsoup.
521 newRequest.removeCredentials();
523 cleanupSoupRequestOperation(handle);
525 if (d->client()->usesAsyncCallbacks())
526 d->client()->willSendRequestAsync(handle, newRequest, d->m_response);
528 d->client()->willSendRequest(handle, newRequest, d->m_response);
529 continueAfterWillSendRequest(handle, newRequest);
534 static void redirectSkipCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
536 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
538 if (handle->cancelledOrClientless()) {
539 cleanupSoupRequestOperation(handle.get());
543 GOwnPtr<GError> error;
544 ResourceHandleInternal* d = handle->getInternal();
545 gssize bytesSkipped = g_input_stream_skip_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
547 handle->client()->didFail(handle.get(), ResourceError::genericGError(error.get(), d->m_soupRequest.get()));
548 cleanupSoupRequestOperation(handle.get());
552 if (bytesSkipped > 0) {
553 g_input_stream_skip_async(d->m_inputStream.get(), gDefaultReadBufferSize, G_PRIORITY_DEFAULT,
554 d->m_cancellable.get(), redirectSkipCallback, handle.get());
558 g_input_stream_close(d->m_inputStream.get(), 0, 0);
559 doRedirect(handle.get());
562 static void wroteBodyDataCallback(SoupMessage*, SoupBuffer* buffer, gpointer data)
564 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
569 ResourceHandleInternal* d = handle->getInternal();
570 d->m_bodyDataSent += buffer->length;
572 if (handle->cancelledOrClientless())
575 handle->client()->didSendData(handle.get(), d->m_bodyDataSent, d->m_bodySize);
578 static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroying)
580 ResourceHandleInternal* d = handle->getInternal();
582 d->m_soupRequest.clear();
583 d->m_inputStream.clear();
584 d->m_multipartInputStream.clear();
585 d->m_cancellable.clear();
586 d->m_soupBuffer.clear();
588 if (d->m_soupMessage) {
589 g_signal_handlers_disconnect_matched(d->m_soupMessage.get(), G_SIGNAL_MATCH_DATA,
591 g_object_set_data(G_OBJECT(d->m_soupMessage.get()), "handle", 0);
592 d->m_soupMessage.clear();
595 if (d->m_timeoutSource) {
596 g_source_destroy(d->m_timeoutSource.get());
597 d->m_timeoutSource.clear();
604 static bool handleUnignoredTLSErrors(ResourceHandle* handle)
606 ResourceHandleInternal* d = handle->getInternal();
607 const ResourceResponse& response = d->m_response;
609 if (!response.soupMessageTLSErrors() || gIgnoreSSLErrors)
612 String lowercaseHostURL = handle->firstRequest().url().host().lower();
613 if (allowsAnyHTTPSCertificateHosts().contains(lowercaseHostURL))
616 // We aren't ignoring errors globally, but the user may have already decided to accept this certificate.
617 CertificatesMap::iterator i = clientCertificates().find(lowercaseHostURL);
618 if (i != clientCertificates().end() && i->value.contains(response.soupMessageCertificate()))
621 handle->client()->didFail(handle, ResourceError::tlsError(d->m_soupRequest.get(), response.soupMessageTLSErrors(), response.soupMessageCertificate()));
625 size_t ResourceHandle::currentStreamPosition() const
627 GInputStream* baseStream = d->m_inputStream.get();
628 while (!G_IS_SEEKABLE(baseStream) && G_IS_FILTER_INPUT_STREAM(baseStream))
629 baseStream = g_filter_input_stream_get_base_stream(G_FILTER_INPUT_STREAM(baseStream));
631 if (!G_IS_SEEKABLE(baseStream))
634 return g_seekable_tell(G_SEEKABLE(baseStream));
637 static void nextMultipartResponsePartCallback(GObject* /*source*/, GAsyncResult* result, gpointer data)
639 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
641 if (handle->cancelledOrClientless()) {
642 cleanupSoupRequestOperation(handle.get());
646 ResourceHandleInternal* d = handle->getInternal();
647 ASSERT(!d->m_inputStream);
649 GOwnPtr<GError> error;
650 d->m_inputStream = adoptGRef(soup_multipart_input_stream_next_part_finish(d->m_multipartInputStream.get(), result, &error.outPtr()));
653 handle->client()->didFail(handle.get(), ResourceError::httpError(d->m_soupMessage.get(), error.get(), d->m_soupRequest.get()));
654 cleanupSoupRequestOperation(handle.get());
658 if (!d->m_inputStream) {
659 handle->client()->didFinishLoading(handle.get(), 0);
660 cleanupSoupRequestOperation(handle.get());
664 d->m_response = ResourceResponse();
665 d->m_response.setURL(handle->firstRequest().url());
666 d->m_response.updateFromSoupMessageHeaders(soup_multipart_input_stream_get_headers(d->m_multipartInputStream.get()));
668 d->m_previousPosition = 0;
670 if (handle->client()->usesAsyncCallbacks())
671 handle->client()->didReceiveResponseAsync(handle.get(), d->m_response);
673 handle->client()->didReceiveResponse(handle.get(), d->m_response);
674 continueAfterDidReceiveResponse(handle.get());
678 static void sendRequestCallback(GObject*, GAsyncResult* result, gpointer data)
680 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
682 if (handle->cancelledOrClientless()) {
683 cleanupSoupRequestOperation(handle.get());
687 ResourceHandleInternal* d = handle->getInternal();
688 SoupMessage* soupMessage = d->m_soupMessage.get();
691 if (d->m_defersLoading) {
692 d->m_deferredResult = result;
696 GOwnPtr<GError> error;
697 GRefPtr<GInputStream> inputStream = adoptGRef(soup_request_send_finish(d->m_soupRequest.get(), result, &error.outPtr()));
699 handle->client()->didFail(handle.get(), ResourceError::httpError(soupMessage, error.get(), d->m_soupRequest.get()));
700 cleanupSoupRequestOperation(handle.get());
705 if (SOUP_STATUS_IS_REDIRECTION(soupMessage->status_code) && shouldRedirect(handle.get())) {
706 d->m_inputStream = inputStream;
707 g_input_stream_skip_async(d->m_inputStream.get(), gDefaultReadBufferSize, G_PRIORITY_DEFAULT,
708 d->m_cancellable.get(), redirectSkipCallback, handle.get());
712 if (handle->shouldContentSniff() && soupMessage->status_code != SOUP_STATUS_NOT_MODIFIED) {
713 const char* sniffedType = soup_request_get_content_type(d->m_soupRequest.get());
714 d->m_response.setSniffedContentType(sniffedType);
716 d->m_response.updateFromSoupMessage(soupMessage);
718 if (handleUnignoredTLSErrors(handle.get())) {
719 cleanupSoupRequestOperation(handle.get());
724 d->m_response.setURL(handle->firstRequest().url());
725 const gchar* contentType = soup_request_get_content_type(d->m_soupRequest.get());
726 d->m_response.setMimeType(extractMIMETypeFromMediaType(contentType));
727 d->m_response.setTextEncodingName(extractCharsetFromMediaType(contentType));
728 d->m_response.setExpectedContentLength(soup_request_get_content_length(d->m_soupRequest.get()));
731 if (soupMessage && d->m_response.isMultipart())
732 d->m_multipartInputStream = adoptGRef(soup_multipart_input_stream_new(soupMessage, inputStream.get()));
734 d->m_inputStream = inputStream;
736 if (d->client()->usesAsyncCallbacks())
737 handle->client()->didReceiveResponseAsync(handle.get(), d->m_response);
739 handle->client()->didReceiveResponse(handle.get(), d->m_response);
740 continueAfterDidReceiveResponse(handle.get());
744 static void continueAfterDidReceiveResponse(ResourceHandle* handle)
746 if (handle->cancelledOrClientless()) {
747 cleanupSoupRequestOperation(handle);
751 ResourceHandleInternal* d = handle->getInternal();
752 if (d->m_soupMessage && d->m_multipartInputStream && !d->m_inputStream) {
753 soup_multipart_input_stream_next_part_async(d->m_multipartInputStream.get(), G_PRIORITY_DEFAULT,
754 d->m_cancellable.get(), nextMultipartResponsePartCallback, handle);
758 ASSERT(d->m_inputStream);
759 handle->ensureReadBuffer();
760 g_input_stream_read_async(d->m_inputStream.get(), const_cast<char*>(d->m_soupBuffer->data), d->m_soupBuffer->length,
761 G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, handle);
764 static bool addFileToSoupMessageBody(SoupMessage* message, const String& fileNameString, size_t offset, size_t lengthToSend, unsigned long& totalBodySize)
766 GOwnPtr<GError> error;
767 CString fileName = fileSystemRepresentation(fileNameString);
768 GMappedFile* fileMapping = g_mapped_file_new(fileName.data(), false, &error.outPtr());
772 gsize bufferLength = lengthToSend;
774 bufferLength = g_mapped_file_get_length(fileMapping);
775 totalBodySize += bufferLength;
777 SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping) + offset,
780 reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
781 soup_message_body_append_buffer(message->request_body, soupBuffer);
782 soup_buffer_free(soupBuffer);
787 static bool blobIsOutOfDate(const BlobDataItem& blobItem)
789 ASSERT(blobItem.type == BlobDataItem::File);
790 if (!isValidFileTime(blobItem.expectedModificationTime))
793 time_t fileModificationTime;
794 if (!getFileModificationTime(blobItem.path, fileModificationTime))
797 return fileModificationTime != static_cast<time_t>(blobItem.expectedModificationTime);
800 static void addEncodedBlobItemToSoupMessageBody(SoupMessage* message, const BlobDataItem& blobItem, unsigned long& totalBodySize)
802 if (blobItem.type == BlobDataItem::Data) {
803 totalBodySize += blobItem.length;
804 soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
805 blobItem.data->data() + blobItem.offset, blobItem.length);
809 ASSERT(blobItem.type == BlobDataItem::File);
810 if (blobIsOutOfDate(blobItem))
813 addFileToSoupMessageBody(message,
816 blobItem.length == BlobDataItem::toEndOfFile ? 0 : blobItem.length,
820 static void addEncodedBlobToSoupMessageBody(SoupMessage* message, const FormDataElement& element, unsigned long& totalBodySize)
822 RefPtr<BlobStorageData> blobData = static_cast<BlobRegistryImpl&>(blobRegistry()).getBlobDataFromURL(URL(ParsedURLString, element.m_url));
826 for (size_t i = 0; i < blobData->items().size(); ++i)
827 addEncodedBlobItemToSoupMessageBody(message, blobData->items()[i], totalBodySize);
829 #endif // ENABLE(BLOB)
831 static bool addFormElementsToSoupMessage(SoupMessage* message, const char*, FormData* httpBody, unsigned long& totalBodySize)
833 soup_message_body_set_accumulate(message->request_body, FALSE);
834 size_t numElements = httpBody->elements().size();
835 for (size_t i = 0; i < numElements; i++) {
836 const FormDataElement& element = httpBody->elements()[i];
838 if (element.m_type == FormDataElement::data) {
839 totalBodySize += element.m_data.size();
840 soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
841 element.m_data.data(), element.m_data.size());
845 if (element.m_type == FormDataElement::encodedFile) {
846 if (!addFileToSoupMessageBody(message ,
849 0 /* lengthToSend */,
856 ASSERT(element.m_type == FormDataElement::encodedBlob);
857 addEncodedBlobToSoupMessageBody(message, element, totalBodySize);
863 #if ENABLE(WEB_TIMING)
864 static int milisecondsSinceRequest(double requestTime)
866 return static_cast<int>((monotonicallyIncreasingTime() - requestTime) * 1000.0);
869 static void wroteBodyCallback(SoupMessage*, gpointer data)
871 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
875 ResourceHandleInternal* d = handle->getInternal();
876 if (!d->m_response.resourceLoadTiming())
879 d->m_response.resourceLoadTiming()->sendEnd = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
882 static void requestStartedCallback(SoupSession*, SoupMessage* soupMessage, SoupSocket*, gpointer)
884 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(G_OBJECT(soupMessage), "handle"));
888 ResourceHandleInternal* d = handle->getInternal();
889 if (!d->m_response.resourceLoadTiming())
892 d->m_response.resourceLoadTiming()->sendStart = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
893 if (d->m_response.resourceLoadTiming()->sslStart != -1) {
894 // WebCore/inspector/front-end/RequestTimingView.js assumes
895 // that SSL time is included in connection time so must
896 // substract here the SSL delta that will be added later (see
897 // WebInspector.RequestTimingView.createTimingTable in the
898 // file above for more details).
899 d->m_response.resourceLoadTiming()->sendStart -=
900 d->m_response.resourceLoadTiming()->sslEnd - d->m_response.resourceLoadTiming()->sslStart;
904 static void networkEventCallback(SoupMessage*, GSocketClientEvent event, GIOStream*, gpointer data)
906 ResourceHandle* handle = static_cast<ResourceHandle*>(data);
910 if (handle->cancelledOrClientless())
913 ResourceHandleInternal* d = handle->getInternal();
914 int deltaTime = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
916 case G_SOCKET_CLIENT_RESOLVING:
917 d->m_response.resourceLoadTiming()->dnsStart = deltaTime;
919 case G_SOCKET_CLIENT_RESOLVED:
920 d->m_response.resourceLoadTiming()->dnsEnd = deltaTime;
922 case G_SOCKET_CLIENT_CONNECTING:
923 d->m_response.resourceLoadTiming()->connectStart = deltaTime;
924 if (d->m_response.resourceLoadTiming()->dnsStart != -1)
925 // WebCore/inspector/front-end/RequestTimingView.js assumes
926 // that DNS time is included in connection time so must
927 // substract here the DNS delta that will be added later (see
928 // WebInspector.RequestTimingView.createTimingTable in the
929 // file above for more details).
930 d->m_response.resourceLoadTiming()->connectStart -=
931 d->m_response.resourceLoadTiming()->dnsEnd - d->m_response.resourceLoadTiming()->dnsStart;
933 case G_SOCKET_CLIENT_CONNECTED:
934 // Web Timing considers that connection time involves dns, proxy & TLS negotiation...
935 // so we better pick G_SOCKET_CLIENT_COMPLETE for connectEnd
937 case G_SOCKET_CLIENT_PROXY_NEGOTIATING:
938 d->m_response.resourceLoadTiming()->proxyStart = deltaTime;
940 case G_SOCKET_CLIENT_PROXY_NEGOTIATED:
941 d->m_response.resourceLoadTiming()->proxyEnd = deltaTime;
943 case G_SOCKET_CLIENT_TLS_HANDSHAKING:
944 d->m_response.resourceLoadTiming()->sslStart = deltaTime;
946 case G_SOCKET_CLIENT_TLS_HANDSHAKED:
947 d->m_response.resourceLoadTiming()->sslEnd = deltaTime;
949 case G_SOCKET_CLIENT_COMPLETE:
950 d->m_response.resourceLoadTiming()->connectEnd = deltaTime;
953 ASSERT_NOT_REACHED();
959 static const char* gSoupRequestInitiatingPageIDKey = "wk-soup-request-initiating-page-id";
961 static void setSoupRequestInitiatingPageIDFromNetworkingContext(SoupRequest* request, NetworkingContext* context)
963 if (!context || !context->isValid())
966 uint64_t* initiatingPageIDPtr = static_cast<uint64_t*>(fastMalloc(sizeof(uint64_t)));
967 *initiatingPageIDPtr = context->initiatingPageID();
968 g_object_set_data_full(G_OBJECT(request), g_intern_static_string(gSoupRequestInitiatingPageIDKey), initiatingPageIDPtr, fastFree);
971 static bool createSoupMessageForHandleAndRequest(ResourceHandle* handle, const ResourceRequest& request)
975 ResourceHandleInternal* d = handle->getInternal();
976 ASSERT(d->m_soupRequest);
978 d->m_soupMessage = adoptGRef(soup_request_http_get_message(SOUP_REQUEST_HTTP(d->m_soupRequest.get())));
979 if (!d->m_soupMessage)
982 SoupMessage* soupMessage = d->m_soupMessage.get();
983 request.updateSoupMessage(soupMessage);
985 g_object_set_data(G_OBJECT(soupMessage), "handle", handle);
986 if (!handle->shouldContentSniff())
987 soup_message_disable_feature(soupMessage, SOUP_TYPE_CONTENT_SNIFFER);
989 FormData* httpBody = request.httpBody();
990 CString contentType = request.httpContentType().utf8().data();
991 if (httpBody && !httpBody->isEmpty() && !addFormElementsToSoupMessage(soupMessage, contentType.data(), httpBody, d->m_bodySize)) {
992 // We failed to prepare the body data, so just fail this load.
993 d->m_soupMessage.clear();
997 // Make sure we have an Accept header for subresources; some sites
998 // want this to serve some of their subresources
999 if (!soup_message_headers_get_one(soupMessage->request_headers, "Accept"))
1000 soup_message_headers_append(soupMessage->request_headers, "Accept", "*/*");
1002 // In the case of XHR .send() and .send("") explicitly tell libsoup to send a zero content-lenght header
1003 // for consistency with other backends (e.g. Chromium's) and other UA implementations like FF. It's done
1004 // in the backend here instead of in XHR code since in XHR CORS checking prevents us from this kind of
1005 // late header manipulation.
1006 if ((request.httpMethod() == "POST" || request.httpMethod() == "PUT")
1007 && (!request.httpBody() || request.httpBody()->isEmpty()))
1008 soup_message_headers_set_content_length(soupMessage->request_headers, 0);
1010 g_signal_connect(d->m_soupMessage.get(), "got-headers", G_CALLBACK(gotHeadersCallback), handle);
1011 g_signal_connect(d->m_soupMessage.get(), "wrote-body-data", G_CALLBACK(wroteBodyDataCallback), handle);
1013 soup_message_set_flags(d->m_soupMessage.get(), static_cast<SoupMessageFlags>(soup_message_get_flags(d->m_soupMessage.get()) | SOUP_MESSAGE_NO_REDIRECT));
1015 #if ENABLE(WEB_TIMING)
1016 d->m_response.setResourceLoadTiming(ResourceLoadTiming::create());
1017 g_signal_connect(d->m_soupMessage.get(), "network-event", G_CALLBACK(networkEventCallback), handle);
1018 g_signal_connect(d->m_soupMessage.get(), "restarted", G_CALLBACK(restartedCallback), handle);
1019 g_signal_connect(d->m_soupMessage.get(), "wrote-body", G_CALLBACK(wroteBodyCallback), handle);
1022 #if SOUP_CHECK_VERSION(2, 43, 1)
1023 soup_message_set_priority(d->m_soupMessage.get(), toSoupMessagePriority(request.priority()));
1029 static bool createSoupRequestAndMessageForHandle(ResourceHandle* handle, const ResourceRequest& request, bool isHTTPFamilyRequest)
1031 ResourceHandleInternal* d = handle->getInternal();
1033 GOwnPtr<GError> error;
1035 GOwnPtr<SoupURI> soupURI(request.soupURI());
1039 d->m_soupRequest = adoptGRef(soup_session_request_uri(d->soupSession(), soupURI.get(), &error.outPtr()));
1041 d->m_soupRequest.clear();
1045 // SoupMessages are only applicable to HTTP-family requests.
1046 if (isHTTPFamilyRequest && !createSoupMessageForHandleAndRequest(handle, request)) {
1047 d->m_soupRequest.clear();
1054 bool ResourceHandle::start()
1056 ASSERT(!d->m_soupMessage);
1058 // The frame could be null if the ResourceHandle is not associated to any
1059 // Frame, e.g. if we are downloading a file.
1060 // If the frame is not null but the page is null this must be an attempted
1061 // load from an unload handler, so let's just block it.
1062 // If both the frame and the page are not null the context is valid.
1063 if (d->m_context && !d->m_context->isValid())
1066 // Only allow the POST and GET methods for non-HTTP requests.
1067 const ResourceRequest& request = firstRequest();
1068 bool isHTTPFamilyRequest = request.url().protocolIsInHTTPFamily();
1069 if (!isHTTPFamilyRequest && request.httpMethod() != "GET" && request.httpMethod() != "POST") {
1070 this->scheduleFailure(InvalidURLFailure); // Error must not be reported immediately
1074 applyAuthenticationToRequest(this, firstRequest(), false);
1076 if (!createSoupRequestAndMessageForHandle(this, request, isHTTPFamilyRequest)) {
1077 this->scheduleFailure(InvalidURLFailure); // Error must not be reported immediately
1081 setSoupRequestInitiatingPageIDFromNetworkingContext(d->m_soupRequest.get(), d->m_context.get());
1083 // Send the request only if it's not been explicitly deferred.
1084 if (!d->m_defersLoading)
1085 sendPendingRequest();
1090 void ResourceHandle::sendPendingRequest()
1092 #if ENABLE(WEB_TIMING)
1093 if (d->m_response.resourceLoadTiming())
1094 d->m_response.resourceLoadTiming()->requestTime = monotonicallyIncreasingTime();
1097 if (d->m_firstRequest.timeoutInterval() > 0) {
1098 // soup_add_timeout returns a GSource* whose only reference is owned by
1099 // the context. We need to have our own reference to it, hence not using adoptRef.
1100 d->m_timeoutSource = soup_add_timeout(g_main_context_get_thread_default(),
1101 d->m_firstRequest.timeoutInterval() * 1000, requestTimeoutCallback, this);
1104 // Balanced by a deref() in cleanupSoupRequestOperation, which should always run.
1107 d->m_cancellable = adoptGRef(g_cancellable_new());
1108 soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, this);
1111 void ResourceHandle::cancel()
1113 d->m_cancelled = true;
1114 if (d->m_soupMessage)
1115 soup_session_cancel_message(d->soupSession(), d->m_soupMessage.get(), SOUP_STATUS_CANCELLED);
1116 else if (d->m_cancellable)
1117 g_cancellable_cancel(d->m_cancellable.get());
1120 bool ResourceHandle::shouldUseCredentialStorage()
1122 return (!client() || client()->shouldUseCredentialStorage(this)) && firstRequest().url().protocolIsInHTTPFamily();
1125 void ResourceHandle::setHostAllowsAnyHTTPSCertificate(const String& host)
1127 allowsAnyHTTPSCertificateHosts().add(host.lower());
1130 void ResourceHandle::setClientCertificate(const String& host, GTlsCertificate* certificate)
1132 clientCertificates().add(host.lower(), HostTLSCertificateSet()).iterator->value.add(certificate);
1135 void ResourceHandle::setIgnoreSSLErrors(bool ignoreSSLErrors)
1137 gIgnoreSSLErrors = ignoreSSLErrors;
1141 void getCredentialFromPersistentStoreCallback(const Credential& credential, void* data)
1143 static_cast<ResourceHandle*>(data)->continueDidReceiveAuthenticationChallenge(credential);
1147 void ResourceHandle::continueDidReceiveAuthenticationChallenge(const Credential& credentialFromPersistentStorage)
1149 ASSERT(!d->m_currentWebChallenge.isNull());
1150 AuthenticationChallenge& challenge = d->m_currentWebChallenge;
1152 ASSERT(challenge.soupSession());
1153 ASSERT(challenge.soupMessage());
1154 if (!credentialFromPersistentStorage.isEmpty())
1155 challenge.setProposedCredential(credentialFromPersistentStorage);
1158 soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1159 clearAuthentication();
1163 ASSERT(challenge.soupSession());
1164 ASSERT(challenge.soupMessage());
1165 client()->didReceiveAuthenticationChallenge(this, challenge);
1168 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
1170 ASSERT(d->m_currentWebChallenge.isNull());
1172 // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly.
1173 bool useCredentialStorage = shouldUseCredentialStorage();
1174 if (useCredentialStorage) {
1175 if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
1176 // The stored credential wasn't accepted, stop using it. There is a race condition
1177 // here, since a different credential might have already been stored by another
1178 // ResourceHandle, but the observable effect should be very minor, if any.
1179 CredentialStorage::remove(challenge.protectionSpace());
1182 if (!challenge.previousFailureCount()) {
1183 Credential credential = CredentialStorage::get(challenge.protectionSpace());
1184 if (!credential.isEmpty() && credential != d->m_initialCredential) {
1185 ASSERT(credential.persistence() == CredentialPersistenceNone);
1187 // Store the credential back, possibly adding it as a default for this directory.
1188 if (isAuthenticationFailureStatusCode(challenge.failureResponse().httpStatusCode()))
1189 CredentialStorage::set(credential, challenge.protectionSpace(), challenge.failureResponse().url());
1191 soup_auth_authenticate(challenge.soupAuth(), credential.user().utf8().data(), credential.password().utf8().data());
1197 d->m_currentWebChallenge = challenge;
1198 soup_session_pause_message(challenge.soupSession(), challenge.soupMessage());
1201 // We could also do this before we even start the request, but that would be at the expense
1202 // of all request latency, versus a one-time latency for the small subset of requests that
1203 // use HTTP authentication. In the end, this doesn't matter much, because persistent credentials
1204 // will become session credentials after the first use.
1205 if (useCredentialStorage) {
1206 credentialBackingStore().credentialForChallenge(challenge, getCredentialFromPersistentStoreCallback, this);
1211 continueDidReceiveAuthenticationChallenge(Credential());
1214 void ResourceHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& challenge)
1216 ASSERT(!challenge.isNull());
1217 if (challenge != d->m_currentWebChallenge)
1219 soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1221 clearAuthentication();
1224 void ResourceHandle::receivedCredential(const AuthenticationChallenge& challenge, const Credential& credential)
1226 ASSERT(!challenge.isNull());
1227 if (challenge != d->m_currentWebChallenge)
1230 // FIXME: Support empty credentials. Currently, an empty credential cannot be stored in WebCore credential storage, as that's empty value for its map.
1231 if (credential.isEmpty()) {
1232 receivedRequestToContinueWithoutCredential(challenge);
1236 if (shouldUseCredentialStorage()) {
1237 // Eventually we will manage per-session credentials only internally or use some newly-exposed API from libsoup,
1238 // because once we authenticate via libsoup, there is no way to ignore it for a particular request. Right now,
1239 // we place the credentials in the store even though libsoup will never fire the authenticate signal again for
1240 // this protection space.
1241 if (credential.persistence() == CredentialPersistenceForSession || credential.persistence() == CredentialPersistencePermanent)
1242 CredentialStorage::set(credential, challenge.protectionSpace(), challenge.failureResponse().url());
1245 if (credential.persistence() == CredentialPersistencePermanent) {
1246 d->m_credentialDataToSaveInPersistentStore.credential = credential;
1247 d->m_credentialDataToSaveInPersistentStore.challenge = challenge;
1252 ASSERT(challenge.soupSession());
1253 ASSERT(challenge.soupMessage());
1254 soup_auth_authenticate(challenge.soupAuth(), credential.user().utf8().data(), credential.password().utf8().data());
1255 soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1257 clearAuthentication();
1260 void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challenge)
1262 ASSERT(!challenge.isNull());
1263 if (challenge != d->m_currentWebChallenge)
1266 soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1269 client()->receivedCancellation(this, challenge);
1271 clearAuthentication();
1274 static bool waitingToSendRequest(ResourceHandle* handle)
1276 // We need to check for d->m_soupRequest because the request may have raised a failure
1277 // (for example invalid URLs). We cannot simply check for d->m_scheduledFailure because
1278 // it's cleared as soon as the failure event is fired.
1279 return handle->getInternal()->m_soupRequest && !handle->getInternal()->m_cancellable;
1282 void ResourceHandle::platformSetDefersLoading(bool defersLoading)
1284 if (cancelledOrClientless())
1287 // Except when canceling a possible timeout timer, we only need to take action here to UN-defer loading.
1288 if (defersLoading) {
1289 if (d->m_timeoutSource) {
1290 g_source_destroy(d->m_timeoutSource.get());
1291 d->m_timeoutSource.clear();
1296 if (waitingToSendRequest(this)) {
1297 sendPendingRequest();
1301 if (d->m_deferredResult) {
1302 GRefPtr<GAsyncResult> asyncResult = adoptGRef(d->m_deferredResult.leakRef());
1304 if (d->m_inputStream)
1305 readCallback(G_OBJECT(d->m_inputStream.get()), asyncResult.get(), this);
1307 sendRequestCallback(G_OBJECT(d->m_soupRequest.get()), asyncResult.get(), this);
1311 bool ResourceHandle::loadsBlocked()
1316 void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
1318 ASSERT(!loadingSynchronousRequest);
1319 if (loadingSynchronousRequest) // In practice this cannot happen, but if for some reason it does,
1320 return; // we want to avoid accidentally going into an infinite loop of requests.
1322 WebCoreSynchronousLoader syncLoader(error, response, sessionFromContext(context), data);
1323 RefPtr<ResourceHandle> handle = create(context, request, &syncLoader, false /*defersLoading*/, false /*shouldContentSniff*/);
1327 // If the request has already failed, do not run the main loop, or else we'll block indefinitely.
1328 if (handle->d->m_scheduledFailureType != NoFailure)
1334 static void readCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
1336 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
1338 if (handle->cancelledOrClientless()) {
1339 cleanupSoupRequestOperation(handle.get());
1343 ResourceHandleInternal* d = handle->getInternal();
1344 if (d->m_defersLoading) {
1345 d->m_deferredResult = asyncResult;
1349 GOwnPtr<GError> error;
1350 gssize bytesRead = g_input_stream_read_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
1353 handle->client()->didFail(handle.get(), ResourceError::genericGError(error.get(), d->m_soupRequest.get()));
1354 cleanupSoupRequestOperation(handle.get());
1359 // If this is a multipart message, we'll look for another part.
1360 if (d->m_soupMessage && d->m_multipartInputStream) {
1361 d->m_inputStream.clear();
1362 soup_multipart_input_stream_next_part_async(d->m_multipartInputStream.get(), G_PRIORITY_DEFAULT,
1363 d->m_cancellable.get(), nextMultipartResponsePartCallback, handle.get());
1367 g_input_stream_close(d->m_inputStream.get(), 0, 0);
1369 handle->client()->didFinishLoading(handle.get(), 0);
1370 cleanupSoupRequestOperation(handle.get());
1374 // It's mandatory to have sent a response before sending data
1375 ASSERT(!d->m_response.isNull());
1377 size_t currentPosition = handle->currentStreamPosition();
1378 size_t encodedDataLength = currentPosition ? currentPosition - d->m_previousPosition : bytesRead;
1380 ASSERT(d->m_soupBuffer);
1381 d->m_soupBuffer->length = bytesRead; // The buffer might be larger than the number of bytes read. SharedBuffer looks at the length property.
1382 handle->client()->didReceiveBuffer(handle.get(), SharedBuffer::wrapSoupBuffer(d->m_soupBuffer.release()), encodedDataLength);
1384 d->m_previousPosition = currentPosition;
1386 // didReceiveBuffer may cancel the load, which may release the last reference.
1387 if (handle->cancelledOrClientless()) {
1388 cleanupSoupRequestOperation(handle.get());
1392 handle->ensureReadBuffer();
1393 g_input_stream_read_async(d->m_inputStream.get(), const_cast<char*>(d->m_soupBuffer->data), d->m_soupBuffer->length, G_PRIORITY_DEFAULT,
1394 d->m_cancellable.get(), readCallback, handle.get());
1397 void ResourceHandle::continueWillSendRequest(const ResourceRequest& request)
1400 ASSERT(client()->usesAsyncCallbacks());
1401 continueAfterWillSendRequest(this, request);
1404 void ResourceHandle::continueDidReceiveResponse()
1407 ASSERT(client()->usesAsyncCallbacks());
1408 continueAfterDidReceiveResponse(this);
1411 void ResourceHandle::continueShouldUseCredentialStorage(bool)
1414 ASSERT(client()->usesAsyncCallbacks());
1415 // FIXME: Implement this method if needed: https://bugs.webkit.org/show_bug.cgi?id=126114.
1418 static gboolean requestTimeoutCallback(gpointer data)
1420 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
1421 handle->client()->didFail(handle.get(), ResourceError::timeoutError(handle->getInternal()->m_firstRequest.url().string()));
1427 static void authenticateCallback(SoupSession* session, SoupMessage* soupMessage, SoupAuth* soupAuth, gboolean retrying)
1429 RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(G_OBJECT(soupMessage), "handle"));
1432 handle->didReceiveAuthenticationChallenge(AuthenticationChallenge(session, soupMessage, soupAuth, retrying, handle.get()));
1435 static SoupSession* createSoupSession()
1437 // Values taken from http://www.browserscope.org/ following
1438 // the rule "Do What Every Other Modern Browser Is Doing". They seem
1439 // to significantly improve page loading time compared to soup's
1441 static const int maxConnections = 35;
1442 static const int maxConnectionsPerHost = 6;
1444 SoupSession* session = soup_session_async_new();
1445 g_object_set(session,
1446 SOUP_SESSION_MAX_CONNS, maxConnections,
1447 SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
1448 SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_DECODER,
1449 SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_SNIFFER,
1450 SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
1451 SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
1453 g_signal_connect(session, "authenticate", G_CALLBACK(authenticateCallback), 0);
1455 #if ENABLE(WEB_TIMING)
1456 g_signal_connect(session, "request-started", G_CALLBACK(requestStartedCallback), 0);
1462 SoupSession* ResourceHandle::defaultSession()
1464 static SoupSession* session = createSoupSession();
1468 SoupSession* ResourceHandle::createTestingSession()
1470 SoupSession* session = createSoupSession();
1471 // The testing session operates with the default cookie jar.
1472 soup_session_add_feature(session, SOUP_SESSION_FEATURE(soupCookieJar()));
1476 SoupSession* ResourceHandle::createPrivateBrowsingSession()
1478 SoupSession* session = createSoupSession();
1479 soup_session_add_feature(session, SOUP_SESSION_FEATURE(createPrivateBrowsingCookieJar()));
1483 uint64_t ResourceHandle::getSoupRequestInitiatingPageID(SoupRequest* request)
1485 uint64_t* initiatingPageIDPtr = static_cast<uint64_t*>(g_object_get_data(G_OBJECT(request), gSoupRequestInitiatingPageIDKey));
1486 return initiatingPageIDPtr ? *initiatingPageIDPtr : 0;