[Soup] Simplify the way that requests are started
[WebKit-https.git] / Source / WebCore / platform / network / soup / ResourceHandleSoup.cpp
1 /*
2  * Copyright (C) 2008 Alp Toker <alp@atoker.com>
3  * Copyright (C) 2008 Xan Lopez <xan@gnome.org>
4  * Copyright (C) 2008, 2010 Collabora Ltd.
5  * Copyright (C) 2009 Holger Hans Peter Freyther
6  * Copyright (C) 2009 Gustavo Noronha Silva <gns@gnome.org>
7  * Copyright (C) 2009 Christian Dywan <christian@imendio.com>
8  * Copyright (C) 2009, 2010, 2011 Igalia S.L.
9  * Copyright (C) 2009 John Kjellberg <john.kjellberg@power.alstom.com>
10  * Copyright (C) 2012 Intel Corporation
11  *
12  * This library is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Library General Public
14  * License as published by the Free Software Foundation; either
15  * version 2 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public License
23  * along with this library; see the file COPYING.LIB.  If not, write to
24  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25  * Boston, MA 02110-1301, USA.
26  */
27
28 #include "config.h"
29 #include "ResourceHandle.h"
30
31 #include "CachedResourceLoader.h"
32 #include "ChromeClient.h"
33 #include "CookieJarSoup.h"
34 #include "FileSystem.h"
35 #include "Frame.h"
36 #include "GOwnPtrSoup.h"
37 #include "HTTPParsers.h"
38 #include "LocalizedStrings.h"
39 #include "Logging.h"
40 #include "MIMETypeRegistry.h"
41 #include "NotImplemented.h"
42 #include "Page.h"
43 #include "ResourceError.h"
44 #include "ResourceHandleClient.h"
45 #include "ResourceHandleInternal.h"
46 #include "ResourceResponse.h"
47 #include "SharedBuffer.h"
48 #include "TextEncoding.h"
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <gio/gio.h>
52 #include <glib.h>
53 #define LIBSOUP_USE_UNSTABLE_REQUEST_API
54 #include <libsoup/soup-request-http.h>
55 #include <libsoup/soup-requester.h>
56 #include <libsoup/soup.h>
57 #include <sys/stat.h>
58 #include <sys/types.h>
59 #include <unistd.h>
60 #include <wtf/SHA1.h>
61 #include <wtf/gobject/GRefPtr.h>
62 #include <wtf/text/Base64.h>
63 #include <wtf/text/CString.h>
64
65 #if ENABLE(BLOB)
66 #include "BlobData.h"
67 #include "BlobRegistryImpl.h"
68 #include "BlobStorageData.h"
69 #endif
70
71 namespace WebCore {
72
73 #define READ_BUFFER_SIZE 8192
74
75 static bool loadingSynchronousRequest = false;
76
77 class WebCoreSynchronousLoader : public ResourceHandleClient {
78     WTF_MAKE_NONCOPYABLE(WebCoreSynchronousLoader);
79 public:
80
81     WebCoreSynchronousLoader(ResourceError& error, ResourceResponse& response, SoupSession* session, Vector<char>& data)
82         : m_error(error)
83         , m_response(response)
84         , m_session(session)
85         , m_data(data)
86         , m_finished(false)
87     {
88         // We don't want any timers to fire while we are doing our synchronous load
89         // so we replace the thread default main context. The main loop iterations
90         // will only process GSources associated with this inner context.
91         loadingSynchronousRequest = true;
92         GRefPtr<GMainContext> innerMainContext = adoptGRef(g_main_context_new());
93         g_main_context_push_thread_default(innerMainContext.get());
94         m_mainLoop = adoptGRef(g_main_loop_new(innerMainContext.get(), false));
95
96         adjustMaxConnections(1);
97     }
98
99     ~WebCoreSynchronousLoader()
100     {
101         adjustMaxConnections(-1);
102         g_main_context_pop_thread_default(g_main_context_get_thread_default());
103         loadingSynchronousRequest = false;
104     }
105
106     void adjustMaxConnections(int adjustment)
107     {
108         int maxConnections, maxConnectionsPerHost;
109         g_object_get(m_session,
110                      SOUP_SESSION_MAX_CONNS, &maxConnections,
111                      SOUP_SESSION_MAX_CONNS_PER_HOST, &maxConnectionsPerHost,
112                      NULL);
113         maxConnections += adjustment;
114         maxConnectionsPerHost += adjustment;
115         g_object_set(m_session,
116                      SOUP_SESSION_MAX_CONNS, maxConnections,
117                      SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
118                      NULL);
119
120     }
121
122     virtual bool isSynchronousClient()
123     {
124         return true;
125     }
126
127     virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
128     {
129         m_response = response;
130     }
131
132     virtual void didReceiveData(ResourceHandle*, const char* data, int length, int)
133     {
134         m_data.append(data, length);
135     }
136
137     virtual void didFinishLoading(ResourceHandle*, double)
138     {
139         if (g_main_loop_is_running(m_mainLoop.get()))
140             g_main_loop_quit(m_mainLoop.get());
141         m_finished = true;
142     }
143
144     virtual void didFail(ResourceHandle* handle, const ResourceError& error)
145     {
146         m_error = error;
147         didFinishLoading(handle, 0);
148     }
149
150     void run()
151     {
152         if (!m_finished)
153             g_main_loop_run(m_mainLoop.get());
154     }
155
156 private:
157     ResourceError& m_error;
158     ResourceResponse& m_response;
159     SoupSession* m_session;
160     Vector<char>& m_data;
161     bool m_finished;
162     GRefPtr<GMainLoop> m_mainLoop;
163 };
164
165 class HostTLSCertificateSet {
166 public:
167     void add(GTlsCertificate* certificate)
168     {
169         String certificateHash = computeCertificateHash(certificate);
170         if (!certificateHash.isEmpty())
171             m_certificates.add(certificateHash);
172     }
173
174     bool contains(GTlsCertificate* certificate)
175     {
176         return m_certificates.contains(computeCertificateHash(certificate));
177     }
178
179 private:
180     static String computeCertificateHash(GTlsCertificate* certificate)
181     {
182         GByteArray* data = 0;
183         g_object_get(G_OBJECT(certificate), "certificate", &data, NULL);
184         if (!data)
185             return String();
186
187         static const size_t sha1HashSize = 20;
188         GRefPtr<GByteArray> certificateData = adoptGRef(data);
189         SHA1 sha1;
190         sha1.addBytes(certificateData->data, certificateData->len);
191
192         Vector<uint8_t, sha1HashSize> digest;
193         sha1.computeHash(digest);
194
195         return base64Encode(reinterpret_cast<const char*>(digest.data()), sha1HashSize);
196     }
197
198     HashSet<String> m_certificates;
199 };
200
201 static void cleanupSoupRequestOperation(ResourceHandle*, bool isDestroying);
202 static void sendRequestCallback(GObject*, GAsyncResult*, gpointer);
203 static void readCallback(GObject*, GAsyncResult*, gpointer);
204 static void closeCallback(GObject*, GAsyncResult*, gpointer);
205 static gboolean requestTimeoutCallback(void*);
206 #if ENABLE(WEB_TIMING)
207 static int  milisecondsSinceRequest(double requestTime);
208 #endif
209
210 static bool gIgnoreSSLErrors = false;
211
212 static HashSet<String>& allowsAnyHTTPSCertificateHosts()
213 {
214     DEFINE_STATIC_LOCAL(HashSet<String>, hosts, ());
215     return hosts;
216 }
217
218 typedef HashMap<String, HostTLSCertificateSet> CertificatesMap;
219 static CertificatesMap& clientCertificates()
220 {
221     DEFINE_STATIC_LOCAL(CertificatesMap, certificates, ());
222     return certificates;
223 }
224
225 ResourceHandleInternal::~ResourceHandleInternal()
226 {
227 }
228
229 static SoupSession* sessionFromContext(NetworkingContext* context)
230 {
231     return (context && context->isValid()) ? context->soupSession() : ResourceHandle::defaultSession();
232 }
233
234 uint64_t ResourceHandleInternal::initiatingPageID()
235 {
236     return (m_context && m_context->isValid()) ? m_context->initiatingPageID() : 0;
237 }
238
239 ResourceHandle::~ResourceHandle()
240 {
241     cleanupSoupRequestOperation(this, true);
242 }
243
244 static void ensureSessionIsInitialized(SoupSession* session)
245 {
246     if (g_object_get_data(G_OBJECT(session), "webkit-init"))
247         return;
248
249     if (session == ResourceHandle::defaultSession()) {
250         SoupCookieJar* jar = SOUP_COOKIE_JAR(soup_session_get_feature(session, SOUP_TYPE_COOKIE_JAR));
251         if (!jar)
252             soup_session_add_feature(session, SOUP_SESSION_FEATURE(soupCookieJar()));
253         else
254             setSoupCookieJar(jar);
255     }
256
257 #if !LOG_DISABLED
258     if (!soup_session_get_feature(session, SOUP_TYPE_LOGGER) && LogNetwork.state == WTFLogChannelOn) {
259         SoupLogger* logger = soup_logger_new(static_cast<SoupLoggerLogLevel>(SOUP_LOGGER_LOG_BODY), -1);
260         soup_session_add_feature(session, SOUP_SESSION_FEATURE(logger));
261         g_object_unref(logger);
262     }
263 #endif // !LOG_DISABLED
264
265     if (!soup_session_get_feature(session, SOUP_TYPE_REQUESTER)) {
266         SoupRequester* requester = soup_requester_new();
267         soup_session_add_feature(session, SOUP_SESSION_FEATURE(requester));
268         g_object_unref(requester);
269     }
270
271     g_object_set_data(G_OBJECT(session), "webkit-init", reinterpret_cast<void*>(0xdeadbeef));
272 }
273
274 SoupSession* ResourceHandleInternal::soupSession()
275 {
276     SoupSession* session = sessionFromContext(m_context.get());
277     ensureSessionIsInitialized(session);
278     return session;
279 }
280
281 static void gotHeadersCallback(SoupMessage* msg, gpointer data)
282 {
283     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
284     if (!handle)
285         return;
286     ResourceHandleInternal* d = handle->getInternal();
287     if (d->m_cancelled)
288         return;
289
290 #if ENABLE(WEB_TIMING)
291     if (d->m_response.resourceLoadTiming())
292         d->m_response.resourceLoadTiming()->receiveHeadersEnd = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
293 #endif
294
295     // The original response will be needed later to feed to willSendRequest in
296     // restartedCallback() in case we are redirected. For this reason, so we store it
297     // here.
298     ResourceResponse response;
299     response.updateFromSoupMessage(msg);
300
301     d->m_response = response;
302 }
303
304 // Called each time the message is going to be sent again except the first time.
305 // It's used mostly to let webkit know about redirects.
306 static void restartedCallback(SoupMessage* msg, 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     GOwnPtr<char> uri(soup_uri_to_string(soup_message_get_uri(msg), false));
316     String location = String::fromUTF8(uri.get());
317     KURL newURL = KURL(handle->firstRequest().url(), location);
318
319     ResourceRequest request = handle->firstRequest();
320     request.setURL(newURL);
321     request.setHTTPMethod(msg->method);
322
323     // Should not set Referer after a redirect from a secure resource to non-secure one.
324     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https")) {
325         request.clearHTTPReferrer();
326         soup_message_headers_remove(msg->request_headers, "Referer");
327     }
328
329     if (d->client())
330         d->client()->willSendRequest(handle, request, d->m_response);
331
332     if (d->m_cancelled)
333         return;
334
335 #if ENABLE(WEB_TIMING)
336     d->m_response.setResourceLoadTiming(ResourceLoadTiming::create());
337     d->m_response.resourceLoadTiming()->requestTime = monotonicallyIncreasingTime();
338 #endif
339
340     // Update the first party in case the base URL changed with the redirect
341     String firstPartyString = request.firstPartyForCookies().string();
342     if (!firstPartyString.isEmpty()) {
343         GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
344         soup_message_set_first_party(d->m_soupMessage.get(), firstParty.get());
345     }
346 }
347
348 static void wroteBodyDataCallback(SoupMessage*, SoupBuffer* buffer, gpointer data)
349 {
350     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
351     if (!handle)
352         return;
353
354     ASSERT(buffer);
355     ResourceHandleInternal* internal = handle->getInternal();
356     internal->m_bodyDataSent += buffer->length;
357
358     if (internal->m_cancelled)
359         return;
360     ResourceHandleClient* client = handle->client();
361     if (!client)
362         return;
363
364     client->didSendData(handle.get(), internal->m_bodyDataSent, internal->m_bodySize);
365 }
366
367 static void cleanupSoupRequestOperation(ResourceHandle* handle, bool isDestroying = false)
368 {
369     ResourceHandleInternal* d = handle->getInternal();
370
371     if (d->m_soupRequest)
372         d->m_soupRequest.clear();
373
374     if (d->m_inputStream)
375         d->m_inputStream.clear();
376
377     d->m_cancellable.clear();
378
379     if (d->m_soupMessage) {
380         g_signal_handlers_disconnect_matched(d->m_soupMessage.get(), G_SIGNAL_MATCH_DATA,
381                                              0, 0, 0, 0, handle);
382         g_object_set_data(G_OBJECT(d->m_soupMessage.get()), "handle", 0);
383         d->m_soupMessage.clear();
384     }
385
386     if (d->m_buffer) {
387         g_slice_free1(READ_BUFFER_SIZE, d->m_buffer);
388         d->m_buffer = 0;
389     }
390
391     if (d->m_timeoutSource) {
392         g_source_destroy(d->m_timeoutSource.get());
393         d->m_timeoutSource.clear();
394     }
395
396     if (!isDestroying)
397         handle->deref();
398 }
399
400 static bool handleUnignoredTLSErrors(ResourceHandle* handle)
401 {
402     ResourceHandleInternal* d = handle->getInternal();
403     const ResourceResponse& response = d->m_response;
404
405     if (!response.soupMessageTLSErrors() || gIgnoreSSLErrors)
406         return false;
407
408     String lowercaseHostURL = handle->firstRequest().url().host().lower();
409     if (allowsAnyHTTPSCertificateHosts().contains(lowercaseHostURL))
410         return false;
411
412     // We aren't ignoring errors globally, but the user may have already decided to accept this certificate.
413     CertificatesMap::iterator i = clientCertificates().find(lowercaseHostURL);
414     if (i != clientCertificates().end() && i->value.contains(response.soupMessageCertificate()))
415         return false;
416
417     handle->client()->didFail(handle, ResourceError::tlsError(d->m_soupRequest.get(), response.soupMessageTLSErrors(), response.soupMessageCertificate()));
418     return true;
419 }
420
421 static void sendRequestCallback(GObject*, GAsyncResult* res, gpointer data)
422 {
423     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
424
425     ResourceHandleInternal* d = handle->getInternal();
426     ResourceHandleClient* client = handle->client();
427     SoupMessage* soupMessage = d->m_soupMessage.get();
428
429     if (d->m_cancelled || !client) {
430         cleanupSoupRequestOperation(handle.get());
431         return;
432     }
433
434     if (d->m_defersLoading) {
435         d->m_deferredResult = res;
436         return;
437     }
438
439     GOwnPtr<GError> error;
440     GInputStream* in = soup_request_send_finish(d->m_soupRequest.get(), res, &error.outPtr());
441     if (error) {
442         client->didFail(handle.get(), ResourceError::httpError(soupMessage, error.get(), d->m_soupRequest.get()));
443         cleanupSoupRequestOperation(handle.get());
444         return;
445     }
446
447     d->m_inputStream = adoptGRef(in);
448     d->m_buffer = static_cast<char*>(g_slice_alloc(READ_BUFFER_SIZE));
449
450     if (soupMessage) {
451         if (handle->shouldContentSniff() && soupMessage->status_code != SOUP_STATUS_NOT_MODIFIED) {
452             const char* sniffedType = soup_request_get_content_type(d->m_soupRequest.get());
453             d->m_response.setSniffedContentType(sniffedType);
454         }
455         d->m_response.updateFromSoupMessage(soupMessage);
456
457         if (handleUnignoredTLSErrors(handle.get())) {
458             cleanupSoupRequestOperation(handle.get());
459             return;
460         }
461
462     } else {
463         d->m_response.setURL(handle->firstRequest().url());
464         const gchar* contentType = soup_request_get_content_type(d->m_soupRequest.get());
465         d->m_response.setMimeType(extractMIMETypeFromMediaType(contentType));
466         d->m_response.setTextEncodingName(extractCharsetFromMediaType(contentType));
467         d->m_response.setExpectedContentLength(soup_request_get_content_length(d->m_soupRequest.get()));
468     }
469
470     client->didReceiveResponse(handle.get(), d->m_response);
471
472     if (d->m_cancelled) {
473         cleanupSoupRequestOperation(handle.get());
474         return;
475     }
476
477     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE,
478                               G_PRIORITY_DEFAULT, d->m_cancellable.get(), readCallback, handle.get());
479 }
480
481 static bool addFileToSoupMessageBody(SoupMessage* message, const String& fileNameString, size_t offset, size_t lengthToSend, unsigned long& totalBodySize)
482 {
483     GOwnPtr<GError> error;
484     CString fileName = fileSystemRepresentation(fileNameString);
485     GMappedFile* fileMapping = g_mapped_file_new(fileName.data(), false, &error.outPtr());
486     if (error)
487         return false;
488
489     gsize bufferLength = lengthToSend;
490     if (!lengthToSend)
491         bufferLength = g_mapped_file_get_length(fileMapping);
492     totalBodySize += bufferLength;
493
494     SoupBuffer* soupBuffer = soup_buffer_new_with_owner(g_mapped_file_get_contents(fileMapping) + offset,
495                                                         bufferLength,
496                                                         fileMapping,
497                                                         reinterpret_cast<GDestroyNotify>(g_mapped_file_unref));
498     soup_message_body_append_buffer(message->request_body, soupBuffer);
499     soup_buffer_free(soupBuffer);
500     return true;
501 }
502
503 #if ENABLE(BLOB)
504 static bool blobIsOutOfDate(const BlobDataItem& blobItem)
505 {
506     ASSERT(blobItem.type == BlobDataItem::File);
507     if (!isValidFileTime(blobItem.expectedModificationTime))
508         return false;
509
510     time_t fileModificationTime;
511     if (!getFileModificationTime(blobItem.path, fileModificationTime))
512         return true;
513
514     return fileModificationTime != static_cast<time_t>(blobItem.expectedModificationTime);
515 }
516
517 static void addEncodedBlobItemToSoupMessageBody(SoupMessage* message, const BlobDataItem& blobItem, unsigned long& totalBodySize)
518 {
519     if (blobItem.type == BlobDataItem::Data) {
520         totalBodySize += blobItem.length;
521         soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
522                                  blobItem.data->data() + blobItem.offset, blobItem.length);
523         return;
524     }
525
526     ASSERT(blobItem.type == BlobDataItem::File);
527     if (blobIsOutOfDate(blobItem))
528         return;
529
530     addFileToSoupMessageBody(message,
531                              blobItem.path,
532                              blobItem.offset,
533                              blobItem.length == BlobDataItem::toEndOfFile ? 0 : blobItem.length,
534                              totalBodySize);
535 }
536
537 static void addEncodedBlobToSoupMessageBody(SoupMessage* message, const FormDataElement& element, unsigned long& totalBodySize)
538 {
539     RefPtr<BlobStorageData> blobData = static_cast<BlobRegistryImpl&>(blobRegistry()).getBlobDataFromURL(KURL(ParsedURLString, element.m_url));
540     if (!blobData)
541         return;
542
543     for (size_t i = 0; i < blobData->items().size(); ++i)
544         addEncodedBlobItemToSoupMessageBody(message, blobData->items()[i], totalBodySize);
545 }
546 #endif // ENABLE(BLOB)
547
548 static bool addFormElementsToSoupMessage(SoupMessage* message, const char*, FormData* httpBody, unsigned long& totalBodySize)
549 {
550     soup_message_body_set_accumulate(message->request_body, FALSE);
551     size_t numElements = httpBody->elements().size();
552     for (size_t i = 0; i < numElements; i++) {
553         const FormDataElement& element = httpBody->elements()[i];
554
555         if (element.m_type == FormDataElement::data) {
556             totalBodySize += element.m_data.size();
557             soup_message_body_append(message->request_body, SOUP_MEMORY_TEMPORARY,
558                                      element.m_data.data(), element.m_data.size());
559             continue;
560         }
561
562         if (element.m_type == FormDataElement::encodedFile) {
563             if (!addFileToSoupMessageBody(message ,
564                                          element.m_filename,
565                                          0 /* offset */,
566                                          0 /* lengthToSend */,
567                                          totalBodySize))
568                 return false;
569             continue;
570         }
571
572 #if ENABLE(BLOB)
573         ASSERT(element.m_type == FormDataElement::encodedBlob);
574         addEncodedBlobToSoupMessageBody(message, element, totalBodySize);
575 #endif
576     }
577     return true;
578 }
579
580 #if ENABLE(WEB_TIMING)
581 static int milisecondsSinceRequest(double requestTime)
582 {
583     return static_cast<int>((monotonicallyIncreasingTime() - requestTime) * 1000.0);
584 }
585
586 static void wroteBodyCallback(SoupMessage*, gpointer data)
587 {
588     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
589     if (!handle)
590         return;
591
592     ResourceHandleInternal* d = handle->getInternal();
593     if (!d->m_response.resourceLoadTiming())
594         return;
595
596     d->m_response.resourceLoadTiming()->sendEnd = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
597 }
598
599 static void requestStartedCallback(SoupSession*, SoupMessage* soupMessage, SoupSocket*, gpointer)
600 {
601     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(g_object_get_data(G_OBJECT(soupMessage), "handle"));
602     if (!handle)
603         return;
604
605     ResourceHandleInternal* d = handle->getInternal();
606     if (!d->m_response.resourceLoadTiming())
607         return;
608
609     d->m_response.resourceLoadTiming()->sendStart = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
610     if (d->m_response.resourceLoadTiming()->sslStart != -1) {
611         // WebCore/inspector/front-end/RequestTimingView.js assumes
612         // that SSL time is included in connection time so must
613         // substract here the SSL delta that will be added later (see
614         // WebInspector.RequestTimingView.createTimingTable in the
615         // file above for more details).
616         d->m_response.resourceLoadTiming()->sendStart -=
617             d->m_response.resourceLoadTiming()->sslEnd - d->m_response.resourceLoadTiming()->sslStart;
618     }
619 }
620
621 static void networkEventCallback(SoupMessage*, GSocketClientEvent event, GIOStream*, gpointer data)
622 {
623     ResourceHandle* handle = static_cast<ResourceHandle*>(data);
624     if (!handle)
625         return;
626     ResourceHandleInternal* d = handle->getInternal();
627     if (d->m_cancelled)
628         return;
629
630     int deltaTime = milisecondsSinceRequest(d->m_response.resourceLoadTiming()->requestTime);
631     switch (event) {
632     case G_SOCKET_CLIENT_RESOLVING:
633         d->m_response.resourceLoadTiming()->dnsStart = deltaTime;
634         break;
635     case G_SOCKET_CLIENT_RESOLVED:
636         d->m_response.resourceLoadTiming()->dnsEnd = deltaTime;
637         break;
638     case G_SOCKET_CLIENT_CONNECTING:
639         d->m_response.resourceLoadTiming()->connectStart = deltaTime;
640         if (d->m_response.resourceLoadTiming()->dnsStart != -1)
641             // WebCore/inspector/front-end/RequestTimingView.js assumes
642             // that DNS time is included in connection time so must
643             // substract here the DNS delta that will be added later (see
644             // WebInspector.RequestTimingView.createTimingTable in the
645             // file above for more details).
646             d->m_response.resourceLoadTiming()->connectStart -=
647                 d->m_response.resourceLoadTiming()->dnsEnd - d->m_response.resourceLoadTiming()->dnsStart;
648         break;
649     case G_SOCKET_CLIENT_CONNECTED:
650         // Web Timing considers that connection time involves dns, proxy & TLS negotiation...
651         // so we better pick G_SOCKET_CLIENT_COMPLETE for connectEnd
652         break;
653     case G_SOCKET_CLIENT_PROXY_NEGOTIATING:
654         d->m_response.resourceLoadTiming()->proxyStart = deltaTime;
655         break;
656     case G_SOCKET_CLIENT_PROXY_NEGOTIATED:
657         d->m_response.resourceLoadTiming()->proxyEnd = deltaTime;
658         break;
659     case G_SOCKET_CLIENT_TLS_HANDSHAKING:
660         d->m_response.resourceLoadTiming()->sslStart = deltaTime;
661         break;
662     case G_SOCKET_CLIENT_TLS_HANDSHAKED:
663         d->m_response.resourceLoadTiming()->sslEnd = deltaTime;
664         break;
665     case G_SOCKET_CLIENT_COMPLETE:
666         d->m_response.resourceLoadTiming()->connectEnd = deltaTime;
667         break;
668     default:
669         ASSERT_NOT_REACHED();
670         break;
671     }
672 }
673 #endif
674
675 static const char* gSoupRequestInitiaingPageIDKey = "wk-soup-request-initiaing-page-id";
676
677 static void setSoupRequestInitiaingPageID(SoupRequest* request, uint64_t initiatingPageID)
678 {
679     if (!initiatingPageID)
680         return;
681
682     uint64_t* initiatingPageIDPtr = static_cast<uint64_t*>(fastMalloc(sizeof(uint64_t)));
683     *initiatingPageIDPtr = initiatingPageID;
684     g_object_set_data_full(G_OBJECT(request), g_intern_static_string(gSoupRequestInitiaingPageIDKey), initiatingPageIDPtr, fastFree);
685 }
686
687 static bool createSoupMessageForHandleAndRequest(ResourceHandle* handle, const ResourceRequest& request)
688 {
689     ASSERT(handle);
690     ASSERT(d->m_soupRequest);
691
692     ResourceHandleInternal* d = handle->getInternal();
693     d->m_soupMessage = adoptGRef(soup_request_http_get_message(SOUP_REQUEST_HTTP(d->m_soupRequest.get())));
694     if (!d->m_soupMessage)
695         return false;
696
697     SoupMessage* soupMessage = d->m_soupMessage.get();
698     request.updateSoupMessage(soupMessage);
699
700     if (!handle->shouldContentSniff())
701         soup_message_disable_feature(soupMessage, SOUP_TYPE_CONTENT_SNIFFER);
702
703     String firstPartyString = request.firstPartyForCookies().string();
704     if (!firstPartyString.isEmpty()) {
705         GOwnPtr<SoupURI> firstParty(soup_uri_new(firstPartyString.utf8().data()));
706         soup_message_set_first_party(soupMessage, firstParty.get());
707     }
708
709     FormData* httpBody = request.httpBody();
710     CString contentType = request.httpContentType().utf8().data();
711     if (httpBody && !httpBody->isEmpty() && !addFormElementsToSoupMessage(soupMessage, contentType.data(), httpBody, d->m_bodySize)) {
712         // We failed to prepare the body data, so just fail this load.
713         d->m_soupMessage.clear();
714         return false;
715     }
716
717     // Make sure we have an Accept header for subresources; some sites
718     // want this to serve some of their subresources
719     if (!soup_message_headers_get_one(soupMessage->request_headers, "Accept"))
720         soup_message_headers_append(soupMessage->request_headers, "Accept", "*/*");
721
722     // In the case of XHR .send() and .send("") explicitly tell libsoup to send a zero content-lenght header
723     // for consistency with other backends (e.g. Chromium's) and other UA implementations like FF. It's done
724     // in the backend here instead of in XHR code since in XHR CORS checking prevents us from this kind of
725     // late header manipulation.
726     if ((request.httpMethod() == "POST" || request.httpMethod() == "PUT")
727         && (!request.httpBody() || request.httpBody()->isEmpty()))
728         soup_message_headers_set_content_length(soupMessage->request_headers, 0);
729
730     g_signal_connect(d->m_soupMessage.get(), "got-headers", G_CALLBACK(gotHeadersCallback), handle);
731     g_signal_connect(d->m_soupMessage.get(), "restarted", G_CALLBACK(restartedCallback), handle);
732     g_signal_connect(d->m_soupMessage.get(), "wrote-body-data", G_CALLBACK(wroteBodyDataCallback), handle);
733
734 #if ENABLE(WEB_TIMING)
735     d->m_response.setResourceLoadTiming(ResourceLoadTiming::create());
736     g_signal_connect(d->m_soupMessage.get(), "network-event", G_CALLBACK(networkEventCallback), handle);
737     g_signal_connect(d->m_soupMessage.get(), "wrote-body", G_CALLBACK(wroteBodyCallback), handle);
738     g_object_set_data(G_OBJECT(d->m_soupMessage.get()), "handle", handle);
739 #endif
740
741     return true;
742 }
743
744 static bool createSoupRequestAndMessageForHandle(ResourceHandle* handle, bool isHTTPFamilyRequest)
745 {
746     ResourceHandleInternal* d = handle->getInternal();
747     SoupRequester* requester = SOUP_REQUESTER(soup_session_get_feature(d->soupSession(), SOUP_TYPE_REQUESTER));
748
749     GOwnPtr<GError> error;
750     const ResourceRequest& request = handle->firstRequest();
751     d->m_soupRequest = adoptGRef(soup_requester_request(requester, request.urlStringForSoup().utf8().data(), &error.outPtr()));
752     if (error) {
753         d->m_soupRequest.clear();
754         return false;
755     }
756
757     // Non-HTTP family requests do not need a soupMessage, as it's callbacks really only apply to HTTP.
758     if (isHTTPFamilyRequest && !createSoupMessageForHandleAndRequest(handle, request)) {
759         d->m_soupRequest.clear();
760         return false;
761     }
762
763     return true;
764 }
765
766 bool ResourceHandle::start(NetworkingContext* context)
767 {
768     ASSERT(!d->m_soupMessage);
769
770     // The frame could be null if the ResourceHandle is not associated to any
771     // Frame, e.g. if we are downloading a file.
772     // If the frame is not null but the page is null this must be an attempted
773     // load from an unload handler, so let's just block it.
774     // If both the frame and the page are not null the context is valid.
775     if (context && !context->isValid())
776         return false;
777
778     if (!(d->m_user.isEmpty() || d->m_pass.isEmpty())) {
779         // If credentials were specified for this request, add them to the url,
780         // so that they will be passed to NetworkRequest.
781         KURL urlWithCredentials(firstRequest().url());
782         urlWithCredentials.setUser(d->m_user);
783         urlWithCredentials.setPass(d->m_pass);
784         d->m_firstRequest.setURL(urlWithCredentials);
785     }
786
787     // Used to set the authentication dialog toplevel; may be NULL
788     d->m_context = context;
789
790     // Only allow the POST and GET methods for non-HTTP requests.
791     const ResourceRequest& request = firstRequest();
792     bool isHTTPFamilyRequest = request.url().protocolIsInHTTPFamily();
793     if (!isHTTPFamilyRequest && request.httpMethod() != "GET" && request.httpMethod() != "POST") {
794         this->scheduleFailure(InvalidURLFailure); // Error must not be reported immediately
795         return true;
796     }
797
798     if (!createSoupRequestAndMessageForHandle(this, isHTTPFamilyRequest)) {
799         this->scheduleFailure(InvalidURLFailure); // Error must not be reported immediately
800         return true;
801     }
802
803     setSoupRequestInitiaingPageID(d->m_soupRequest.get(), d->initiatingPageID());
804
805     // Send the request only if it's not been explicitly deferred.
806     if (!d->m_defersLoading)
807         sendPendingRequest();
808
809     return true;
810 }
811
812 void ResourceHandle::sendPendingRequest()
813 {
814 #if ENABLE(WEB_TIMING)
815     if (d->m_response.resourceLoadTiming())
816         d->m_response.resourceLoadTiming()->requestTime = monotonicallyIncreasingTime();
817 #endif
818
819     if (d->m_firstRequest.timeoutInterval() > 0) {
820         // soup_add_timeout returns a GSource* whose only reference is owned by
821         // the context. We need to have our own reference to it, hence not using adoptRef.
822         d->m_timeoutSource = soup_add_timeout(g_main_context_get_thread_default(),
823             d->m_firstRequest.timeoutInterval() * 1000, requestTimeoutCallback, this);
824     }
825
826     // Balanced by a deref() in cleanupSoupRequestOperation, which should always run.
827     ref();
828
829     d->m_cancellable = adoptGRef(g_cancellable_new());
830     soup_request_send_async(d->m_soupRequest.get(), d->m_cancellable.get(), sendRequestCallback, this);
831 }
832
833 void ResourceHandle::cancel()
834 {
835     d->m_cancelled = true;
836     if (d->m_soupMessage)
837         soup_session_cancel_message(d->soupSession(), d->m_soupMessage.get(), SOUP_STATUS_CANCELLED);
838     else if (d->m_cancellable)
839         g_cancellable_cancel(d->m_cancellable.get());
840 }
841
842 void ResourceHandle::setHostAllowsAnyHTTPSCertificate(const String& host)
843 {
844     allowsAnyHTTPSCertificateHosts().add(host.lower());
845 }
846
847 void ResourceHandle::setClientCertificate(const String& host, GTlsCertificate* certificate)
848 {
849     clientCertificates().add(host.lower(), HostTLSCertificateSet()).iterator->value.add(certificate);
850 }
851
852 void ResourceHandle::setIgnoreSSLErrors(bool ignoreSSLErrors)
853 {
854     gIgnoreSSLErrors = ignoreSSLErrors;
855 }
856
857 static bool waitingToSendRequest(ResourceHandle* handle)
858 {
859     // We need to check for d->m_soupRequest because the request may have raised a failure
860     // (for example invalid URLs). We cannot  simply check for d->m_scheduledFailure because
861     // it's cleared as soon as the failure event is fired.
862     return handle->getInternal()->m_soupRequest && !handle->getInternal()->m_cancellable;
863 }
864
865 void ResourceHandle::platformSetDefersLoading(bool defersLoading)
866 {
867     if (d->m_cancelled)
868         return;
869
870     // Except when canceling a possible timeout timer, we only need to take action here to UN-defer loading.
871     if (defersLoading) {
872         if (d->m_timeoutSource) {
873             g_source_destroy(d->m_timeoutSource.get());
874             d->m_timeoutSource.clear();
875         }
876         return;
877     }
878
879     if (waitingToSendRequest(this)) {
880         sendPendingRequest();
881         return;
882     }
883
884     if (d->m_deferredResult) {
885         GRefPtr<GAsyncResult> asyncResult = adoptGRef(d->m_deferredResult.leakRef());
886
887         if (d->m_inputStream)
888             readCallback(G_OBJECT(d->m_inputStream.get()), asyncResult.get(), this);
889         else
890             sendRequestCallback(G_OBJECT(d->m_soupRequest.get()), asyncResult.get(), this);
891     }
892 }
893
894 bool ResourceHandle::loadsBlocked()
895 {
896     return false;
897 }
898
899 bool ResourceHandle::willLoadFromCache(ResourceRequest&, Frame*)
900 {
901     // Not having this function means that we'll ask the user about re-posting a form
902     // even when we go back to a page that's still in the cache.
903     notImplemented();
904     return false;
905 }
906
907 void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials /*storedCredentials*/, ResourceError& error, ResourceResponse& response, Vector<char>& data)
908 {
909 #if ENABLE(BLOB)
910     if (request.url().protocolIs("blob")) {
911         blobRegistry().loadResourceSynchronously(request, error, response, data);
912         return;
913     }
914 #endif
915  
916     ASSERT(!loadingSynchronousRequest);
917     if (loadingSynchronousRequest) // In practice this cannot happen, but if for some reason it does,
918         return;                    // we want to avoid accidentally going into an infinite loop of requests.
919
920     WebCoreSynchronousLoader syncLoader(error, response, sessionFromContext(context), data);
921     RefPtr<ResourceHandle> handle = create(context, request, &syncLoader, false /*defersLoading*/, false /*shouldContentSniff*/);
922     if (!handle)
923         return;
924
925     // If the request has already failed, do not run the main loop, or else we'll block indefinitely.
926     if (handle->d->m_scheduledFailureType != NoFailure)
927         return;
928
929     syncLoader.run();
930 }
931
932 static void closeCallback(GObject*, GAsyncResult* res, gpointer data)
933 {
934     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
935     ResourceHandleInternal* d = handle->getInternal();
936
937     g_input_stream_close_finish(d->m_inputStream.get(), res, 0);
938
939     ResourceHandleClient* client = handle->client();
940     if (client && loadingSynchronousRequest)
941         client->didFinishLoading(handle.get(), 0);
942
943     cleanupSoupRequestOperation(handle.get());
944 }
945
946 static void readCallback(GObject*, GAsyncResult* asyncResult, gpointer data)
947 {
948     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
949
950     ResourceHandleInternal* d = handle->getInternal();
951     ResourceHandleClient* client = handle->client();
952
953     if (d->m_cancelled || !client) {
954         cleanupSoupRequestOperation(handle.get());
955         return;
956     }
957
958     if (d->m_defersLoading) {
959         d->m_deferredResult = asyncResult;
960         return;
961     }
962
963     GOwnPtr<GError> error;
964     gssize bytesRead = g_input_stream_read_finish(d->m_inputStream.get(), asyncResult, &error.outPtr());
965     if (error) {
966         client->didFail(handle.get(), ResourceError::genericIOError(error.get(), d->m_soupRequest.get()));
967         cleanupSoupRequestOperation(handle.get());
968         return;
969     }
970
971     if (!bytesRead) {
972         // We inform WebCore of load completion now instead of waiting for the input
973         // stream to close because the input stream is closed asynchronously. If this
974         // is a synchronous request, we wait until the closeCallback, because we don't
975         // want to halt the internal main loop before the input stream closes.
976         if (client && !loadingSynchronousRequest) {
977             client->didFinishLoading(handle.get(), 0);
978             handle->setClient(0); // Unset the client so that we do not try to access th
979                                   // client in the closeCallback.
980         }
981         g_input_stream_close_async(d->m_inputStream.get(), G_PRIORITY_DEFAULT, 0, closeCallback, handle.get());
982         return;
983     }
984
985     // It's mandatory to have sent a response before sending data
986     ASSERT(!d->m_response.isNull());
987
988     client->didReceiveData(handle.get(), d->m_buffer, bytesRead, bytesRead);
989
990     // didReceiveData may cancel the load, which may release the last reference.
991     if (d->m_cancelled || !client) {
992         cleanupSoupRequestOperation(handle.get());
993         return;
994     }
995
996     g_input_stream_read_async(d->m_inputStream.get(), d->m_buffer, READ_BUFFER_SIZE, G_PRIORITY_DEFAULT,
997                               d->m_cancellable.get(), readCallback, handle.get());
998 }
999
1000 static gboolean requestTimeoutCallback(gpointer data)
1001 {
1002     RefPtr<ResourceHandle> handle = static_cast<ResourceHandle*>(data);
1003     handle->client()->didFail(handle.get(), ResourceError::timeoutError(handle->getInternal()->m_firstRequest.url().string()));
1004     cleanupSoupRequestOperation(handle.get());
1005     handle->cancel();
1006
1007     return FALSE;
1008 }
1009
1010 SoupSession* ResourceHandle::defaultSession()
1011 {
1012     static SoupSession* session = 0;
1013     // Values taken from http://www.browserscope.org/  following
1014     // the rule "Do What Every Other Modern Browser Is Doing". They seem
1015     // to significantly improve page loading time compared to soup's
1016     // default values.
1017     static const int maxConnections = 35;
1018     static const int maxConnectionsPerHost = 6;
1019
1020     if (!session) {
1021         session = soup_session_async_new();
1022         g_object_set(session,
1023                      SOUP_SESSION_MAX_CONNS, maxConnections,
1024                      SOUP_SESSION_MAX_CONNS_PER_HOST, maxConnectionsPerHost,
1025                      SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_DECODER,
1026                      SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_SNIFFER,
1027                      SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
1028                      SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,
1029                      NULL);
1030 #if ENABLE(WEB_TIMING)
1031         g_signal_connect(G_OBJECT(session), "request-started", G_CALLBACK(requestStartedCallback), 0);
1032 #endif
1033     }
1034
1035     return session;
1036 }
1037
1038 uint64_t ResourceHandle::getSoupRequestInitiaingPageID(SoupRequest* request)
1039 {
1040     uint64_t* initiatingPageIDPtr = static_cast<uint64_t*>(g_object_get_data(G_OBJECT(request), gSoupRequestInitiaingPageIDKey));
1041     return initiatingPageIDPtr ? *initiatingPageIDPtr : 0;
1042 }
1043
1044 }