26fb6b7949fa3743e28a0d23dc8c4ec3f027b606
[WebKit.git] / Source / WebKit / WebProcess / Network / WebLoaderStrategy.cpp
1 /*
2  * Copyright (C) 2012, 2015 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "WebLoaderStrategy.h"
28
29 #include "DataReference.h"
30 #include "HangDetectionDisabler.h"
31 #include "Logging.h"
32 #include "NetworkConnectionToWebProcessMessages.h"
33 #include "NetworkProcessConnection.h"
34 #include "NetworkResourceLoadParameters.h"
35 #include "SessionTracker.h"
36 #include "WebCompiledContentRuleList.h"
37 #include "WebCoreArgumentCoders.h"
38 #include "WebErrors.h"
39 #include "WebFrame.h"
40 #include "WebFrameLoaderClient.h"
41 #include "WebPage.h"
42 #include "WebPageProxyMessages.h"
43 #include "WebProcess.h"
44 #include "WebResourceLoader.h"
45 #include "WebServiceWorkerProvider.h"
46 #include "WebURLSchemeHandlerProxy.h"
47 #include "WebURLSchemeTaskProxy.h"
48 #include <WebCore/ApplicationCacheHost.h>
49 #include <WebCore/CachedResource.h>
50 #include <WebCore/ContentSecurityPolicy.h>
51 #include <WebCore/DiagnosticLoggingClient.h>
52 #include <WebCore/DiagnosticLoggingKeys.h>
53 #include <WebCore/Document.h>
54 #include <WebCore/DocumentLoader.h>
55 #include <WebCore/FetchOptions.h>
56 #include <WebCore/Frame.h>
57 #include <WebCore/FrameLoader.h>
58 #include <WebCore/NetscapePlugInStreamLoader.h>
59 #include <WebCore/PlatformStrategies.h>
60 #include <WebCore/ReferrerPolicy.h>
61 #include <WebCore/ResourceLoader.h>
62 #include <WebCore/RuntimeEnabledFeatures.h>
63 #include <WebCore/SecurityOrigin.h>
64 #include <WebCore/Settings.h>
65 #include <WebCore/SubresourceLoader.h>
66 #include <WebCore/UserContentProvider.h>
67 #include <pal/SessionID.h>
68 #include <wtf/CompletionHandler.h>
69 #include <wtf/text/CString.h>
70
71 #if USE(QUICK_LOOK)
72 #include <WebCore/QuickLook.h>
73 #endif
74
75 using namespace WebCore;
76
77 #define RELEASE_LOG_IF_ALLOWED(permissionChecker, fmt, ...) RELEASE_LOG_IF(permissionChecker.isAlwaysOnLoggingAllowed(), Network, "%p - WebLoaderStrategy::" fmt, this, ##__VA_ARGS__)
78 #define RELEASE_LOG_ERROR_IF_ALLOWED(permissionChecker, fmt, ...) RELEASE_LOG_ERROR_IF(permissionChecker.isAlwaysOnLoggingAllowed(), Network, "%p - WebLoaderStrategy::" fmt, this, ##__VA_ARGS__)
79
80 namespace WebKit {
81
82 WebLoaderStrategy::WebLoaderStrategy()
83     : m_internallyFailedLoadTimer(RunLoop::main(), this, &WebLoaderStrategy::internallyFailedLoadTimerFired)
84 {
85 }
86
87 WebLoaderStrategy::~WebLoaderStrategy()
88 {
89 }
90
91 void WebLoaderStrategy::loadResource(Frame& frame, CachedResource& resource, ResourceRequest&& request, const ResourceLoaderOptions& options, CompletionHandler<void(RefPtr<SubresourceLoader>&&)>&& completionHandler)
92 {
93     SubresourceLoader::create(frame, resource, WTFMove(request), options, [this, completionHandler = WTFMove(completionHandler), resource = CachedResourceHandle<CachedResource>(&resource), frame = makeRef(frame)] (RefPtr<SubresourceLoader>&& loader) mutable {
94         if (loader)
95             scheduleLoad(*loader, resource.get(), frame->document()->referrerPolicy() == ReferrerPolicy::NoReferrerWhenDowngrade);
96         else
97             RELEASE_LOG_IF_ALLOWED(frame.get(), "loadResource: Unable to create SubresourceLoader (frame = %p", &frame);
98         completionHandler(WTFMove(loader));
99     });
100 }
101
102 void WebLoaderStrategy::schedulePluginStreamLoad(Frame& frame, NetscapePlugInStreamLoaderClient& client, ResourceRequest&& request, CompletionHandler<void(RefPtr<NetscapePlugInStreamLoader>&&)>&& completionHandler)
103 {
104     NetscapePlugInStreamLoader::create(frame, client, WTFMove(request), [this, completionHandler = WTFMove(completionHandler), frame = makeRef(frame)] (RefPtr<NetscapePlugInStreamLoader>&& loader) mutable {
105         if (loader)
106             scheduleLoad(*loader, 0, frame->document()->referrerPolicy() == ReferrerPolicy::NoReferrerWhenDowngrade);
107         completionHandler(WTFMove(loader));
108     });
109 }
110
111 static Seconds maximumBufferingTime(CachedResource* resource)
112 {
113     if (!resource)
114         return 0_s;
115
116     switch (resource->type()) {
117     case CachedResource::Beacon:
118     case CachedResource::CSSStyleSheet:
119     case CachedResource::Script:
120 #if ENABLE(SVG_FONTS)
121     case CachedResource::SVGFontResource:
122 #endif
123     case CachedResource::FontResource:
124 #if ENABLE(APPLICATION_MANIFEST)
125     case CachedResource::ApplicationManifest:
126 #endif
127         return Seconds::infinity();
128     case CachedResource::ImageResource:
129         return 500_ms;
130     case CachedResource::MediaResource:
131         return 50_ms;
132     case CachedResource::MainResource:
133     case CachedResource::Icon:
134     case CachedResource::RawResource:
135     case CachedResource::SVGDocumentResource:
136     case CachedResource::LinkPrefetch:
137 #if ENABLE(VIDEO_TRACK)
138     case CachedResource::TextTrackResource:
139 #endif
140 #if ENABLE(XSLT)
141     case CachedResource::XSLStyleSheet:
142 #endif
143         return 0_s;
144     }
145
146     ASSERT_NOT_REACHED();
147     return 0_s;
148 }
149
150 void WebLoaderStrategy::scheduleLoad(ResourceLoader& resourceLoader, CachedResource* resource, bool shouldClearReferrerOnHTTPSToHTTPRedirect)
151 {
152     ResourceLoadIdentifier identifier = resourceLoader.identifier();
153     ASSERT(identifier);
154
155     auto& frameLoaderClient = resourceLoader.frameLoader()->client();
156
157     WebResourceLoader::TrackingParameters trackingParameters;
158     trackingParameters.pageID = frameLoaderClient.pageID().value();
159     trackingParameters.frameID = frameLoaderClient.frameID().value();
160     trackingParameters.resourceID = identifier;
161     auto sessionID = frameLoaderClient.sessionID();
162
163 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
164     // If the DocumentLoader schedules this as an archive resource load,
165     // then we should remember the ResourceLoader in our records but not schedule it in the NetworkProcess.
166     if (resourceLoader.documentLoader()->scheduleArchiveLoad(resourceLoader, resourceLoader.request())) {
167         LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be handled as an archive resource.", resourceLoader.url().string().utf8().data());
168         RELEASE_LOG_IF_ALLOWED(resourceLoader, "scheduleLoad: URL will be handled as an archive resource (frame = %p, pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", resourceLoader.frame(), trackingParameters.pageID, trackingParameters.frameID, identifier);
169         m_webResourceLoaders.set(identifier, WebResourceLoader::create(resourceLoader, trackingParameters));
170         return;
171     }
172 #endif
173
174     if (resourceLoader.documentLoader()->applicationCacheHost().maybeLoadResource(resourceLoader, resourceLoader.request(), resourceLoader.request().url())) {
175         LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be loaded from application cache.", resourceLoader.url().string().utf8().data());
176         RELEASE_LOG_IF_ALLOWED(resourceLoader, "scheduleLoad: URL will be loaded from application cache (frame = %p, pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", resourceLoader.frame(), trackingParameters.pageID, trackingParameters.frameID, identifier);
177         m_webResourceLoaders.set(identifier, WebResourceLoader::create(resourceLoader, trackingParameters));
178         return;
179     }
180
181     if (resourceLoader.request().url().protocolIsData()) {
182         LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be loaded as data.", resourceLoader.url().string().utf8().data());
183         RELEASE_LOG_IF_ALLOWED(resourceLoader, "scheduleLoad: URL will be loaded as data (frame = %p, pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", resourceLoader.frame(), trackingParameters.pageID, trackingParameters.frameID, identifier);
184         startLocalLoad(resourceLoader);
185         return;
186     }
187
188 #if USE(QUICK_LOOK)
189     if (isQuickLookPreviewURL(resourceLoader.request().url())) {
190         LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be handled as a QuickLook resource.", resourceLoader.url().string().utf8().data());
191         RELEASE_LOG_IF_ALLOWED(resourceLoader, "scheduleLoad: URL will be handled as a QuickLook resource (frame = %p, pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", resourceLoader.frame(), trackingParameters.pageID, trackingParameters.frameID, identifier);
192         startLocalLoad(resourceLoader);
193         return;
194     }
195 #endif
196
197 #if USE(SOUP)
198     // For apps that call g_resource_load in a web extension.
199     // https://blogs.gnome.org/alexl/2012/01/26/resources-in-glib/
200     if (resourceLoader.request().url().protocolIs("resource")) {
201         LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be handled as a GResource.", resourceLoader.url().string().utf8().data());
202         RELEASE_LOG_IF_ALLOWED(resourceLoader, "scheduleLoad: URL will be handled as a GResource (frame = %p, pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", resourceLoader.frame(), trackingParameters.pageID, trackingParameters.frameID, identifier);
203         startLocalLoad(resourceLoader);
204         return;
205     }
206 #endif
207
208 #if ENABLE(SERVICE_WORKER)
209     WebServiceWorkerProvider::singleton().handleFetch(resourceLoader, resource, sessionID, shouldClearReferrerOnHTTPSToHTTPRedirect, [trackingParameters, sessionID, shouldClearReferrerOnHTTPSToHTTPRedirect, maximumBufferingTime = maximumBufferingTime(resource), resourceLoader = makeRef(resourceLoader)] (ServiceWorkerClientFetch::Result result) mutable {
210         if (result != ServiceWorkerClientFetch::Result::Unhandled) {
211             LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be scheduled through ServiceWorker handle fetch algorithm", resourceLoader->url().string().latin1().data());
212             return;
213         }
214         if (resourceLoader->options().serviceWorkersMode == ServiceWorkersMode::Only) {
215             callOnMainThread([resourceLoader = WTFMove(resourceLoader)] {
216                 auto error = internalError(resourceLoader->request().url());
217                 error.setType(ResourceError::Type::Cancellation);
218                 resourceLoader->didFail(error);
219             });
220             return;
221         }
222
223         if (!WebProcess::singleton().webLoaderStrategy().tryLoadingUsingURLSchemeHandler(resourceLoader))
224             WebProcess::singleton().webLoaderStrategy().scheduleLoadFromNetworkProcess(resourceLoader.get(), resourceLoader->request(), trackingParameters, sessionID, shouldClearReferrerOnHTTPSToHTTPRedirect, maximumBufferingTime);
225     });
226 #else
227     if (!tryLoadingUsingURLSchemeHandler(resourceLoader))
228         scheduleLoadFromNetworkProcess(resourceLoader, resourceLoader.request(), trackingParameters, sessionID, shouldClearReferrerOnHTTPSToHTTPRedirect, maximumBufferingTime(resource));
229 #endif
230 }
231
232 bool WebLoaderStrategy::tryLoadingUsingURLSchemeHandler(ResourceLoader& resourceLoader)
233 {
234     auto* webFrameLoaderClient = toWebFrameLoaderClient(resourceLoader.frameLoader()->client());
235     auto* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : nullptr;
236     auto* webPage = webFrame ? webFrame->page() : nullptr;
237     if (webPage) {
238         if (auto* handler = webPage->urlSchemeHandlerForScheme(resourceLoader.request().url().protocol().toStringWithoutCopying())) {
239             LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, URL '%s' will be handled by a UIProcess URL scheme handler.", resourceLoader.url().string().utf8().data());
240             RELEASE_LOG_IF_ALLOWED(resourceLoader, "scheduleLoad: URL will be handled by a UIProcess URL scheme handler (frame = %p, resourceID = %lu)", resourceLoader.frame(), resourceLoader.identifier());
241
242             handler->startNewTask(resourceLoader);
243             return true;
244         }
245     }
246     return false;
247 }
248
249 void WebLoaderStrategy::scheduleLoadFromNetworkProcess(ResourceLoader& resourceLoader, const ResourceRequest& request, const WebResourceLoader::TrackingParameters& trackingParameters, PAL::SessionID sessionID, bool shouldClearReferrerOnHTTPSToHTTPRedirect, Seconds maximumBufferingTime)
250 {
251     ResourceLoadIdentifier identifier = resourceLoader.identifier();
252     ASSERT(identifier);
253
254     LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::scheduleLoad, url '%s' will be scheduled with the NetworkProcess with priority %d", resourceLoader.url().string().latin1().data(), static_cast<int>(resourceLoader.request().priority()));
255
256     ContentSniffingPolicy contentSniffingPolicy = resourceLoader.shouldSniffContent() ? SniffContent : DoNotSniffContent;
257     ContentEncodingSniffingPolicy contentEncodingSniffingPolicy = resourceLoader.shouldSniffContentEncoding() ? ContentEncodingSniffingPolicy::Sniff : ContentEncodingSniffingPolicy::DoNotSniff;
258     StoredCredentialsPolicy storedCredentialsPolicy = resourceLoader.shouldUseCredentialStorage() ? StoredCredentialsPolicy::Use : StoredCredentialsPolicy::DoNotUse;
259
260     NetworkResourceLoadParameters loadParameters;
261     loadParameters.identifier = identifier;
262     loadParameters.webPageID = trackingParameters.pageID;
263     loadParameters.webFrameID = trackingParameters.frameID;
264     loadParameters.sessionID = sessionID;
265     loadParameters.request = request;
266     loadParameters.contentSniffingPolicy = contentSniffingPolicy;
267     loadParameters.contentEncodingSniffingPolicy = contentEncodingSniffingPolicy;
268     loadParameters.storedCredentialsPolicy = storedCredentialsPolicy;
269     // If there is no WebFrame then this resource cannot be authenticated with the client.
270     loadParameters.clientCredentialPolicy = (loadParameters.webFrameID && loadParameters.webPageID && resourceLoader.isAllowedToAskUserForCredentials()) ? ClientCredentialPolicy::MayAskClientForCredentials : ClientCredentialPolicy::CannotAskClientForCredentials;
271     loadParameters.shouldClearReferrerOnHTTPSToHTTPRedirect = shouldClearReferrerOnHTTPSToHTTPRedirect;
272     loadParameters.defersLoading = resourceLoader.defersLoading();
273     loadParameters.needsCertificateInfo = resourceLoader.shouldIncludeCertificateInfo();
274     loadParameters.maximumBufferingTime = maximumBufferingTime;
275     loadParameters.derivedCachedDataTypesToRetrieve = resourceLoader.options().derivedCachedDataTypesToRetrieve;
276
277     // FIXME: We should also sanitize redirect response for navigations.
278     loadParameters.shouldRestrictHTTPResponseAccess = RuntimeEnabledFeatures::sharedFeatures().restrictedHTTPResponseAccess() && resourceLoader.options().mode != FetchOptions::Mode::Navigate;
279
280     ASSERT((loadParameters.webPageID && loadParameters.webFrameID) || loadParameters.clientCredentialPolicy == ClientCredentialPolicy::CannotAskClientForCredentials);
281
282     RELEASE_LOG_IF_ALLOWED(resourceLoader, "scheduleLoad: Resource is being scheduled with the NetworkProcess (frame = %p, priority = %d, pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", resourceLoader.frame(), static_cast<int>(resourceLoader.request().priority()), loadParameters.webPageID, loadParameters.webFrameID, loadParameters.identifier);
283     if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::ScheduleResourceLoad(loadParameters), 0)) {
284         RELEASE_LOG_ERROR_IF_ALLOWED(resourceLoader, "scheduleLoad: Unable to schedule resource with the NetworkProcess (frame = %p, priority = %d, pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", resourceLoader.frame(), static_cast<int>(resourceLoader.request().priority()), loadParameters.webPageID, loadParameters.webFrameID, loadParameters.identifier);
285         // We probably failed to schedule this load with the NetworkProcess because it had crashed.
286         // This load will never succeed so we will schedule it to fail asynchronously.
287         scheduleInternallyFailedLoad(resourceLoader);
288         return;
289     }
290
291     m_webResourceLoaders.set(identifier, WebResourceLoader::create(resourceLoader, trackingParameters));
292 }
293
294 void WebLoaderStrategy::scheduleInternallyFailedLoad(WebCore::ResourceLoader& resourceLoader)
295 {
296     m_internallyFailedResourceLoaders.add(&resourceLoader);
297     m_internallyFailedLoadTimer.startOneShot(0_s);
298 }
299
300 void WebLoaderStrategy::internallyFailedLoadTimerFired()
301 {
302     for (auto& resourceLoader : copyToVector(m_internallyFailedResourceLoaders))
303         resourceLoader->didFail(internalError(resourceLoader->url()));
304 }
305
306 void WebLoaderStrategy::startLocalLoad(WebCore::ResourceLoader& resourceLoader)
307 {
308     resourceLoader.start();
309     m_webResourceLoaders.set(resourceLoader.identifier(), WebResourceLoader::create(resourceLoader, { }));
310 }
311
312 void WebLoaderStrategy::addURLSchemeTaskProxy(WebURLSchemeTaskProxy& task)
313 {
314     auto result = m_urlSchemeTasks.add(task.identifier(), &task);
315     ASSERT_UNUSED(result, result.isNewEntry);
316 }
317
318 void WebLoaderStrategy::removeURLSchemeTaskProxy(WebURLSchemeTaskProxy& task)
319 {
320     m_urlSchemeTasks.remove(task.identifier());
321 }
322
323 void WebLoaderStrategy::remove(ResourceLoader* resourceLoader)
324 {
325     ASSERT(resourceLoader);
326     LOG(NetworkScheduling, "(WebProcess) WebLoaderStrategy::remove, url '%s'", resourceLoader->url().string().utf8().data());
327
328     if (auto task = m_urlSchemeTasks.take(resourceLoader->identifier())) {
329         ASSERT(!m_internallyFailedResourceLoaders.contains(resourceLoader));
330         task->stopLoading();
331         return;
332     }
333
334     if (m_internallyFailedResourceLoaders.contains(resourceLoader)) {
335         m_internallyFailedResourceLoaders.remove(resourceLoader);
336         return;
337     }
338     
339     ResourceLoadIdentifier identifier = resourceLoader->identifier();
340     if (!identifier) {
341         LOG_ERROR("WebLoaderStrategy removing a ResourceLoader that has no identifier.");
342         return;
343     }
344
345 #if ENABLE(SERVICE_WORKER)
346     if (WebServiceWorkerProvider::singleton().cancelFetch(identifier))
347         return;
348 #endif
349
350     RefPtr<WebResourceLoader> loader = m_webResourceLoaders.take(identifier);
351     // Loader may not be registered if we created it, but haven't scheduled yet (a bundle client can decide to cancel such request via willSendRequest).
352     if (!loader)
353         return;
354
355     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::RemoveLoadIdentifier(identifier), 0);
356
357     // It's possible that this WebResourceLoader might be just about to message back to the NetworkProcess (e.g. ContinueWillSendRequest)
358     // but there's no point in doing so anymore.
359     loader->detachFromCoreLoader();
360 }
361
362 void WebLoaderStrategy::setDefersLoading(ResourceLoader* resourceLoader, bool defers)
363 {
364     ResourceLoadIdentifier identifier = resourceLoader->identifier();
365     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::SetDefersLoading(identifier, defers), 0);
366 }
367
368 void WebLoaderStrategy::crossOriginRedirectReceived(ResourceLoader*, const URL&)
369 {
370     // We handle cross origin redirects entirely within the NetworkProcess.
371     // We override this call in the WebProcess to make it a no-op.
372 }
373
374 void WebLoaderStrategy::servePendingRequests(ResourceLoadPriority)
375 {
376     // This overrides the base class version.
377     // We don't need to do anything as this is handled by the network process.
378 }
379
380 void WebLoaderStrategy::suspendPendingRequests()
381 {
382     // Network process does keep requests in pending state.
383 }
384
385 void WebLoaderStrategy::resumePendingRequests()
386 {
387     // Network process does keep requests in pending state.
388 }
389
390 void WebLoaderStrategy::networkProcessCrashed()
391 {
392     RELEASE_LOG_ERROR(Network, "WebLoaderStrategy::networkProcessCrashed: failing all pending resource loaders");
393
394     for (auto& loader : m_webResourceLoaders)
395         scheduleInternallyFailedLoad(*loader.value->resourceLoader());
396
397     m_webResourceLoaders.clear();
398
399     auto pingLoadCompletionHandlers = WTFMove(m_pingLoadCompletionHandlers);
400     for (auto& pingLoadCompletionHandler : pingLoadCompletionHandlers.values())
401         pingLoadCompletionHandler(internalError(URL()), { });
402
403     auto preconnectCompletionHandlers = WTFMove(m_preconnectCompletionHandlers);
404     for (auto& preconnectCompletionHandler : preconnectCompletionHandlers.values())
405         preconnectCompletionHandler(internalError(URL()));
406 }
407
408 static bool shouldClearReferrerOnHTTPSToHTTPRedirect(Frame* frame)
409 {
410     if (frame) {
411         if (auto* document = frame->document())
412             return document->referrerPolicy() == ReferrerPolicy::NoReferrerWhenDowngrade;
413     }
414     return true;
415 }
416
417 void WebLoaderStrategy::loadResourceSynchronously(FrameLoader& frameLoader, unsigned long resourceLoadIdentifier, const ResourceRequest& request, StoredCredentialsPolicy storedCredentialsPolicy, ClientCredentialPolicy clientCredentialPolicy, ResourceError& error, ResourceResponse& response, Vector<char>& data)
418 {
419     WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frameLoader.client());
420     WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : nullptr;
421     WebPage* webPage = webFrame ? webFrame->page() : nullptr;
422
423     NetworkResourceLoadParameters loadParameters;
424     loadParameters.identifier = resourceLoadIdentifier;
425     loadParameters.webPageID = webPage ? webPage->pageID() : 0;
426     loadParameters.webFrameID = webFrame ? webFrame->frameID() : 0;
427     loadParameters.sessionID = webPage ? webPage->sessionID() : PAL::SessionID::defaultSessionID();
428     loadParameters.request = request;
429     loadParameters.contentSniffingPolicy = SniffContent;
430     loadParameters.contentEncodingSniffingPolicy = ContentEncodingSniffingPolicy::Sniff;
431     loadParameters.storedCredentialsPolicy = storedCredentialsPolicy;
432     loadParameters.clientCredentialPolicy = clientCredentialPolicy;
433     loadParameters.shouldClearReferrerOnHTTPSToHTTPRedirect = shouldClearReferrerOnHTTPSToHTTPRedirect(webFrame ? webFrame->coreFrame() : nullptr);
434     loadParameters.shouldRestrictHTTPResponseAccess = RuntimeEnabledFeatures::sharedFeatures().restrictedHTTPResponseAccess();
435
436     data.shrink(0);
437
438     HangDetectionDisabler hangDetectionDisabler;
439
440     if (!WebProcess::singleton().ensureNetworkProcessConnection().connection().sendSync(Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad(loadParameters), Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::Reply(error, response, data), 0, Seconds::infinity(), IPC::SendSyncOption::DoNotProcessIncomingMessagesWhenWaitingForSyncReply)) {
441         RELEASE_LOG_ERROR_IF_ALLOWED(loadParameters.sessionID, "loadResourceSynchronously: failed sending synchronous network process message (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", loadParameters.webPageID, loadParameters.webFrameID, loadParameters.identifier);
442         if (auto* page = webPage->corePage())
443             page->diagnosticLoggingClient().logDiagnosticMessage(WebCore::DiagnosticLoggingKeys::internalErrorKey(), WebCore::DiagnosticLoggingKeys::synchronousMessageFailedKey(), WebCore::ShouldSample::No);
444         response = ResourceResponse();
445         error = internalError(request.url());
446     }
447 }
448
449 static uint64_t generateLoadIdentifier()
450 {
451     static uint64_t identifier = 0;
452     return ++identifier;
453 }
454
455 void WebLoaderStrategy::startPingLoad(Frame& frame, ResourceRequest& request, const HTTPHeaderMap& originalRequestHeaders, const FetchOptions& options, PingLoadCompletionHandler&& completionHandler)
456 {
457     auto* document = frame.document();
458     if (!document) {
459         if (completionHandler)
460             completionHandler(internalError(request.url()), { });
461         return;
462     }
463
464     NetworkResourceLoadParameters loadParameters;
465     loadParameters.identifier = generateLoadIdentifier();
466     loadParameters.request = request;
467     loadParameters.sourceOrigin = &document->securityOrigin();
468     loadParameters.sessionID = frame.page() ? frame.page()->sessionID() : PAL::SessionID::defaultSessionID();
469     loadParameters.storedCredentialsPolicy = options.credentials == FetchOptions::Credentials::Omit ? StoredCredentialsPolicy::DoNotUse : StoredCredentialsPolicy::Use;
470     loadParameters.mode = options.mode;
471     loadParameters.shouldFollowRedirects = options.redirect == FetchOptions::Redirect::Follow;
472     loadParameters.shouldClearReferrerOnHTTPSToHTTPRedirect = shouldClearReferrerOnHTTPSToHTTPRedirect(&frame);
473     loadParameters.shouldRestrictHTTPResponseAccess = RuntimeEnabledFeatures::sharedFeatures().restrictedHTTPResponseAccess();
474     if (!document->shouldBypassMainWorldContentSecurityPolicy()) {
475         if (auto * contentSecurityPolicy = document->contentSecurityPolicy())
476             loadParameters.cspResponseHeaders = contentSecurityPolicy->responseHeaders();
477     }
478
479 #if ENABLE(CONTENT_EXTENSIONS)
480     loadParameters.mainDocumentURL = document->topDocument().url();
481     // FIXME: Instead of passing userContentControllerIdentifier, we should just pass webPageId to NetworkProcess.
482     WebFrameLoaderClient* webFrameLoaderClient = toWebFrameLoaderClient(frame.loader().client());
483     WebFrame* webFrame = webFrameLoaderClient ? webFrameLoaderClient->webFrame() : nullptr;
484     WebPage* webPage = webFrame ? webFrame->page() : nullptr;
485     if (webPage)
486         loadParameters.userContentControllerIdentifier = webPage->userContentControllerIdentifier();
487 #endif
488
489     if (completionHandler)
490         m_pingLoadCompletionHandlers.add(loadParameters.identifier, WTFMove(completionHandler));
491
492     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::LoadPing(WTFMove(loadParameters), originalRequestHeaders), 0);
493 }
494
495 void WebLoaderStrategy::didFinishPingLoad(uint64_t pingLoadIdentifier, ResourceError&& error, ResourceResponse&& response)
496 {
497     if (auto completionHandler = m_pingLoadCompletionHandlers.take(pingLoadIdentifier))
498         completionHandler(WTFMove(error), WTFMove(response));
499 }
500
501 void WebLoaderStrategy::preconnectTo(FrameLoader& frameLoader, const WebCore::URL& url, StoredCredentialsPolicy storedCredentialsPolicy, PreconnectCompletionHandler&& completionHandler)
502 {
503     uint64_t preconnectionIdentifier = generateLoadIdentifier();
504     auto addResult = m_preconnectCompletionHandlers.add(preconnectionIdentifier, WTFMove(completionHandler));
505     ASSERT_UNUSED(addResult, addResult.isNewEntry);
506
507     auto* webFrameLoaderClient = toWebFrameLoaderClient(frameLoader.client());
508     if (!webFrameLoaderClient) {
509         completionHandler(internalError(url));
510         return;
511     }
512     auto* webFrame = webFrameLoaderClient->webFrame();
513     if (!webFrame) {
514         completionHandler(internalError(url));
515         return;
516     }
517     auto* webPage = webFrame->page();
518     if (!webPage) {
519         completionHandler(internalError(url));
520         return;
521     }
522
523     NetworkResourceLoadParameters parameters;
524     parameters.request = ResourceRequest { url };
525     parameters.webPageID = webPage ? webPage->pageID() : 0;
526     parameters.webFrameID = webFrame ? webFrame->frameID() : 0;
527     parameters.sessionID = webPage ? webPage->sessionID() : PAL::SessionID::defaultSessionID();
528     parameters.storedCredentialsPolicy = storedCredentialsPolicy;
529     parameters.shouldPreconnectOnly = PreconnectOnly::Yes;
530     parameters.shouldRestrictHTTPResponseAccess = RuntimeEnabledFeatures::sharedFeatures().restrictedHTTPResponseAccess();
531
532     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::PreconnectTo(preconnectionIdentifier, WTFMove(parameters)), 0);
533 }
534
535 void WebLoaderStrategy::didFinishPreconnection(uint64_t preconnectionIdentifier, ResourceError&& error)
536 {
537     if (auto completionHandler = m_preconnectCompletionHandlers.take(preconnectionIdentifier))
538         completionHandler(WTFMove(error));
539 }
540
541 void WebLoaderStrategy::storeDerivedDataToCache(const SHA1::Digest& bodyHash, const String& type, const String& partition, WebCore::SharedBuffer& data)
542 {
543     NetworkCache::DataKey key { partition, type, bodyHash };
544     IPC::SharedBufferDataReference dataReference { &data };
545     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::StoreDerivedDataToCache(key, dataReference), 0);
546 }
547
548 bool WebLoaderStrategy::isOnLine() const
549 {
550     return m_isOnLine;
551 }
552
553 void WebLoaderStrategy::addOnlineStateChangeListener(Function<void(bool)>&& listener)
554 {
555     WebProcess::singleton().ensureNetworkProcessConnection();
556     m_onlineStateChangeListeners.append(WTFMove(listener));
557 }
558
559 void WebLoaderStrategy::setOnLineState(bool isOnLine)
560 {
561     if (m_isOnLine == isOnLine)
562         return;
563
564     m_isOnLine = isOnLine;
565     for (auto& listener : m_onlineStateChangeListeners)
566         listener(isOnLine);
567 }
568
569 void WebLoaderStrategy::setCaptureExtraNetworkLoadMetricsEnabled(bool enabled)
570 {
571     WebProcess::singleton().ensureNetworkProcessConnection().connection().send(Messages::NetworkConnectionToWebProcess::SetCaptureExtraNetworkLoadMetricsEnabled(enabled), 0);
572 }
573
574 } // namespace WebKit