ResourceHandle::willLoadFromCache is evil
[WebKit-https.git] / Source / WebCore / platform / network / soup / ResourceHandleSoup.cpp
1 /*
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 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
12  *
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.
17  *
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.
22  *
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.
27  */
28
29 #include "config.h"
30 #include "ResourceHandle.h"
31
32 #include "CachedResourceLoader.h"
33 #include "ChromeClient.h"
34 #include "CookieJarSoup.h"
35 #include "CredentialStorage.h"
36 #include "FileSystem.h"
37 #include "Frame.h"
38 #include "GOwnPtrSoup.h"
39 #include "HTTPParsers.h"
40 #include "LocalizedStrings.h"
41 #include "Logging.h"
42 #include "MIMETypeRegistry.h"
43 #include "NetworkingContext.h"
44 #include "NotImplemented.h"
45 #include "Page.h"
46 #include "ResourceError.h"
47 #include "ResourceHandleClient.h"
48 #include "ResourceHandleInternal.h"
49 #include "ResourceResponse.h"
50 #include "SharedBuffer.h"
51 #include "SoupURIUtils.h"
52 #include "TextEncoding.h"
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <gio/gio.h>
56 #include <glib.h>
57 #define LIBSOUP_USE_UNSTABLE_REQUEST_API
58 #include <libsoup/soup-multipart-input-stream.h>
59 #include <libsoup/soup-request-http.h>
60 #include <libsoup/soup-requester.h>
61 #include <libsoup/soup.h>
62 #include <sys/stat.h>
63 #include <sys/types.h>
64 #include <unistd.h>
65 #include <wtf/SHA1.h>
66 #include <wtf/gobject/GRefPtr.h>
67 #include <wtf/text/Base64.h>
68 #include <wtf/text/CString.h>
69
70 #if ENABLE(BLOB)
71 #include "BlobData.h"
72 #include "BlobRegistryImpl.h"
73 #include "BlobStorageData.h"
74 #endif
75
76 #if PLATFORM(GTK)
77 #include "CredentialBackingStore.h"
78 #endif
79
80 namespace WebCore {
81
82 #define READ_BUFFER_SIZE 8192
83
84 inline static void soupLogPrinter(SoupLogger*, SoupLoggerLogLevel, char direction, const char* data, gpointer)
85 {
86 #if LOG_DISABLED
87     UNUSED_PARAM(direction);
88     UNUSED_PARAM(data);
89 #endif
90     LOG(Network, "%c %s", direction, data);
91 }
92
93 static bool loadingSynchronousRequest = false;
94
95 class WebCoreSynchronousLoader : public ResourceHandleClient {
96     WTF_MAKE_NONCOPYABLE(WebCoreSynchronousLoader);
97 public:
98
99     WebCoreSynchronousLoader(ResourceError& error, ResourceResponse& response, SoupSession* session, Vector<char>& data)
100         : m_error(error)
101         , m_response(response)
102         , m_session(session)
103         , m_data(data)
104         , m_finished(false)
105     {
106         // We don't want any timers to fire while we are doing our synchronous load
107         // so we replace the thread default main context. The main loop iterations
108         // will only process GSources associated with this inner context.
109         loadingSynchronousRequest = true;
110         GRefPtr<GMainContext> innerMainContext = adoptGRef(g_main_context_new());
111         g_main_context_push_thread_default(innerMainContext.get());
112         m_mainLoop = adoptGRef(g_main_loop_new(innerMainContext.get(), false));
113
114         adjustMaxConnections(1);
115     }
116
117     ~WebCoreSynchronousLoader()
118     {
119         adjustMaxConnections(-1);
120         g_main_context_pop_thread_default(g_main_context_get_thread_default());
121         loadingSynchronousRequest = false;
122     }
123
124     void adjustMaxConnections(int adjustment)
125     {
126         int maxConnections, maxConnectionsPerHost;
127         g_object_get(m_session,
128                      SOUP_SESSION_MAX_CONNS, &maxConnections,
129                      SOUP_SESSION_MAX_CONNS_PER_HOST, &maxConnectionsPerHost,
130                      NULL);
131         maxConnections += adjustment;
132         maxConnectionsPerHost += adjustment;
133         g_object_set(m_session,
134                      SOUP_SESSION_MAX_CONNS, maxConnections,
135                      SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
136                      NULL);
137
138     }
139
140     virtual bool isSynchronousClient()
141     {
142         return true;
143     }
144
145     virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
146     {
147         m_response = response;
148     }
149
150     virtual void didReceiveData(ResourceHandle*, const char* data, int length, int)
151     {
152         m_data.append(data, length);
153     }
154
155     virtual void didFinishLoading(ResourceHandle*, double)
156     {
157         if (g_main_loop_is_running(m_mainLoop.get()))
158             g_main_loop_quit(m_mainLoop.get());
159         m_finished = true;
160     }
161
162     virtual void didFail(ResourceHandle* handle, const ResourceError& error)
163     {
164         m_error = error;
165         didFinishLoading(handle, 0);
166     }
167
168     virtual void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge& challenge)
169     {
170         // We do not handle authentication for synchronous XMLHttpRequests.
171         challenge.authenticationClient()->receivedRequestToContinueWithoutCredential(challenge);
172     }
173
174     void run()
175     {
176         if (!m_finished)
177             g_main_loop_run(m_mainLoop.get());
178     }
179
180 private:
181     ResourceError& m_error;
182     ResourceResponse& m_response;
183     SoupSession* m_session;
184     Vector<char>& m_data;
185     bool m_finished;
186     GRefPtr<GMainLoop> m_mainLoop;
187 };
188
189 class HostTLSCertificateSet {
190 public:
191     void add(GTlsCertificate* certificate)
192     {
193         String certificateHash = computeCertificateHash(certificate);
194         if (!certificateHash.isEmpty())
195             m_certificates.add(certificateHash);
196     }
197
198     bool contains(GTlsCertificate* certificate)
199     {
200         return m_certificates.contains(computeCertificateHash(certificate));
201     }
202
203 private:
204     static String computeCertificateHash(GTlsCertificate* certificate)
205     {
206         GByteArray* data = 0;
207         g_object_get(G_OBJECT(certificate), "certificate", &data, NULL);
208         if (!data)
209             return String();
210
211         static const size_t sha1HashSize = 20;
212         GRefPtr<GByteArray> certificateData = adoptGRef(data);
213         SHA1 sha1;
214         sha1.addBytes(certificateData->data, certificateData->len);
215
216         Vector<uint8_t, sha1HashSize> digest;
217         sha1.computeHash(digest);
218
219         return base64Encode(reinterpret_cast<const char*>(digest.data()), sha1HashSize);
220     }
221
222     HashSet<String> m_certificates;
223 };
224
225 static void cleanupSoupRequestOperation(ResourceHandle*, bool isDestroying);
226 static void sendRequestCallback(GObject*, GAsyncResult*, gpointer);
227 static void readCallback(GObject*, GAsyncResult*, gpointer);
228 static void closeCallback(GObject*, GAsyncResult*, gpointer);
229 static gboolean requestTimeoutCallback(void*);
230 #if ENABLE(WEB_TIMING)
231 static int  milisecondsSinceRequest(double requestTime);
232 #endif
233
234 static bool gIgnoreSSLErrors = false;
235
236 static HashSet<String>& allowsAnyHTTPSCertificateHosts()
237 {
238     DEFINE_STATIC_LOCAL(HashSet<String>, hosts, ());
239     return hosts;
240 }
241
242 typedef HashMap<String, HostTLSCertificateSet> CertificatesMap;
243 static CertificatesMap& clientCertificates()
244 {
245     DEFINE_STATIC_LOCAL(CertificatesMap, certificates, ());
246     return certificates;
247 }
248
249 ResourceHandleInternal::~ResourceHandleInternal()
250 {
251 }
252
253 static SoupSession* sessionFromContext(NetworkingContext* context)
254 {
255     return (context && context->isValid()) ? context->soupSession() : ResourceHandle::defaultSession();
256 }
257
258 ResourceHandle::~ResourceHandle()
259 {
260     cleanupSoupRequestOperation(this, true);
261 }
262
263 static void ensureSessionIsInitialized(SoupSession* session)
264 {
265     if (g_object_get_data(G_OBJECT(session), "webkit-init"))
266         return;
267
268     if (session == ResourceHandle::defaultSession()) {
269         SoupCookieJar* jar = SOUP_COOKIE_JAR(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
270         if (!jar)
271             soup_session_add_feature(session, SOUP_SESSION_FEATURE(soupCookieJar()));
272         else
273             setSoupCookieJar(jar);
274     }
275
276 #if !LOG_DISABLED
277     if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
278         SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
279         soup_session_add_feature(session, SOUP_SESSION_FEATURE(logger));
280         soup_logger_set_printer(logger, soupLogPrinter, 0, 0);
281         g_object_unref(logger);
282     }
283 #endif // !LOG_DISABLED
284
285     if (!soup_session_get_feature(session, SOUP_TYPE_REQUESTER)) {
286         SoupRequester* requester = soup_requester_new();
287         soup_session_add_feature(session, SOUP_SESSION_FEATURE(requester));
288         g_object_unref(requester);
289     }
290
291     g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
292 }
293
294 SoupSession* ResourceHandleInternal::soupSession()
295 {
296     SoupSession* session = sessionFromContext(m_context.get());
297     ensureSessionIsInitialized(session);
298     return session;
299 }
300
301 static bool isAuthenticationFailureStatusCode(int httpStatusCode)
302 {
303     return httpStatusCode == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED || httpStatusCode == SOUP_STATUS_UNAUTHORIZED;
304 }
305
306 static void gotHeadersCallback(SoupMessage* message, gpointer data)
307 {
308     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
309     if (!handle)
310         return;
311     ResourceHandleInternal* d = handle->getInternal();
312     if (d->m_cancelled)
313         return;
314
315 #if ENABLE(WEB_TIMING)
316     if (d->m_response.resourceLoadTiming())
317         d->m_response.resourceLoadTiming()->receiveHeadersEnd = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
318 #endif
319
320 #if PLATFORM(GTK)
321     // We are a bit more conservative with the persistent credential storage than the session store,
322     // since we are waiting until we know that this authentication succeeded before actually storing.
323     // This is because we want to avoid hitting the disk twice (once to add and once to remove) for
324     // incorrect credentials or polluting the keychain with invalid credentials.
325     if (!isAuthenticationFailureStatusCode(message->status_code) && message->status_code < 500 && !d->m_credentialDataToSaveInPersistentStore.credential.isEmpty()) {
326         credentialBackingStore().storeCredentialsForChallenge(
327             d->m_credentialDataToSaveInPersistentStore.challenge,
328             d->m_credentialDataToSaveInPersistentStore.credential);
329     }
330 #endif
331
332     // The original response will be needed later to feed to willSendRequest in
333     // restartedCallback() in case we are redirected. For this reason, so we store it
334     // here.
335     ResourceResponse response;
336     response.updateFromSoupMessage(message);
337     d->m_response = response;
338 }
339
340 static void applyAuthenticationToRequest(ResourceHandle* handle, ResourceRequest& request, bool redirect)
341 {
342     // m_user/m_pass are credentials given manually, for instance, by the arguments passed to XMLHttpRequest.open().
343     ResourceHandleInternal* d = handle->getInternal();
344
345     if (handle->shouldUseCredentialStorage()) {
346         if (d->m_user.isEmpty() && d->m_pass.isEmpty())
347             d->m_initialCredential = CredentialStorage::get(request.url());
348         else if (!redirect) {
349             // If there is already a protection space known for the URL, update stored credentials
350             // before sending a request. This makes it possible to implement logout by sending an
351             // XMLHttpRequest with known incorrect credentials, and aborting it immediately (so that
352             // an authentication dialog doesn't pop up).
353             CredentialStorage::set(Credential(d->m_user, d->m_pass, CredentialPersistenceNone), request.url());
354         }
355     }
356
357     String user = d->m_user;
358     String password = d->m_pass;
359     if (!d->m_initialCredential.isEmpty()) {
360         user = d->m_initialCredential.user();
361         password = d->m_initialCredential.password();
362     }
363
364     if (user.isEmpty() && password.isEmpty())
365         return;
366
367     // We always put the credentials into the URL. In the CFNetwork-port HTTP family credentials are applied in
368     // the didReceiveAuthenticationChallenge callback, but libsoup requires us to use this method to override
369     // any previously remembered credentials. It has its own per-session credential storage.
370     KURL urlWithCredentials(request.url());
371     urlWithCredentials.setUser(user);
372     urlWithCredentials.setPass(password);
373     request.setURL(urlWithCredentials);
374 }
375
376 // Called each time the message is going to be sent again except the first time.
377 // It's used mostly to let webkit know about redirects.
378 static void restartedCallback(SoupMessage* message, gpointer data)
379 {
380     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
381     if (!handle)
382         return;
383     ResourceHandleInternal* d = handle->getInternal();
384     if (d->m_cancelled)
385         return;
386
387     ResourceResponse& redirectResponse = d->m_response;
388 #if ENABLE(WEB_TIMING)
389     redirectResponse.setResourceLoadTiming(ResourceLoadTiming::create());
390     redirectResponse.resourceLoadTiming()->requestTime = monotonicallyIncreasingTime();
391 #endif
392
393     // WebCore only expects us to call willSendRequest when we are redirecting. soup
394     // fires this signal also when it's handling authentication challenges, so in that
395     // case we should not willSendRequest.
396     if (isAuthenticationFailureStatusCode(redirectResponse.httpStatusCode()))
397         return;
398
399     ResourceRequest request = handle->firstRequest();
400     request.setURL(KURL(handle->firstRequest().url(), soupURIToKURL(soup_message_get_uri(message))));
401     request.setHTTPMethod(message->method);
402
403     // Should not set Referer after a redirect from a secure resource to non-secure one.
404     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https")) {
405         request.clearHTTPReferrer();
406         soup_message_headers_remove(message->request_headers, "Referer");
407     }
408
409     const KURL& url = request.url();
410     d->m_user = url.user();
411     d->m_pass = url.pass();
412     request.removeCredentials();
413
414     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
415         // If the network layer carries over authentication headers from the original request
416         // in a cross-origin redirect, we want to clear those headers here. 
417         request.clearHTTPAuthorization();
418         soup_message_headers_remove(message->request_headers, "Authorization");
419
420         // TODO: We are losing any username and password specified in the redirect URL, as this is the 
421         // same behavior as the CFNet port. We should investigate if this is really what we want.
422     } else
423         applyAuthenticationToRequest(handle, request, true);
424
425     // Per-request authentication is handled via the URI-embedded username/password.
426     GOwnPtr<SoupURI> newSoupURI(request.soupURI());
427     soup_message_set_uri(message, newSoupURI.get());
428
429     if (d->client())
430         d->client()->willSendRequest(handle, request, redirectResponse);
431
432     if (d->m_cancelled)
433         return;
434
435     // Update the first party in case the base URL changed with the redirect
436     String firstPartyString = request.firstPartyForCookies().string();
437     if (!firstPartyString.isEmpty()) {
438         GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
439         soup_message_set_first_party(d->m_soupMessage.get(), firstParty.get());
440     }
441 }
442
443 static void wroteBodyDataCallback(SoupMessage*, SoupBuffer* buffer, gpointer data)
444 {
445     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
446     if (!handle)
447         return;
448
449     ASSERT(buffer);
450     ResourceHandleInternal* internal = handle->getInternal();
451     internal->m_bodyDataSent += buffer->length;
452
453     if (internal->m_cancelled)
454         return;
455     ResourceHandleClient* client = handle->client();
456     if (!client)
457         return;
458
459     client->didSendData(handle.get(), internal->m_bodyDataSent, internal->m_bodySize);
460 }
461
462 static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroying = false)
463 {
464     ResourceHandleInternal* d = handle->getInternal();
465
466     d->m_soupRequest.clear();
467     d->m_inputStream.clear();
468     d->m_multipartInputStream.clear();
469     d->m_cancellable.clear();
470
471     if (d->m_soupMessage) {
472         g_signal_handlers_disconnect_matched(d->m_soupMessage.get(), G_SIGNAL_MATCH_DATA,
473                                              0, 0, 0, 0, handle);
474         g_object_set_data(G_OBJECT(d->m_soupMessage.get()), "handle", 0);
475         d->m_soupMessage.clear();
476     }
477
478     if (d->m_buffer) {
479         g_slice_free1(READ_BUFFER_SIZE, d->m_buffer);
480         d->m_buffer = 0;
481     }
482
483     if (d->m_timeoutSource) {
484         g_source_destroy(d->m_timeoutSource.get());
485         d->m_timeoutSource.clear();
486     }
487
488     if (!isDestroying)
489         handle->deref();
490 }
491
492 static bool handleUnignoredTLSErrors(ResourceHandle* handle)
493 {
494     ResourceHandleInternal* d = handle->getInternal();
495     const ResourceResponse& response = d->m_response;
496
497     if (!response.soupMessageTLSErrors() || gIgnoreSSLErrors)
498         return false;
499
500     String lowercaseHostURL = handle->firstRequest().url().host().lower();
501     if (allowsAnyHTTPSCertificateHosts().contains(lowercaseHostURL))
502         return false;
503
504     // We aren't ignoring errors globally, but the user may have already decided to accept this certificate.
505     CertificatesMap::iterator i = clientCertificates().find(lowercaseHostURL);
506     if (i != clientCertificates().end() && i->value.contains(response.soupMessageCertificate()))
507         return false;
508
509     handle->client()->didFail(handle, ResourceError::tlsError(d->m_soupRequest.get(), response.soupMessageTLSErrors(), response.soupMessageCertificate()));
510     return true;
511 }
512
513 static void nextMultipartResponsePartCallback(GObject* /*source*/, GAsyncResult* result, gpointer data)
514 {
515     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
516
517     ResourceHandleInternal* d = handle->getInternal();
518     ResourceHandleClient* client = handle->client();
519
520     if (d->m_cancelled || !client) {
521         cleanupSoupRequestOperation(handle.get());
522         return;
523     }
524
525     ASSERT(!d->m_inputStream);
526
527     GOwnPtr<GError> error;
528     d->m_inputStream = adoptGRef(soup_multipart_input_stream_next_part_finish(d->m_multipartInputStream.get(), result, &error.outPtr()));
529     if (error) {
530         client->didFail(handle.get(), ResourceError::httpError(d->m_soupMessage.get(), error.get(), d->m_soupRequest.get()));
531         cleanupSoupRequestOperation(handle.get());
532         return;
533     }
534
535     if (!d->m_inputStream) {
536         client->didFinishLoading(handle.get(), 0);
537         cleanupSoupRequestOperation(handle.get());
538         return;
539     }
540
541     d->m_response = ResourceResponse();
542     d->m_response.setURL(handle->firstRequest().url());
543     d->m_response.updateFromSoupMessageHeaders(soup_multipart_input_stream_get_headers(d->m_multipartInputStream.get()));
544
545     client->didReceiveResponse(handle.get(), d->m_response);
546
547     if (d->m_cancelled || !client) {
548         cleanupSoupRequestOperation(handle.get());
549         return;
550     }
551
552     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
553         G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, handle.get());
554 }
555
556 static void sendRequestCallback(GObject*, GAsyncResult* result, gpointer data)
557 {
558     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
559
560     ResourceHandleInternal* d = handle->getInternal();
561     ResourceHandleClient* client = handle->client();
562     SoupMessage* soupMessage = d->m_soupMessage.get();
563
564     if (d->m_cancelled || !client) {
565         cleanupSoupRequestOperation(handle.get());
566         return;
567     }
568
569     if (d->m_defersLoading) {
570         d->m_deferredResult = result;
571         return;
572     }
573
574     GOwnPtr<GError> error;
575     GRefPtr<GInputStream> inputStream = adoptGRef(soup_request_send_finish(d->m_soupRequest.get(), result, &error.outPtr()));
576     if (error) {
577         client->didFail(handle.get(), ResourceError::httpError(soupMessage, error.get(), d->m_soupRequest.get()));
578         cleanupSoupRequestOperation(handle.get());
579         return;
580     }
581
582     d->m_buffer = static_cast<char*>(g_slice_alloc(READ_BUFFER_SIZE));
583
584     if (soupMessage) {
585         if (handle->shouldContentSniff() && soupMessage->status_code != SOUP_STATUS_NOT_MODIFIED) {
586             const char* sniffedType = soup_request_get_content_type(d->m_soupRequest.get());
587             d->m_response.setSniffedContentType(sniffedType);
588         }
589         d->m_response.updateFromSoupMessage(soupMessage);
590
591         if (handleUnignoredTLSErrors(handle.get())) {
592             cleanupSoupRequestOperation(handle.get());
593             return;
594         }
595
596     } else {
597         d->m_response.setURL(handle->firstRequest().url());
598         const gchar* contentType = soup_request_get_content_type(d->m_soupRequest.get());
599         d->m_response.setMimeType(extractMIMETypeFromMediaType(contentType));
600         d->m_response.setTextEncodingName(extractCharsetFromMediaType(contentType));
601         d->m_response.setExpectedContentLength(soup_request_get_content_length(d->m_soupRequest.get()));
602     }
603
604     client->didReceiveResponse(handle.get(), d->m_response);
605
606     if (d->m_cancelled) {
607         cleanupSoupRequestOperation(handle.get());
608         return;
609     }
610
611     if (soupMessage && d->m_response.isMultipart()) {
612         d->m_multipartInputStream = adoptGRef(soup_multipart_input_stream_new(soupMessage, inputStream.get()));
613         soup_multipart_input_stream_next_part_async(d->m_multipartInputStream.get(), G_PRIORITY_DEFAULT,
614             d->m_cancellable.get(), nextMultipartResponsePartCallback, handle.get());
615         return;
616     }
617
618     d->m_inputStream = inputStream;
619     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
620                               G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, handle.get());
621 }
622
623 static bool addFileToSoupMessageBody(SoupMessage* message, const String& fileNameString, size_t offset, size_t lengthToSend, unsigned long& totalBodySize)
624 {
625     GOwnPtr<GError> error;
626     CString fileName = fileSystemRepresentation(fileNameString);
627     GMappedFile* fileMapping = g_mapped_file_new(fileName.data(), false, &error.outPtr());
628     if (error)
629         return false;
630
631     gsize bufferLength = lengthToSend;
632     if (!lengthToSend)
633         bufferLength = g_mapped_file_get_length(fileMapping);
634     totalBodySize += bufferLength;
635
636     SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping) + offset,
637                                                         bufferLength,
638                                                         fileMapping,
639                                                         reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
640     soup_message_body_append_buffer(message->request_body, soupBuffer);
641     soup_buffer_free(soupBuffer);
642     return true;
643 }
644
645 #if ENABLE(BLOB)
646 static bool blobIsOutOfDate(const BlobDataItem& blobItem)
647 {
648     ASSERT(blobItem.type == BlobDataItem::File);
649     if (!isValidFileTime(blobItem.expectedModificationTime))
650         return false;
651
652     time_t fileModificationTime;
653     if (!getFileModificationTime(blobItem.path, fileModificationTime))
654         return true;
655
656     return fileModificationTime != static_cast<time_t>(blobItem.expectedModificationTime);
657 }
658
659 static void addEncodedBlobItemToSoupMessageBody(SoupMessage* message, const BlobDataItem& blobItem, unsigned long& totalBodySize)
660 {
661     if (blobItem.type == BlobDataItem::Data) {
662         totalBodySize += blobItem.length;
663         soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
664                                  blobItem.data->data() + blobItem.offset, blobItem.length);
665         return;
666     }
667
668     ASSERT(blobItem.type == BlobDataItem::File);
669     if (blobIsOutOfDate(blobItem))
670         return;
671
672     addFileToSoupMessageBody(message,
673                              blobItem.path,
674                              blobItem.offset,
675                              blobItem.length == BlobDataItem::toEndOfFile ? 0 : blobItem.length,
676                              totalBodySize);
677 }
678
679 static void addEncodedBlobToSoupMessageBody(SoupMessage* message, const FormDataElement& element, unsigned long& totalBodySize)
680 {
681     RefPtr<BlobStorageData> blobData = static_cast<BlobRegistryImpl&>(blobRegistry()).getBlobDataFromURL(KURL(ParsedURLString, element.m_url));
682     if (!blobData)
683         return;
684
685     for (size_t i = 0; i < blobData->items().size(); ++i)
686         addEncodedBlobItemToSoupMessageBody(message, blobData->items()[i], totalBodySize);
687 }
688 #endif // ENABLE(BLOB)
689
690 static bool addFormElementsToSoupMessage(SoupMessage* message, const char*, FormData* httpBody, unsigned long& totalBodySize)
691 {
692     soup_message_body_set_accumulate(message->request_body, FALSE);
693     size_t numElements = httpBody->elements().size();
694     for (size_t i = 0; i < numElements; i++) {
695         const FormDataElement& element = httpBody->elements()[i];
696
697         if (element.m_type == FormDataElement::data) {
698             totalBodySize += element.m_data.size();
699             soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
700                                      element.m_data.data(), element.m_data.size());
701             continue;
702         }
703
704         if (element.m_type == FormDataElement::encodedFile) {
705             if (!addFileToSoupMessageBody(message ,
706                                          element.m_filename,
707                                          0 /* offset */,
708                                          0 /* lengthToSend */,
709                                          totalBodySize))
710                 return false;
711             continue;
712         }
713
714 #if ENABLE(BLOB)
715         ASSERT(element.m_type == FormDataElement::encodedBlob);
716         addEncodedBlobToSoupMessageBody(message, element, totalBodySize);
717 #endif
718     }
719     return true;
720 }
721
722 #if ENABLE(WEB_TIMING)
723 static int milisecondsSinceRequest(double requestTime)
724 {
725     return static_cast<int>((monotonicallyIncreasingTime() - requestTime) * 1000.0);
726 }
727
728 static void wroteBodyCallback(SoupMessage*, gpointer data)
729 {
730     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
731     if (!handle)
732         return;
733
734     ResourceHandleInternal* d = handle->getInternal();
735     if (!d->m_response.resourceLoadTiming())
736         return;
737
738     d->m_response.resourceLoadTiming()->sendEnd = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
739 }
740
741 static void requestStartedCallback(SoupSession*, SoupMessage* soupMessage, SoupSocket*, gpointer)
742 {
743     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(G_OBJECT(soupMessage), "handle"));
744     if (!handle)
745         return;
746
747     ResourceHandleInternal* d = handle->getInternal();
748     if (!d->m_response.resourceLoadTiming())
749         return;
750
751     d->m_response.resourceLoadTiming()->sendStart = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
752     if (d->m_response.resourceLoadTiming()->sslStart != -1) {
753         // WebCore/inspector/front-end/RequestTimingView.js assumes
754         // that SSL time is included in connection time so must
755         // substract here the SSL delta that will be added later (see
756         // WebInspector.RequestTimingView.createTimingTable in the
757         // file above for more details).
758         d->m_response.resourceLoadTiming()->sendStart -=
759             d->m_response.resourceLoadTiming()->sslEnd - d->m_response.resourceLoadTiming()->sslStart;
760     }
761 }
762
763 static void networkEventCallback(SoupMessage*, GSocketClientEvent event, GIOStream*, gpointer data)
764 {
765     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
766     if (!handle)
767         return;
768     ResourceHandleInternal* d = handle->getInternal();
769     if (d->m_cancelled)
770         return;
771
772     int deltaTime = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
773     switch (event) {
774     case G_SOCKET_CLIENT_RESOLVING:
775         d->m_response.resourceLoadTiming()->dnsStart = deltaTime;
776         break;
777     case G_SOCKET_CLIENT_RESOLVED:
778         d->m_response.resourceLoadTiming()->dnsEnd = deltaTime;
779         break;
780     case G_SOCKET_CLIENT_CONNECTING:
781         d->m_response.resourceLoadTiming()->connectStart = deltaTime;
782         if (d->m_response.resourceLoadTiming()->dnsStart != -1)
783             // WebCore/inspector/front-end/RequestTimingView.js assumes
784             // that DNS time is included in connection time so must
785             // substract here the DNS delta that will be added later (see
786             // WebInspector.RequestTimingView.createTimingTable in the
787             // file above for more details).
788             d->m_response.resourceLoadTiming()->connectStart -=
789                 d->m_response.resourceLoadTiming()->dnsEnd - d->m_response.resourceLoadTiming()->dnsStart;
790         break;
791     case G_SOCKET_CLIENT_CONNECTED:
792         // Web Timing considers that connection time involves dns, proxy & TLS negotiation...
793         // so we better pick G_SOCKET_CLIENT_COMPLETE for connectEnd
794         break;
795     case G_SOCKET_CLIENT_PROXY_NEGOTIATING:
796         d->m_response.resourceLoadTiming()->proxyStart = deltaTime;
797         break;
798     case G_SOCKET_CLIENT_PROXY_NEGOTIATED:
799         d->m_response.resourceLoadTiming()->proxyEnd = deltaTime;
800         break;
801     case G_SOCKET_CLIENT_TLS_HANDSHAKING:
802         d->m_response.resourceLoadTiming()->sslStart = deltaTime;
803         break;
804     case G_SOCKET_CLIENT_TLS_HANDSHAKED:
805         d->m_response.resourceLoadTiming()->sslEnd = deltaTime;
806         break;
807     case G_SOCKET_CLIENT_COMPLETE:
808         d->m_response.resourceLoadTiming()->connectEnd = deltaTime;
809         break;
810     default:
811         ASSERT_NOT_REACHED();
812         break;
813     }
814 }
815 #endif
816
817 static const char* gSoupRequestInitiatingPageIDKey = "wk-soup-request-initiating-page-id";
818
819 static void setSoupRequestInitiatingPageIDFromNetworkingContext(SoupRequest* request, NetworkingContext* context)
820 {
821     if (!context || !context->isValid())
822         return;
823
824     uint64_t* initiatingPageIDPtr = static_cast<uint64_t*>(fastMalloc(sizeof(uint64_t)));
825     *initiatingPageIDPtr = context->initiatingPageID();
826     g_object_set_data_full(G_OBJECT(request), g_intern_static_string(gSoupRequestInitiatingPageIDKey), initiatingPageIDPtr, fastFree);
827 }
828
829 static bool createSoupMessageForHandleAndRequest(ResourceHandle* handle, const ResourceRequest& request)
830 {
831     ASSERT(handle);
832
833     ResourceHandleInternal* d = handle->getInternal();
834     ASSERT(d->m_soupRequest);
835
836     d->m_soupMessage = adoptGRef(soup_request_http_get_message(SOUP_REQUEST_HTTP(d->m_soupRequest.get())));
837     if (!d->m_soupMessage)
838         return false;
839
840     SoupMessage* soupMessage = d->m_soupMessage.get();
841     request.updateSoupMessage(soupMessage);
842
843     g_object_set_data(G_OBJECT(soupMessage), "handle", handle);
844     if (!handle->shouldContentSniff())
845         soup_message_disable_feature(soupMessage, SOUP_TYPE_CONTENT_SNIFFER);
846
847     String firstPartyString = request.firstPartyForCookies().string();
848     if (!firstPartyString.isEmpty()) {
849         GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
850         soup_message_set_first_party(soupMessage, firstParty.get());
851     }
852
853     FormData* httpBody = request.httpBody();
854     CString contentType = request.httpContentType().utf8().data();
855     if (httpBody && !httpBody->isEmpty() && !addFormElementsToSoupMessage(soupMessage, contentType.data(), httpBody, d->m_bodySize)) {
856         // We failed to prepare the body data, so just fail this load.
857         d->m_soupMessage.clear();
858         return false;
859     }
860
861     // Make sure we have an Accept header for subresources; some sites
862     // want this to serve some of their subresources
863     if (!soup_message_headers_get_one(soupMessage->request_headers, "Accept"))
864         soup_message_headers_append(soupMessage->request_headers, "Accept", "*/*");
865
866     // In the case of XHR .send() and .send("") explicitly tell libsoup to send a zero content-lenght header
867     // for consistency with other backends (e.g. Chromium's) and other UA implementations like FF. It's done
868     // in the backend here instead of in XHR code since in XHR CORS checking prevents us from this kind of
869     // late header manipulation.
870     if ((request.httpMethod() == "POST" || request.httpMethod() == "PUT")
871         && (!request.httpBody() || request.httpBody()->isEmpty()))
872         soup_message_headers_set_content_length(soupMessage->request_headers, 0);
873
874     g_signal_connect(d->m_soupMessage.get(), "got-headers", G_CALLBACK(gotHeadersCallback), handle);
875     g_signal_connect(d->m_soupMessage.get(), "restarted", G_CALLBACK(restartedCallback), handle);
876     g_signal_connect(d->m_soupMessage.get(), "wrote-body-data", G_CALLBACK(wroteBodyDataCallback), handle);
877
878 #if ENABLE(WEB_TIMING)
879     d->m_response.setResourceLoadTiming(ResourceLoadTiming::create());
880     g_signal_connect(d->m_soupMessage.get(), "network-event", G_CALLBACK(networkEventCallback), handle);
881     g_signal_connect(d->m_soupMessage.get(), "wrote-body", G_CALLBACK(wroteBodyCallback), handle);
882 #endif
883
884     return true;
885 }
886
887 static bool createSoupRequestAndMessageForHandle(ResourceHandle* handle, bool isHTTPFamilyRequest)
888 {
889     ResourceHandleInternal* d = handle->getInternal();
890     SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(d->soupSession(), SOUP_TYPE_REQUESTER));
891
892     GOwnPtr<GError> error;
893     ResourceRequest& request = handle->firstRequest();
894
895     GOwnPtr<SoupURI> soupURI(request.soupURI());
896     d->m_soupRequest = adoptGRef(soup_requester_request_uri(requester, soupURI.get(), &error.outPtr()));
897     if (error) {
898         d->m_soupRequest.clear();
899         return false;
900     }
901
902     // SoupMessages are only applicable to HTTP-family requests.
903     if (isHTTPFamilyRequest && !createSoupMessageForHandleAndRequest(handle, request)) {
904         d->m_soupRequest.clear();
905         return false;
906     }
907
908     return true;
909 }
910
911 bool ResourceHandle::start(NetworkingContext* context)
912 {
913     ASSERT(!d->m_soupMessage);
914
915     // The frame could be null if the ResourceHandle is not associated to any
916     // Frame, e.g. if we are downloading a file.
917     // If the frame is not null but the page is null this must be an attempted
918     // load from an unload handler, so let's just block it.
919     // If both the frame and the page are not null the context is valid.
920     if (context && !context->isValid())
921         return false;
922
923     // Used to set the keep track of custom SoupSessions for ports that support it (EFL).
924     d->m_context = context;
925
926     // Only allow the POST and GET methods for non-HTTP requests.
927     const ResourceRequest& request = firstRequest();
928     bool isHTTPFamilyRequest = request.url().protocolIsInHTTPFamily();
929     if (!isHTTPFamilyRequest && request.httpMethod() != "GET" && request.httpMethod() != "POST") {
930         this->scheduleFailure(InvalidURLFailure); // Error must not be reported immediately
931         return true;
932     }
933
934     applyAuthenticationToRequest(this, firstRequest(), false);
935
936     if (!createSoupRequestAndMessageForHandle(this, isHTTPFamilyRequest)) {
937         this->scheduleFailure(InvalidURLFailure); // Error must not be reported immediately
938         return true;
939     }
940
941     setSoupRequestInitiatingPageIDFromNetworkingContext(d->m_soupRequest.get(), context);
942
943     // Send the request only if it's not been explicitly deferred.
944     if (!d->m_defersLoading)
945         sendPendingRequest();
946
947     return true;
948 }
949
950 void ResourceHandle::sendPendingRequest()
951 {
952 #if ENABLE(WEB_TIMING)
953     if (d->m_response.resourceLoadTiming())
954         d->m_response.resourceLoadTiming()->requestTime = monotonicallyIncreasingTime();
955 #endif
956
957     if (d->m_firstRequest.timeoutInterval() > 0) {
958         // soup_add_timeout returns a GSource* whose only reference is owned by
959         // the context. We need to have our own reference to it, hence not using adoptRef.
960         d->m_timeoutSource = soup_add_timeout(g_main_context_get_thread_default(),
961             d->m_firstRequest.timeoutInterval() * 1000, requestTimeoutCallback, this);
962     }
963
964     // Balanced by a deref() in cleanupSoupRequestOperation, which should always run.
965     ref();
966
967     d->m_cancellable = adoptGRef(g_cancellable_new());
968     soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, this);
969 }
970
971 void ResourceHandle::cancel()
972 {
973     d->m_cancelled = true;
974     if (d->m_soupMessage)
975         soup_session_cancel_message(d->soupSession(), d->m_soupMessage.get(), SOUP_STATUS_CANCELLED);
976     else if (d->m_cancellable)
977         g_cancellable_cancel(d->m_cancellable.get());
978 }
979
980 bool ResourceHandle::shouldUseCredentialStorage()
981 {
982     return (!client() || client()->shouldUseCredentialStorage(this)) && firstRequest().url().protocolIsInHTTPFamily();
983 }
984
985 void ResourceHandle::setHostAllowsAnyHTTPSCertificate(const String& host)
986 {
987     allowsAnyHTTPSCertificateHosts().add(host.lower());
988 }
989
990 void ResourceHandle::setClientCertificate(const String& host, GTlsCertificate* certificate)
991 {
992     clientCertificates().add(host.lower(), HostTLSCertificateSet()).iterator->value.add(certificate);
993 }
994
995 void ResourceHandle::setIgnoreSSLErrors(bool ignoreSSLErrors)
996 {
997     gIgnoreSSLErrors = ignoreSSLErrors;
998 }
999
1000 #if PLATFORM(GTK)
1001 void getCredentialFromPersistentStoreCallback(const Credential& credential, void* data)
1002 {
1003     static_cast<ResourceHandle*>(data)->continueDidReceiveAuthenticationChallenge(credential);
1004 }
1005 #endif
1006
1007 void ResourceHandle::continueDidReceiveAuthenticationChallenge(const Credential& credentialFromPersistentStorage)
1008 {
1009     ASSERT(!d->m_currentWebChallenge.isNull());
1010     AuthenticationChallenge& challenge = d->m_currentWebChallenge;
1011
1012     ASSERT(challenge.soupSession());
1013     ASSERT(challenge.soupMessage());
1014     if (!credentialFromPersistentStorage.isEmpty())
1015         challenge.setProposedCredential(credentialFromPersistentStorage);
1016
1017     if (!client()) {
1018         soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1019         clearAuthentication();
1020         return;
1021     }
1022
1023     ASSERT(challenge.soupSession());
1024     ASSERT(challenge.soupMessage());
1025     client()->didReceiveAuthenticationChallenge(this, challenge);
1026 }
1027
1028 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
1029 {
1030     ASSERT(d->m_currentWebChallenge.isNull());
1031
1032     // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly.
1033     bool useCredentialStorage = shouldUseCredentialStorage();
1034     if (useCredentialStorage) {
1035         if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
1036             // The stored credential wasn't accepted, stop using it. There is a race condition
1037             // here, since a different credential might have already been stored by another
1038             // ResourceHandle, but the observable effect should be very minor, if any.
1039             CredentialStorage::remove(challenge.protectionSpace());
1040         }
1041
1042         if (!challenge.previousFailureCount()) {
1043             Credential credential = CredentialStorage::get(challenge.protectionSpace());
1044             if (!credential.isEmpty() && credential != d->m_initialCredential) {
1045                 ASSERT(credential.persistence() == CredentialPersistenceNone);
1046
1047                 // Store the credential back, possibly adding it as a default for this directory.
1048                 if (isAuthenticationFailureStatusCode(challenge.failureResponse().httpStatusCode()))
1049                     CredentialStorage::set(credential, challenge.protectionSpace(), challenge.failureResponse().url());
1050
1051                 soup_auth_authenticate(challenge.soupAuth(), credential.user().utf8().data(), credential.password().utf8().data());
1052                 return;
1053             }
1054         }
1055     }
1056
1057     d->m_currentWebChallenge = challenge;
1058     soup_session_pause_message(challenge.soupSession(), challenge.soupMessage());
1059
1060 #if PLATFORM(GTK)
1061     // We could also do this before we even start the request, but that would be at the expense
1062     // of all request latency, versus a one-time latency for the small subset of requests that
1063     // use HTTP authentication. In the end, this doesn't matter much, because persistent credentials
1064     // will become session credentials after the first use.
1065     if (useCredentialStorage) {
1066         credentialBackingStore().credentialForChallenge(challenge, getCredentialFromPersistentStoreCallback, this);
1067         return;
1068     }
1069 #endif
1070
1071     continueDidReceiveAuthenticationChallenge(Credential());
1072 }
1073
1074 void ResourceHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& challenge)
1075 {
1076     ASSERT(!challenge.isNull());
1077     if (challenge != d->m_currentWebChallenge)
1078         return;
1079     soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1080
1081     clearAuthentication();
1082 }
1083
1084 void ResourceHandle::receivedCredential(const AuthenticationChallenge& challenge, const Credential& credential)
1085 {
1086     ASSERT(!challenge.isNull());
1087     if (challenge != d->m_currentWebChallenge)
1088         return;
1089
1090     // FIXME: Support empty credentials. Currently, an empty credential cannot be stored in WebCore credential storage, as that's empty value for its map.
1091     if (credential.isEmpty()) {
1092         receivedRequestToContinueWithoutCredential(challenge);
1093         return;
1094     }
1095
1096     if (shouldUseCredentialStorage()) {
1097         // Eventually we will manage per-session credentials only internally or use some newly-exposed API from libsoup,
1098         // because once we authenticate via libsoup, there is no way to ignore it for a particular request. Right now,
1099         // we place the credentials in the store even though libsoup will never fire the authenticate signal again for
1100         // this protection space.
1101         if (credential.persistence() == CredentialPersistenceForSession || credential.persistence() == CredentialPersistencePermanent)
1102             CredentialStorage::set(credential, challenge.protectionSpace(), challenge.failureResponse().url());
1103
1104 #if PLATFORM(GTK)
1105         if (credential.persistence() == CredentialPersistencePermanent) {
1106             d->m_credentialDataToSaveInPersistentStore.credential = credential;
1107             d->m_credentialDataToSaveInPersistentStore.challenge = challenge;
1108         }
1109 #endif
1110     }
1111
1112     ASSERT(challenge.soupSession());
1113     ASSERT(challenge.soupMessage());
1114     soup_auth_authenticate(challenge.soupAuth(), credential.user().utf8().data(), credential.password().utf8().data());
1115     soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1116
1117     clearAuthentication();
1118 }
1119
1120 void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challenge)
1121 {
1122     ASSERT(!challenge.isNull());
1123     if (challenge != d->m_currentWebChallenge)
1124         return;
1125
1126     soup_session_unpause_message(challenge.soupSession(), challenge.soupMessage());
1127
1128     if (client())
1129         client()->receivedCancellation(this, challenge);
1130
1131     clearAuthentication();
1132 }
1133
1134 static bool waitingToSendRequest(ResourceHandle* handle)
1135 {
1136     // We need to check for d->m_soupRequest because the request may have raised a failure
1137     // (for example invalid URLs). We cannot  simply check for d->m_scheduledFailure because
1138     // it's cleared as soon as the failure event is fired.
1139     return handle->getInternal()->m_soupRequest && !handle->getInternal()->m_cancellable;
1140 }
1141
1142 void ResourceHandle::platformSetDefersLoading(bool defersLoading)
1143 {
1144     if (d->m_cancelled)
1145         return;
1146
1147     // Except when canceling a possible timeout timer, we only need to take action here to UN-defer loading.
1148     if (defersLoading) {
1149         if (d->m_timeoutSource) {
1150             g_source_destroy(d->m_timeoutSource.get());
1151             d->m_timeoutSource.clear();
1152         }
1153         return;
1154     }
1155
1156     if (waitingToSendRequest(this)) {
1157         sendPendingRequest();
1158         return;
1159     }
1160
1161     if (d->m_deferredResult) {
1162         GRefPtr<GAsyncResult> asyncResult = adoptGRef(d->m_deferredResult.leakRef());
1163
1164         if (d->m_inputStream)
1165             readCallback(G_OBJECT(d->m_inputStream.get()), asyncResult.get(), this);
1166         else
1167             sendRequestCallback(G_OBJECT(d->m_soupRequest.get()), asyncResult.get(), this);
1168     }
1169 }
1170
1171 bool ResourceHandle::loadsBlocked()
1172 {
1173     return false;
1174 }
1175
1176 void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
1177 {
1178 #if ENABLE(BLOB)
1179     if (request.url().protocolIs("blob")) {
1180         blobRegistry().loadResourceSynchronously(request, error, response, data);
1181         return;
1182     }
1183 #endif
1184  
1185     ASSERT(!loadingSynchronousRequest);
1186     if (loadingSynchronousRequest) // In practice this cannot happen, but if for some reason it does,
1187         return;                    // we want to avoid accidentally going into an infinite loop of requests.
1188
1189     WebCoreSynchronousLoader syncLoader(error, response, sessionFromContext(context), data);
1190     RefPtr<ResourceHandle> handle = create(context, request, &syncLoader, false /*defersLoading*/, false /*shouldContentSniff*/);
1191     if (!handle)
1192         return;
1193
1194     // If the request has already failed, do not run the main loop, or else we'll block indefinitely.
1195     if (handle->d->m_scheduledFailureType != NoFailure)
1196         return;
1197
1198     syncLoader.run();
1199 }
1200
1201 static void closeCallback(GObject*, GAsyncResult* res, gpointer data)
1202 {
1203     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
1204     ResourceHandleInternal* d = handle->getInternal();
1205
1206     g_input_stream_close_finish(d->m_inputStream.get(), res, 0);
1207
1208     ResourceHandleClient* client = handle->client();
1209     if (client && loadingSynchronousRequest)
1210         client->didFinishLoading(handle.get(), 0);
1211
1212     cleanupSoupRequestOperation(handle.get());
1213 }
1214
1215 static void readCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
1216 {
1217     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
1218
1219     ResourceHandleInternal* d = handle->getInternal();
1220     ResourceHandleClient* client = handle->client();
1221
1222     if (d->m_cancelled || !client) {
1223         cleanupSoupRequestOperation(handle.get());
1224         return;
1225     }
1226
1227     if (d->m_defersLoading) {
1228         d->m_deferredResult = asyncResult;
1229         return;
1230     }
1231
1232     GOwnPtr<GError> error;
1233     gssize bytesRead = g_input_stream_read_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
1234     if (error) {
1235         client->didFail(handle.get(), ResourceError::genericIOError(error.get(), d->m_soupRequest.get()));
1236         cleanupSoupRequestOperation(handle.get());
1237         return;
1238     }
1239
1240     if (!bytesRead) {
1241         // If this is a multipart message, we'll look for another part.
1242         if (d->m_soupMessage && d->m_multipartInputStream) {
1243             d->m_inputStream.clear();
1244             soup_multipart_input_stream_next_part_async(d->m_multipartInputStream.get(), G_PRIORITY_DEFAULT,
1245                 d->m_cancellable.get(), nextMultipartResponsePartCallback, handle.get());
1246             return;
1247         }
1248
1249         // We inform WebCore of load completion now instead of waiting for the input
1250         // stream to close because the input stream is closed asynchronously. If this
1251         // is a synchronous request, we wait until the closeCallback, because we don't
1252         // want to halt the internal main loop before the input stream closes.
1253         if (client && !loadingSynchronousRequest) {
1254             client->didFinishLoading(handle.get(), 0);
1255             handle->setClient(0); // Unset the client so that we do not try to access th
1256                                   // client in the closeCallback.
1257         }
1258         g_input_stream_close_async(d->m_inputStream.get(), G_PRIORITY_DEFAULT, 0, closeCallback, handle.get());
1259         return;
1260     }
1261
1262     // It's mandatory to have sent a response before sending data
1263     ASSERT(!d->m_response.isNull());
1264
1265     client->didReceiveData(handle.get(), d->m_buffer, bytesRead, bytesRead);
1266
1267     // didReceiveData may cancel the load, which may release the last reference.
1268     if (d->m_cancelled || !client) {
1269         cleanupSoupRequestOperation(handle.get());
1270         return;
1271     }
1272
1273     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE, G_PRIORITY_DEFAULT,
1274                               d->m_cancellable.get(), readCallback, handle.get());
1275 }
1276
1277 static gboolean requestTimeoutCallback(gpointer data)
1278 {
1279     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
1280     handle->client()->didFail(handle.get(), ResourceError::timeoutError(handle->getInternal()->m_firstRequest.url().string()));
1281     handle->cancel();
1282
1283     return FALSE;
1284 }
1285
1286 static void authenticateCallback(SoupSession* session, SoupMessage* soupMessage, SoupAuth* soupAuth, gboolean retrying)
1287 {
1288     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(G_OBJECT(soupMessage), "handle"));
1289     if (!handle)
1290         return;
1291     handle->didReceiveAuthenticationChallenge(AuthenticationChallenge(session, soupMessage, soupAuth, retrying, handle.get()));
1292 }
1293
1294 SoupSession* ResourceHandle::defaultSession()
1295 {
1296     static SoupSession* session = 0;
1297     // Values taken from http://www.browserscope.org/  following
1298     // the rule "Do What Every Other Modern Browser Is Doing". They seem
1299     // to significantly improve page loading time compared to soup's
1300     // default values.
1301     static const int maxConnections = 35;
1302     static const int maxConnectionsPerHost = 6;
1303
1304     if (!session) {
1305         session = soup_session_async_new();
1306         g_object_set(session,
1307                      SOUP_SESSION_MAX_CONNS, maxConnections,
1308                      SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
1309                      SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_DECODER,
1310                      SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_SNIFFER,
1311                      SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
1312                      SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
1313                      NULL);
1314         g_signal_connect(session, "authenticate", G_CALLBACK(authenticateCallback), 0);
1315
1316 #if ENABLE(WEB_TIMING)
1317         g_signal_connect(session, "request-started", G_CALLBACK(requestStartedCallback), 0);
1318 #endif
1319     }
1320
1321     return session;
1322 }
1323
1324 uint64_t ResourceHandle::getSoupRequestInitiatingPageID(SoupRequest* request)
1325 {
1326     uint64_t* initiatingPageIDPtr = static_cast<uint64_t*>(g_object_get_data(G_OBJECT(request), gSoupRequestInitiatingPageIDKey));
1327     return initiatingPageIDPtr ? *initiatingPageIDPtr : 0;
1328 }
1329
1330 }