d48efb11495bf6adad798daeb56d5b8243e165e2
[WebKit-https.git] / Source / WebKit / NetworkProcess / NetworkResourceLoader.cpp
1 /*
2  * Copyright (C) 2012-2019 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 "NetworkResourceLoader.h"
28
29 #include "DataReference.h"
30 #include "FormDataReference.h"
31 #include "Logging.h"
32 #include "NetworkBlobRegistry.h"
33 #include "NetworkCache.h"
34 #include "NetworkConnectionToWebProcess.h"
35 #include "NetworkLoad.h"
36 #include "NetworkLoadChecker.h"
37 #include "NetworkProcess.h"
38 #include "NetworkProcessConnectionMessages.h"
39 #include "SharedBufferDataReference.h"
40 #include "WebCoreArgumentCoders.h"
41 #include "WebErrors.h"
42 #include "WebPageMessages.h"
43 #include "WebResourceLoaderMessages.h"
44 #include "WebsiteDataStoreParameters.h"
45 #include <WebCore/BlobDataFileReference.h>
46 #include <WebCore/CertificateInfo.h>
47 #include <WebCore/ContentSecurityPolicy.h>
48 #include <WebCore/DiagnosticLoggingKeys.h>
49 #include <WebCore/HTTPParsers.h>
50 #include <WebCore/NetworkLoadMetrics.h>
51 #include <WebCore/NetworkStorageSession.h>
52 #include <WebCore/SameSiteInfo.h>
53 #include <WebCore/SecurityOrigin.h>
54 #include <WebCore/SharedBuffer.h>
55 #include <wtf/RunLoop.h>
56
57 #if USE(QUICK_LOOK)
58 #include <WebCore/PreviewLoader.h>
59 #endif
60
61 #define RELEASE_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkResourceLoader::" fmt, this, ##__VA_ARGS__)
62 #define RELEASE_LOG_ERROR_IF_ALLOWED(fmt, ...) RELEASE_LOG_ERROR_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkResourceLoader::" fmt, this, ##__VA_ARGS__)
63
64 namespace WebKit {
65 using namespace WebCore;
66
67 struct NetworkResourceLoader::SynchronousLoadData {
68     SynchronousLoadData(Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply&& reply)
69         : delayedReply(WTFMove(reply))
70     {
71         ASSERT(delayedReply);
72     }
73     ResourceRequest currentRequest;
74     Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply delayedReply;
75     ResourceResponse response;
76     ResourceError error;
77 };
78
79 static void sendReplyToSynchronousRequest(NetworkResourceLoader::SynchronousLoadData& data, const SharedBuffer* buffer)
80 {
81     ASSERT(data.delayedReply);
82     ASSERT(!data.response.isNull() || !data.error.isNull());
83
84     Vector<char> responseBuffer;
85     if (buffer && buffer->size())
86         responseBuffer.append(buffer->data(), buffer->size());
87
88     data.delayedReply(data.error, data.response, responseBuffer);
89     data.delayedReply = nullptr;
90 }
91
92 NetworkResourceLoader::NetworkResourceLoader(NetworkResourceLoadParameters&& parameters, NetworkConnectionToWebProcess& connection, Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply&& synchronousReply)
93     : m_parameters { WTFMove(parameters) }
94     , m_connection { connection }
95     , m_defersLoading { parameters.defersLoading }
96     , m_isAllowedToAskUserForCredentials { m_parameters.clientCredentialPolicy == ClientCredentialPolicy::MayAskClientForCredentials }
97     , m_bufferingTimer { *this, &NetworkResourceLoader::bufferingTimerFired }
98     , m_cache { sessionID().isEphemeral() ? nullptr : connection.networkProcess().cache() }
99     , m_shouldCaptureExtraNetworkLoadMetrics(m_connection->captureExtraNetworkLoadMetricsEnabled())
100 {
101     ASSERT(RunLoop::isMain());
102     // FIXME: This is necessary because of the existence of EmptyFrameLoaderClient in WebCore.
103     //        Once bug 116233 is resolved, this ASSERT can just be "m_webPageID && m_webFrameID"
104     ASSERT((m_parameters.webPageID && m_parameters.webFrameID) || m_parameters.clientCredentialPolicy == ClientCredentialPolicy::CannotAskClientForCredentials);
105
106     if (originalRequest().httpBody()) {
107         for (const auto& element : originalRequest().httpBody()->elements()) {
108             if (auto* blobData = WTF::get_if<FormDataElement::EncodedBlobData>(element.data))
109                 m_fileReferences.appendVector(NetworkBlobRegistry::singleton().filesInBlob(connection, blobData->url));
110         }
111     }
112
113     if (synchronousReply || parameters.shouldRestrictHTTPResponseAccess) {
114         NetworkLoadChecker::LoadType requestLoadType = isMainFrameLoad() ? NetworkLoadChecker::LoadType::MainFrame : NetworkLoadChecker::LoadType::Other;
115         m_networkLoadChecker = std::make_unique<NetworkLoadChecker>(connection.networkProcess(), FetchOptions { m_parameters.options }, m_parameters.sessionID, m_parameters.webPageID, m_parameters.webFrameID, HTTPHeaderMap { m_parameters.originalRequestHeaders }, URL { m_parameters.request.url() }, m_parameters.sourceOrigin.copyRef(), m_parameters.preflightPolicy, originalRequest().httpReferrer(), m_parameters.isHTTPSUpgradeEnabled, shouldCaptureExtraNetworkLoadMetrics(), requestLoadType);
116         if (m_parameters.cspResponseHeaders)
117             m_networkLoadChecker->setCSPResponseHeaders(ContentSecurityPolicyResponseHeaders { m_parameters.cspResponseHeaders.value() });
118 #if ENABLE(CONTENT_EXTENSIONS)
119         m_networkLoadChecker->setContentExtensionController(URL { m_parameters.mainDocumentURL }, m_parameters.userContentControllerIdentifier);
120 #endif
121     }
122     if (synchronousReply)
123         m_synchronousLoadData = std::make_unique<SynchronousLoadData>(WTFMove(synchronousReply));
124 }
125
126 NetworkResourceLoader::~NetworkResourceLoader()
127 {
128     ASSERT(RunLoop::isMain());
129     ASSERT(!m_networkLoad);
130     ASSERT(!isSynchronous() || !m_synchronousLoadData->delayedReply);
131     if (m_responseCompletionHandler)
132         m_responseCompletionHandler(PolicyAction::Ignore);
133 }
134
135 bool NetworkResourceLoader::canUseCache(const ResourceRequest& request) const
136 {
137     if (!m_cache)
138         return false;
139     ASSERT(!sessionID().isEphemeral());
140
141     if (!request.url().protocolIsInHTTPFamily())
142         return false;
143     if (originalRequest().cachePolicy() == WebCore::ResourceRequestCachePolicy::DoNotUseAnyCache)
144         return false;
145
146     return true;
147 }
148
149 bool NetworkResourceLoader::canUseCachedRedirect(const ResourceRequest& request) const
150 {
151     if (!canUseCache(request) || m_cacheEntryForMaxAgeCapValidation)
152         return false;
153     // Limit cached redirects to avoid cycles and other trouble.
154     // Networking layer follows over 30 redirects but caching that many seems unnecessary.
155     static const unsigned maximumCachedRedirectCount { 5 };
156     if (m_redirectCount > maximumCachedRedirectCount)
157         return false;
158
159     return true;
160 }
161
162 bool NetworkResourceLoader::isSynchronous() const
163 {
164     return !!m_synchronousLoadData;
165 }
166
167 void NetworkResourceLoader::start()
168 {
169     ASSERT(RunLoop::isMain());
170
171     m_networkActivityTracker = m_connection->startTrackingResourceLoad(m_parameters.webPageID, m_parameters.identifier, isMainResource(), sessionID());
172
173     if (m_defersLoading) {
174         RELEASE_LOG_IF_ALLOWED("start: Loading is deferred (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d, parentPID = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous(), m_parameters.parentPID);
175         return;
176     }
177
178     ASSERT(!m_wasStarted);
179     m_wasStarted = true;
180
181     if (m_networkLoadChecker) {
182         m_networkLoadChecker->check(ResourceRequest { originalRequest() }, this, [this] (auto&& result) {
183             WTF::switchOn(result,
184                 [this] (ResourceError& error) {
185                     RELEASE_LOG_IF_ALLOWED("start: error checking (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d, parentPID = %d, error.domain = %{public}s, error.code = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, this->isMainResource(), this->isSynchronous(), m_parameters.parentPID, error.domain().utf8().data(), error.errorCode());
186                     if (!error.isCancellation())
187                         this->didFailLoading(error);
188                 },
189                 [this] (NetworkLoadChecker::RedirectionTriplet& triplet) {
190                     this->m_isWaitingContinueWillSendRequestForCachedRedirect = true;
191                     this->willSendRedirectedRequest(WTFMove(triplet.request), WTFMove(triplet.redirectRequest), WTFMove(triplet.redirectResponse));
192                     RELEASE_LOG_IF_ALLOWED("start: synthetic redirect sent because request URL was modified (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d, parentPID = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, this->isMainResource(), this->isSynchronous(), m_parameters.parentPID);
193                 },
194                 [this] (ResourceRequest& request) {
195                     if (this->canUseCache(request)) {
196                         RELEASE_LOG_IF_ALLOWED("start: Checking cache for resource (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d, parentPID = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, this->isMainResource(), this->isSynchronous(), m_parameters.parentPID);
197                         this->retrieveCacheEntry(request);
198                         return;
199                     }
200
201                     this->startNetworkLoad(WTFMove(request), FirstLoad::Yes);
202                 }
203             );
204         });
205         return;
206     }
207     // FIXME: Remove that code path once m_networkLoadChecker is used for all network loads.
208     if (canUseCache(originalRequest())) {
209         RELEASE_LOG_IF_ALLOWED("start: Checking cache for resource (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d, parentPID = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous(), m_parameters.parentPID);
210         retrieveCacheEntry(originalRequest());
211         return;
212     }
213
214     startNetworkLoad(ResourceRequest { originalRequest() }, FirstLoad::Yes);
215 }
216
217 void NetworkResourceLoader::retrieveCacheEntry(const ResourceRequest& request)
218 {
219     ASSERT(canUseCache(request));
220
221     RefPtr<NetworkResourceLoader> loader(this);
222     m_cache->retrieve(request, { m_parameters.webPageID, m_parameters.webFrameID }, [this, loader = WTFMove(loader), request = ResourceRequest { request }](auto entry, auto info) mutable {
223         if (loader->hasOneRef()) {
224             // The loader has been aborted and is only held alive by this lambda.
225             return;
226         }
227
228         loader->logSlowCacheRetrieveIfNeeded(info);
229
230         if (!entry) {
231             RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Resource not in cache (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
232             loader->startNetworkLoad(WTFMove(request), FirstLoad::Yes);
233             return;
234         }
235 #if ENABLE(RESOURCE_LOAD_STATISTICS)
236         if (entry->hasReachedPrevalentResourceAgeCap()) {
237             RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Resource has reached prevalent resource age cap (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
238             m_cacheEntryForMaxAgeCapValidation = WTFMove(entry);
239             ResourceRequest revalidationRequest = originalRequest();
240             loader->startNetworkLoad(WTFMove(revalidationRequest), FirstLoad::Yes);
241             return;
242         }
243 #endif
244         if (entry->redirectRequest()) {
245             RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Handling redirect (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
246             loader->dispatchWillSendRequestForCacheEntry(WTFMove(request), WTFMove(entry));
247             return;
248         }
249         if (loader->m_parameters.needsCertificateInfo && !entry->response().certificateInfo()) {
250             RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Resource does not have required certificate (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
251             loader->startNetworkLoad(WTFMove(request), FirstLoad::Yes);
252             return;
253         }
254         if (entry->needsValidation() || request.cachePolicy() == WebCore::ResourceRequestCachePolicy::RefreshAnyCacheData) {
255             RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Validating cache entry (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
256             loader->validateCacheEntry(WTFMove(entry));
257             return;
258         }
259         RELEASE_LOG_IF_ALLOWED("retrieveCacheEntry: Retrieved resource from cache (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
260         loader->didRetrieveCacheEntry(WTFMove(entry));
261     });
262 }
263
264 void NetworkResourceLoader::startNetworkLoad(ResourceRequest&& request, FirstLoad load)
265 {
266     if (load == FirstLoad::Yes) {
267         RELEASE_LOG_IF_ALLOWED("startNetworkLoad: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isMainResource = %d, isSynchronous = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, isMainResource(), isSynchronous());
268
269         consumeSandboxExtensions();
270
271         if (isSynchronous() || m_parameters.maximumBufferingTime > 0_s)
272             m_bufferedData = SharedBuffer::create();
273
274         if (canUseCache(request))
275             m_bufferedDataForCache = SharedBuffer::create();
276     }
277
278     NetworkLoadParameters parameters = m_parameters;
279     parameters.defersLoading = m_defersLoading;
280     parameters.networkActivityTracker = m_networkActivityTracker;
281     if (m_networkLoadChecker)
282         parameters.storedCredentialsPolicy = m_networkLoadChecker->storedCredentialsPolicy();
283
284     if (request.url().protocolIsBlob())
285         parameters.blobFileReferences = NetworkBlobRegistry::singleton().filesInBlob(m_connection, originalRequest().url());
286
287     auto* networkSession = m_connection->networkProcess().networkSession(parameters.sessionID);
288     if (!networkSession && parameters.sessionID.isEphemeral()) {
289         m_connection->networkProcess().addWebsiteDataStore(WebsiteDataStoreParameters::privateSessionParameters(parameters.sessionID));
290         networkSession = m_connection->networkProcess().networkSession(parameters.sessionID);
291     }
292     if (!networkSession) {
293         WTFLogAlways("Attempted to create a NetworkLoad with a session (id=%" PRIu64 ") that does not exist.", parameters.sessionID.sessionID());
294         RELEASE_LOG_ERROR_IF_ALLOWED("startNetworkLoad: Attempted to create a NetworkLoad with a session that does not exist (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", sessionID=%" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, parameters.sessionID.sessionID());
295         m_connection->networkProcess().logDiagnosticMessage(m_parameters.webPageID, WebCore::DiagnosticLoggingKeys::internalErrorKey(), WebCore::DiagnosticLoggingKeys::invalidSessionIDKey(), WebCore::ShouldSample::No);
296         didFailLoading(internalError(request.url()));
297         return;
298     }
299
300     parameters.request = WTFMove(request);
301     m_networkLoad = std::make_unique<NetworkLoad>(*this, WTFMove(parameters), *networkSession);
302
303     RELEASE_LOG_IF_ALLOWED("startNetworkLoad: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", description = %{public}s)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, m_networkLoad->description().utf8().data());
304
305     if (m_defersLoading) {
306         RELEASE_LOG_IF_ALLOWED("startNetworkLoad: Created, but deferred (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")",
307             m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
308     }
309 }
310
311 void NetworkResourceLoader::setDefersLoading(bool defers)
312 {
313     if (m_defersLoading == defers)
314         return;
315     m_defersLoading = defers;
316
317     if (defers)
318         RELEASE_LOG_IF_ALLOWED("setDefersLoading: Deferring resource load (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
319     else
320         RELEASE_LOG_IF_ALLOWED("setDefersLoading: Resuming deferred resource load (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
321
322     if (m_networkLoad) {
323         m_networkLoad->setDefersLoading(defers);
324         return;
325     }
326
327     if (!m_defersLoading && !m_wasStarted)
328         start();
329     else
330         RELEASE_LOG_IF_ALLOWED("setDefersLoading: defers = %d, but nothing to do (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_defersLoading, m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
331 }
332
333 void NetworkResourceLoader::cleanup(LoadResult result)
334 {
335     ASSERT(RunLoop::isMain());
336
337     m_connection->stopTrackingResourceLoad(m_parameters.identifier,
338         result == LoadResult::Success ? NetworkActivityTracker::CompletionCode::Success :
339         result == LoadResult::Failure ? NetworkActivityTracker::CompletionCode::Failure :
340         NetworkActivityTracker::CompletionCode::None);
341
342     m_bufferingTimer.stop();
343
344     invalidateSandboxExtensions();
345
346     m_networkLoad = nullptr;
347
348     // This will cause NetworkResourceLoader to be destroyed and therefore we do it last.
349     m_connection->didCleanupResourceLoader(*this);
350 }
351
352 void NetworkResourceLoader::convertToDownload(DownloadID downloadID, const ResourceRequest& request, const ResourceResponse& response)
353 {
354     // This can happen if the resource came from the disk cache.
355     if (!m_networkLoad) {
356         m_connection->networkProcess().downloadManager().startDownload(m_connection.ptr(), m_parameters.sessionID, downloadID, request);
357         abort();
358         return;
359     }
360
361     ASSERT(m_responseCompletionHandler);
362     m_connection->networkProcess().downloadManager().convertNetworkLoadToDownload(downloadID, std::exchange(m_networkLoad, nullptr), WTFMove(m_responseCompletionHandler), WTFMove(m_fileReferences), request, response);
363 }
364
365 void NetworkResourceLoader::abort()
366 {
367     ASSERT(RunLoop::isMain());
368
369     RELEASE_LOG_IF_ALLOWED("abort: Canceling resource load (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")",
370         m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
371
372     if (m_networkLoad) {
373         if (canUseCache(m_networkLoad->currentRequest())) {
374             // We might already have used data from this incomplete load. Ensure older versions don't remain in the cache after cancel.
375             if (!m_response.isNull())
376                 m_cache->remove(m_networkLoad->currentRequest());
377         }
378         m_networkLoad->cancel();
379     }
380
381     cleanup(LoadResult::Cancel);
382 }
383
384 bool NetworkResourceLoader::shouldInterruptLoadForXFrameOptions(const String& xFrameOptions, const URL& url)
385 {
386     if (isMainFrameLoad())
387         return false;
388
389     switch (parseXFrameOptionsHeader(xFrameOptions)) {
390     case XFrameOptionsNone:
391     case XFrameOptionsAllowAll:
392         return false;
393     case XFrameOptionsDeny:
394         return true;
395     case XFrameOptionsSameOrigin: {
396         auto origin = SecurityOrigin::create(url);
397         auto topFrameOrigin = m_parameters.frameAncestorOrigins.last();
398         if (!origin->isSameSchemeHostPort(*topFrameOrigin))
399             return true;
400         for (auto& ancestorOrigin : m_parameters.frameAncestorOrigins) {
401             if (!origin->isSameSchemeHostPort(*ancestorOrigin))
402                 return true;
403         }
404         return false;
405     }
406     case XFrameOptionsConflict: {
407         String errorMessage = "Multiple 'X-Frame-Options' headers with conflicting values ('" + xFrameOptions + "') encountered when loading '" + url.stringCenterEllipsizedToLength() + "'. Falling back to 'DENY'.";
408         send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID,  MessageSource::JS, MessageLevel::Error, errorMessage, identifier() }, m_parameters.webPageID);
409         return true;
410     }
411     case XFrameOptionsInvalid: {
412         String errorMessage = "Invalid 'X-Frame-Options' header encountered when loading '" + url.stringCenterEllipsizedToLength() + "': '" + xFrameOptions + "' is not a recognized directive. The header will be ignored.";
413         send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID,  MessageSource::JS, MessageLevel::Error, errorMessage, identifier() }, m_parameters.webPageID);
414         return false;
415     }
416     }
417     ASSERT_NOT_REACHED();
418     return false;
419 }
420
421 bool NetworkResourceLoader::shouldInterruptLoadForCSPFrameAncestorsOrXFrameOptions(const ResourceResponse& response)
422 {
423     ASSERT(isMainResource());
424
425 #if USE(QUICK_LOOK)
426     if (PreviewLoader::shouldCreateForMIMEType(response.mimeType()))
427         return false;
428 #endif
429
430     auto url = response.url();
431     ContentSecurityPolicy contentSecurityPolicy { URL { url }, this };
432     contentSecurityPolicy.didReceiveHeaders(ContentSecurityPolicyResponseHeaders { response }, originalRequest().httpReferrer());
433     if (!contentSecurityPolicy.allowFrameAncestors(m_parameters.frameAncestorOrigins, url))
434         return true;
435     String xFrameOptions = m_response.httpHeaderField(HTTPHeaderName::XFrameOptions);
436     if (!xFrameOptions.isNull() && shouldInterruptLoadForXFrameOptions(xFrameOptions, response.url())) {
437         String errorMessage = "Refused to display '" + response.url().stringCenterEllipsizedToLength() + "' in a frame because it set 'X-Frame-Options' to '" + xFrameOptions + "'.";
438         send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID,  MessageSource::Security, MessageLevel::Error, errorMessage, identifier() }, m_parameters.webPageID);
439         return true;
440     }
441     return false;
442 }
443
444 void NetworkResourceLoader::didReceiveResponse(ResourceResponse&& receivedResponse, ResponseCompletionHandler&& completionHandler)
445 {
446     RELEASE_LOG_IF_ALLOWED("didReceiveResponse: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", httpStatusCode = %d, length = %" PRId64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, receivedResponse.httpStatusCode(), receivedResponse.expectedContentLength());
447
448     m_response = WTFMove(receivedResponse);
449
450     if (shouldCaptureExtraNetworkLoadMetrics() && m_networkLoadChecker) {
451         auto information = m_networkLoadChecker->takeNetworkLoadInformation();
452         information.response = m_response;
453         m_connection->addNetworkLoadInformation(identifier(), WTFMove(information));
454     }
455
456     // For multipart/x-mixed-replace didReceiveResponseAsync gets called multiple times and buffering would require special handling.
457     if (!isSynchronous() && m_response.isMultipart())
458         m_bufferedData = nullptr;
459
460     if (m_response.isMultipart())
461         m_bufferedDataForCache = nullptr;
462
463     if (m_cacheEntryForValidation) {
464         bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
465         if (validationSucceeded) {
466             m_cacheEntryForValidation = m_cache->update(originalRequest(), { m_parameters.webPageID, m_parameters.webFrameID }, *m_cacheEntryForValidation, m_response);
467             // If the request was conditional then this revalidation was not triggered by the network cache and we pass the 304 response to WebCore.
468             if (originalRequest().isConditional())
469                 m_cacheEntryForValidation = nullptr;
470         } else
471             m_cacheEntryForValidation = nullptr;
472     }
473     if (m_cacheEntryForValidation)
474         return completionHandler(PolicyAction::Use);
475
476     if (isMainResource() && shouldInterruptLoadForCSPFrameAncestorsOrXFrameOptions(m_response)) {
477         auto response = sanitizeResponseIfPossible(ResourceResponse { m_response }, ResourceResponse::SanitizationType::CrossOriginSafe);
478         send(Messages::WebResourceLoader::StopLoadingAfterXFrameOptionsOrContentSecurityPolicyDenied { response });
479         return completionHandler(PolicyAction::Ignore);
480     }
481
482     if (m_networkLoadChecker) {
483         auto error = m_networkLoadChecker->validateResponse(m_response);
484         if (!error.isNull()) {
485             RunLoop::main().dispatch([protectedThis = makeRef(*this), error = WTFMove(error)] {
486                 if (protectedThis->m_networkLoad)
487                     protectedThis->didFailLoading(error);
488             });
489             return completionHandler(PolicyAction::Ignore);
490         }
491     }
492
493     auto response = sanitizeResponseIfPossible(ResourceResponse { m_response }, ResourceResponse::SanitizationType::CrossOriginSafe);
494     if (isSynchronous()) {
495         m_synchronousLoadData->response = WTFMove(response);
496         return completionHandler(PolicyAction::Use);
497     }
498
499     // We wait to receive message NetworkResourceLoader::ContinueDidReceiveResponse before continuing a load for
500     // a main resource because the embedding client must decide whether to allow the load.
501     bool willWaitForContinueDidReceiveResponse = isMainResource();
502     send(Messages::WebResourceLoader::DidReceiveResponse { response, willWaitForContinueDidReceiveResponse });
503     if (willWaitForContinueDidReceiveResponse)
504         m_responseCompletionHandler = WTFMove(completionHandler);
505     else
506         completionHandler(PolicyAction::Use);
507 }
508
509 void NetworkResourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, int reportedEncodedDataLength)
510 {
511     if (!m_numBytesReceived)
512         RELEASE_LOG_IF_ALLOWED("didReceiveBuffer: Started receiving data (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
513     m_numBytesReceived += buffer->size();
514
515     ASSERT(!m_cacheEntryForValidation);
516
517     if (m_bufferedDataForCache) {
518         // Prevent memory growth in case of streaming data.
519         const size_t maximumCacheBufferSize = 10 * 1024 * 1024;
520         if (m_bufferedDataForCache->size() + buffer->size() <= maximumCacheBufferSize)
521             m_bufferedDataForCache->append(buffer.get());
522         else
523             m_bufferedDataForCache = nullptr;
524     }
525     // FIXME: At least on OS X Yosemite we always get -1 from the resource handle.
526     unsigned encodedDataLength = reportedEncodedDataLength >= 0 ? reportedEncodedDataLength : buffer->size();
527
528     if (m_bufferedData) {
529         m_bufferedData->append(buffer.get());
530         m_bufferedDataEncodedDataLength += encodedDataLength;
531         startBufferingTimerIfNeeded();
532         return;
533     }
534     sendBuffer(buffer, encodedDataLength);
535 }
536
537 void NetworkResourceLoader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
538 {
539     RELEASE_LOG_IF_ALLOWED("didFinishLoading: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", length = %zd)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, m_numBytesReceived);
540
541     if (shouldCaptureExtraNetworkLoadMetrics())
542         m_connection->addNetworkLoadInformationMetrics(identifier(), networkLoadMetrics);
543
544     if (m_cacheEntryForValidation) {
545         // 304 Not Modified
546         ASSERT(m_response.httpStatusCode() == 304);
547         LOG(NetworkCache, "(NetworkProcess) revalidated");
548         didRetrieveCacheEntry(WTFMove(m_cacheEntryForValidation));
549         return;
550     }
551
552 #if ENABLE(RESOURCE_LOAD_STATISTICS) && !RELEASE_LOG_DISABLED
553     if (shouldLogCookieInformation(m_connection, sessionID()))
554         logCookieInformation();
555 #endif
556
557     if (isSynchronous())
558         sendReplyToSynchronousRequest(*m_synchronousLoadData, m_bufferedData.get());
559     else {
560         if (m_bufferedData && !m_bufferedData->isEmpty()) {
561             // FIXME: Pass a real value or remove the encoded data size feature.
562             sendBuffer(*m_bufferedData, -1);
563         }
564         send(Messages::WebResourceLoader::DidFinishResourceLoad(networkLoadMetrics));
565     }
566
567     tryStoreAsCacheEntry();
568
569     cleanup(LoadResult::Success);
570 }
571
572 void NetworkResourceLoader::didFailLoading(const ResourceError& error)
573 {
574     RELEASE_LOG_IF_ALLOWED("didFailLoading: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ", isTimeout = %d, isCancellation = %d, isAccessControl = %d, errCode = %d)", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier, error.isTimeout(), error.isCancellation(), error.isAccessControl(), error.errorCode());
575
576     if (shouldCaptureExtraNetworkLoadMetrics())
577         m_connection->removeNetworkLoadInformation(identifier());
578
579     ASSERT(!error.isNull());
580
581     m_cacheEntryForValidation = nullptr;
582
583     if (isSynchronous()) {
584         m_synchronousLoadData->error = error;
585         sendReplyToSynchronousRequest(*m_synchronousLoadData, nullptr);
586     } else if (auto* connection = messageSenderConnection())
587         connection->send(Messages::WebResourceLoader::DidFailResourceLoad(error), messageSenderDestinationID());
588
589     cleanup(LoadResult::Failure);
590 }
591
592 void NetworkResourceLoader::didBlockAuthenticationChallenge()
593 {
594     send(Messages::WebResourceLoader::DidBlockAuthenticationChallenge());
595 }
596
597 Optional<Seconds> NetworkResourceLoader::validateCacheEntryForMaxAgeCapValidation(const ResourceRequest& request, const ResourceRequest& redirectRequest, const ResourceResponse& redirectResponse)
598 {
599 #if ENABLE(RESOURCE_LOAD_STATISTICS)
600     bool existingCacheEntryMatchesNewResponse = false;
601     if (m_cacheEntryForMaxAgeCapValidation) {
602         ASSERT(redirectResponse.source() == ResourceResponse::Source::Network);
603         ASSERT(redirectResponse.isRedirection());
604         if (redirectResponse.httpHeaderField(WebCore::HTTPHeaderName::Location) == m_cacheEntryForMaxAgeCapValidation->response().httpHeaderField(WebCore::HTTPHeaderName::Location))
605             existingCacheEntryMatchesNewResponse = true;
606
607         m_cache->remove(m_cacheEntryForMaxAgeCapValidation->key());
608         m_cacheEntryForMaxAgeCapValidation = nullptr;
609     }
610     
611     if (!existingCacheEntryMatchesNewResponse) {
612         if (auto networkStorageSession = WebCore::NetworkStorageSession::storageSession(sessionID()))
613             return networkStorageSession->maxAgeCacheCap(request);
614     }
615 #endif
616     return WTF::nullopt;
617 }
618
619 void NetworkResourceLoader::willSendRedirectedRequest(ResourceRequest&& request, ResourceRequest&& redirectRequest, ResourceResponse&& redirectResponse)
620 {
621     ++m_redirectCount;
622
623     auto maxAgeCap = validateCacheEntryForMaxAgeCapValidation(request, redirectRequest, redirectResponse);
624     if (redirectResponse.source() == ResourceResponse::Source::Network && canUseCachedRedirect(request))
625         m_cache->storeRedirect(request, redirectResponse, redirectRequest, maxAgeCap);
626
627     if (m_networkLoadChecker) {
628         m_networkLoadChecker->storeRedirectionIfNeeded(request, redirectResponse);
629         m_networkLoadChecker->checkRedirection(WTFMove(request), WTFMove(redirectRequest), WTFMove(redirectResponse), this, [protectedThis = makeRef(*this), this, storedCredentialsPolicy = m_networkLoadChecker->storedCredentialsPolicy()](auto&& result) mutable {
630             if (!result.has_value()) {
631                 if (result.error().isCancellation())
632                     return;
633
634                 this->didFailLoading(result.error());
635                 return;
636             }
637
638             if (m_parameters.options.redirect == FetchOptions::Redirect::Manual) {
639                 this->didFinishWithRedirectResponse(WTFMove(result->redirectResponse));
640                 return;
641             }
642
643             if (this->isSynchronous()) {
644                 if (storedCredentialsPolicy != m_networkLoadChecker->storedCredentialsPolicy()) {
645                     // We need to restart the load to update the session according the new credential policy.
646                     this->restartNetworkLoad(WTFMove(result->redirectRequest));
647                     return;
648                 }
649
650                 // We do not support prompting for credentials for synchronous loads. If we ever change this policy then
651                 // we need to take care to prompt if and only if request and redirectRequest are not mixed content.
652                 this->continueWillSendRequest(WTFMove(result->redirectRequest), false);
653                 return;
654             }
655
656             m_shouldRestartLoad = storedCredentialsPolicy != m_networkLoadChecker->storedCredentialsPolicy();
657             this->continueWillSendRedirectedRequest(WTFMove(result->request), WTFMove(result->redirectRequest), WTFMove(result->redirectResponse));
658         });
659         return;
660     }
661     continueWillSendRedirectedRequest(WTFMove(request), WTFMove(redirectRequest), WTFMove(redirectResponse));
662 }
663
664 void NetworkResourceLoader::continueWillSendRedirectedRequest(ResourceRequest&& request, ResourceRequest&& redirectRequest, ResourceResponse&& redirectResponse)
665 {
666     ASSERT(!isSynchronous());
667
668     send(Messages::WebResourceLoader::WillSendRequest(redirectRequest, sanitizeResponseIfPossible(WTFMove(redirectResponse), ResourceResponse::SanitizationType::Redirection)));
669 }
670
671 void NetworkResourceLoader::didFinishWithRedirectResponse(ResourceResponse&& redirectResponse)
672 {
673     redirectResponse.setType(ResourceResponse::Type::Opaqueredirect);
674     didReceiveResponse(WTFMove(redirectResponse), [] (auto) { });
675
676     WebCore::NetworkLoadMetrics networkLoadMetrics;
677     networkLoadMetrics.markComplete();
678     networkLoadMetrics.responseBodyBytesReceived = 0;
679     networkLoadMetrics.responseBodyDecodedSize = 0;
680     send(Messages::WebResourceLoader::DidFinishResourceLoad { networkLoadMetrics });
681
682     cleanup(LoadResult::Success);
683 }
684
685 ResourceResponse NetworkResourceLoader::sanitizeResponseIfPossible(ResourceResponse&& response, ResourceResponse::SanitizationType type)
686 {
687     if (m_parameters.shouldRestrictHTTPResponseAccess)
688         response.sanitizeHTTPHeaderFields(type);
689
690     return WTFMove(response);
691 }
692
693 void NetworkResourceLoader::restartNetworkLoad(WebCore::ResourceRequest&& newRequest)
694 {
695     if (m_networkLoad)
696         m_networkLoad->cancel();
697
698     startNetworkLoad(WTFMove(newRequest), FirstLoad::No);
699 }
700
701 void NetworkResourceLoader::continueWillSendRequest(ResourceRequest&& newRequest, bool isAllowedToAskUserForCredentials)
702 {
703     if (m_shouldRestartLoad) {
704         m_shouldRestartLoad = false;
705         restartNetworkLoad(WTFMove(newRequest));
706         return;
707     }
708
709     if (m_networkLoadChecker) {
710         // FIXME: We should be doing this check when receiving the redirection and not allow about protocol as per fetch spec.
711         if (!newRequest.url().protocolIsInHTTPFamily() && !newRequest.url().protocolIsAbout() && m_redirectCount) {
712             didFailLoading(ResourceError { String { }, 0, newRequest.url(), "Redirection to URL with a scheme that is not HTTP(S)"_s, ResourceError::Type::AccessControl });
713             return;
714         }
715     }
716
717     RELEASE_LOG_IF_ALLOWED("continueWillSendRequest: (pageID = %" PRIu64 ", frameID = %" PRIu64 ", resourceID = %" PRIu64 ")", m_parameters.webPageID, m_parameters.webFrameID, m_parameters.identifier);
718
719     m_isAllowedToAskUserForCredentials = isAllowedToAskUserForCredentials;
720
721     // If there is a match in the network cache, we need to reuse the original cache policy and partition.
722     newRequest.setCachePolicy(originalRequest().cachePolicy());
723     newRequest.setCachePartition(originalRequest().cachePartition());
724
725     if (m_isWaitingContinueWillSendRequestForCachedRedirect) {
726         m_isWaitingContinueWillSendRequestForCachedRedirect = false;
727
728         LOG(NetworkCache, "(NetworkProcess) Retrieving cached redirect");
729
730         if (canUseCachedRedirect(newRequest))
731             retrieveCacheEntry(newRequest);
732         else
733             startNetworkLoad(WTFMove(newRequest), FirstLoad::Yes);
734
735         return;
736     }
737
738     if (m_networkLoad)
739         m_networkLoad->continueWillSendRequest(WTFMove(newRequest));
740 }
741
742 void NetworkResourceLoader::continueDidReceiveResponse()
743 {
744     if (m_cacheEntryWaitingForContinueDidReceiveResponse) {
745         sendResultForCacheEntry(WTFMove(m_cacheEntryWaitingForContinueDidReceiveResponse));
746         cleanup(LoadResult::Success);
747         return;
748     }
749
750     if (m_responseCompletionHandler)
751         m_responseCompletionHandler(PolicyAction::Use);
752 }
753
754 void NetworkResourceLoader::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
755 {
756     if (!isSynchronous())
757         send(Messages::WebResourceLoader::DidSendData(bytesSent, totalBytesToBeSent));
758 }
759
760 void NetworkResourceLoader::startBufferingTimerIfNeeded()
761 {
762     if (isSynchronous())
763         return;
764     if (m_bufferingTimer.isActive())
765         return;
766     m_bufferingTimer.startOneShot(m_parameters.maximumBufferingTime);
767 }
768
769 void NetworkResourceLoader::bufferingTimerFired()
770 {
771     ASSERT(m_bufferedData);
772     ASSERT(m_networkLoad);
773
774     if (m_bufferedData->isEmpty())
775         return;
776
777     send(Messages::WebResourceLoader::DidReceiveData({ *m_bufferedData }, m_bufferedDataEncodedDataLength));
778
779     m_bufferedData = SharedBuffer::create();
780     m_bufferedDataEncodedDataLength = 0;
781 }
782
783 void NetworkResourceLoader::sendBuffer(SharedBuffer& buffer, size_t encodedDataLength)
784 {
785     ASSERT(!isSynchronous());
786
787     send(Messages::WebResourceLoader::DidReceiveData({ buffer }, encodedDataLength));
788 }
789
790 void NetworkResourceLoader::tryStoreAsCacheEntry()
791 {
792     if (!canUseCache(m_networkLoad->currentRequest()))
793         return;
794     if (!m_bufferedDataForCache)
795         return;
796
797     m_cache->store(m_networkLoad->currentRequest(), m_response, WTFMove(m_bufferedDataForCache), [loader = makeRef(*this)](auto& mappedBody) mutable {
798 #if ENABLE(SHAREABLE_RESOURCE)
799         if (mappedBody.shareableResourceHandle.isNull())
800             return;
801         LOG(NetworkCache, "(NetworkProcess) sending DidCacheResource");
802         loader->send(Messages::NetworkProcessConnection::DidCacheResource(loader->originalRequest(), mappedBody.shareableResourceHandle, loader->sessionID()));
803 #endif
804     });
805 }
806
807 void NetworkResourceLoader::didRetrieveCacheEntry(std::unique_ptr<NetworkCache::Entry> entry)
808 {
809     auto response = entry->response();
810
811     if (isMainResource() && shouldInterruptLoadForCSPFrameAncestorsOrXFrameOptions(response)) {
812         response = sanitizeResponseIfPossible(WTFMove(response), ResourceResponse::SanitizationType::CrossOriginSafe);
813         send(Messages::WebResourceLoader::StopLoadingAfterXFrameOptionsOrContentSecurityPolicyDenied { response });
814         return;
815     }
816     if (m_networkLoadChecker) {
817         auto error = m_networkLoadChecker->validateResponse(response);
818         if (!error.isNull()) {
819             didFailLoading(error);
820             return;
821         }
822     }
823
824     response = sanitizeResponseIfPossible(WTFMove(response), ResourceResponse::SanitizationType::CrossOriginSafe);
825     if (isSynchronous()) {
826         m_synchronousLoadData->response = WTFMove(response);
827         sendReplyToSynchronousRequest(*m_synchronousLoadData, entry->buffer());
828         cleanup(LoadResult::Success);
829         return;
830     }
831
832     bool needsContinueDidReceiveResponseMessage = isMainResource();
833     send(Messages::WebResourceLoader::DidReceiveResponse { response, needsContinueDidReceiveResponseMessage });
834
835     if (needsContinueDidReceiveResponseMessage)
836         m_cacheEntryWaitingForContinueDidReceiveResponse = WTFMove(entry);
837     else {
838         sendResultForCacheEntry(WTFMove(entry));
839         cleanup(LoadResult::Success);
840     }
841 }
842
843 void NetworkResourceLoader::sendResultForCacheEntry(std::unique_ptr<NetworkCache::Entry> entry)
844 {
845 #if ENABLE(SHAREABLE_RESOURCE)
846     if (!entry->shareableResourceHandle().isNull()) {
847         send(Messages::WebResourceLoader::DidReceiveResource(entry->shareableResourceHandle()));
848         return;
849     }
850 #endif
851
852 #if ENABLE(RESOURCE_LOAD_STATISTICS) && !RELEASE_LOG_DISABLED
853     if (shouldLogCookieInformation(m_connection, sessionID()))
854         logCookieInformation();
855 #endif
856
857     WebCore::NetworkLoadMetrics networkLoadMetrics;
858     networkLoadMetrics.markComplete();
859     networkLoadMetrics.requestHeaderBytesSent = 0;
860     networkLoadMetrics.requestBodyBytesSent = 0;
861     networkLoadMetrics.responseHeaderBytesReceived = 0;
862     networkLoadMetrics.responseBodyBytesReceived = 0;
863     networkLoadMetrics.responseBodyDecodedSize = 0;
864
865     sendBuffer(*entry->buffer(), entry->buffer()->size());
866     send(Messages::WebResourceLoader::DidFinishResourceLoad(networkLoadMetrics));
867 }
868
869 void NetworkResourceLoader::validateCacheEntry(std::unique_ptr<NetworkCache::Entry> entry)
870 {
871     ASSERT(!m_networkLoad);
872
873     // If the request is already conditional then the revalidation was not triggered by the disk cache
874     // and we should not overwrite the existing conditional headers.
875     ResourceRequest revalidationRequest = originalRequest();
876     if (!revalidationRequest.isConditional()) {
877         String eTag = entry->response().httpHeaderField(HTTPHeaderName::ETag);
878         String lastModified = entry->response().httpHeaderField(HTTPHeaderName::LastModified);
879         if (!eTag.isEmpty())
880             revalidationRequest.setHTTPHeaderField(HTTPHeaderName::IfNoneMatch, eTag);
881         if (!lastModified.isEmpty())
882             revalidationRequest.setHTTPHeaderField(HTTPHeaderName::IfModifiedSince, lastModified);
883     }
884
885     m_cacheEntryForValidation = WTFMove(entry);
886
887     startNetworkLoad(WTFMove(revalidationRequest), FirstLoad::Yes);
888 }
889
890 void NetworkResourceLoader::dispatchWillSendRequestForCacheEntry(ResourceRequest&& request, std::unique_ptr<NetworkCache::Entry>&& entry)
891 {
892     ASSERT(entry->redirectRequest());
893     ASSERT(!m_isWaitingContinueWillSendRequestForCachedRedirect);
894
895     LOG(NetworkCache, "(NetworkProcess) Executing cached redirect");
896
897     m_isWaitingContinueWillSendRequestForCachedRedirect = true;
898     willSendRedirectedRequest(WTFMove(request), ResourceRequest { *entry->redirectRequest() }, ResourceResponse { entry->response() });
899 }
900
901 IPC::Connection* NetworkResourceLoader::messageSenderConnection()
902 {
903     return &connectionToWebProcess().connection();
904 }
905
906 void NetworkResourceLoader::consumeSandboxExtensions()
907 {
908     ASSERT(!m_didConsumeSandboxExtensions);
909
910     for (auto& extension : m_parameters.requestBodySandboxExtensions)
911         extension->consume();
912
913     if (auto& extension = m_parameters.resourceSandboxExtension)
914         extension->consume();
915
916     for (auto& fileReference : m_fileReferences)
917         fileReference->prepareForFileAccess();
918
919     m_didConsumeSandboxExtensions = true;
920 }
921
922 void NetworkResourceLoader::invalidateSandboxExtensions()
923 {
924     if (m_didConsumeSandboxExtensions) {
925         for (auto& extension : m_parameters.requestBodySandboxExtensions)
926             extension->revoke();
927         if (auto& extension = m_parameters.resourceSandboxExtension)
928             extension->revoke();
929         for (auto& fileReference : m_fileReferences)
930             fileReference->revokeFileAccess();
931
932         m_didConsumeSandboxExtensions = false;
933     }
934
935     m_fileReferences.clear();
936 }
937
938 bool NetworkResourceLoader::isAlwaysOnLoggingAllowed() const
939 {
940     if (m_connection->networkProcess().sessionIsControlledByAutomation(sessionID()))
941         return true;
942
943     return sessionID().isAlwaysOnLoggingAllowed();
944 }
945
946 bool NetworkResourceLoader::shouldCaptureExtraNetworkLoadMetrics() const
947 {
948     return m_shouldCaptureExtraNetworkLoadMetrics;
949 }
950
951 #if ENABLE(RESOURCE_LOAD_STATISTICS) && !RELEASE_LOG_DISABLED
952 bool NetworkResourceLoader::shouldLogCookieInformation(NetworkConnectionToWebProcess& connection, const PAL::SessionID& sessionID)
953 {
954     if (auto session = connection.networkProcess().networkSession(sessionID))
955         return session->shouldLogCookieInformation();
956     return false;
957 }
958
959 static String escapeForJSON(String s)
960 {
961     return s.replace('\\', "\\\\").replace('"', "\\\"");
962 }
963
964 static String escapeIDForJSON(const Optional<uint64_t>& value)
965 {
966     return value ? String::number(value.value()) : String("None");
967 };
968
969 void NetworkResourceLoader::logCookieInformation() const
970 {
971     ASSERT(shouldLogCookieInformation(m_connection, sessionID()));
972
973     auto networkStorageSession = WebCore::NetworkStorageSession::storageSession(sessionID());
974     ASSERT(networkStorageSession);
975
976     logCookieInformation(m_connection, "NetworkResourceLoader", reinterpret_cast<const void*>(this), *networkStorageSession, originalRequest().firstPartyForCookies(), SameSiteInfo::create(originalRequest()), originalRequest().url(), originalRequest().httpReferrer(), frameID(), pageID(), identifier());
977 }
978
979 static void logBlockedCookieInformation(NetworkConnectionToWebProcess& connection, const String& label, const void* loggedObject, const WebCore::NetworkStorageSession& networkStorageSession, const URL& firstParty, const SameSiteInfo& sameSiteInfo, const URL& url, const String& referrer, Optional<uint64_t> frameID, Optional<uint64_t> pageID, Optional<uint64_t> identifier)
980 {
981     ASSERT(NetworkResourceLoader::shouldLogCookieInformation(connection, networkStorageSession.sessionID()));
982
983     auto escapedURL = escapeForJSON(url.string());
984     auto escapedFirstParty = escapeForJSON(firstParty.string());
985     auto escapedFrameID = escapeIDForJSON(frameID);
986     auto escapedPageID = escapeIDForJSON(pageID);
987     auto escapedIdentifier = escapeIDForJSON(identifier);
988     auto escapedReferrer = escapeForJSON(referrer);
989
990 #define LOCAL_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(networkStorageSession.sessionID().isAlwaysOnLoggingAllowed(), Network, "%p - %s::" fmt, loggedObject, label.utf8().data(), ##__VA_ARGS__)
991 #define LOCAL_LOG(str, ...) \
992     LOCAL_LOG_IF_ALLOWED("logCookieInformation: BLOCKED cookie access for pageID = %s, frameID = %s, resourceID = %s, firstParty = %s: " str, escapedPageID.utf8().data(), escapedFrameID.utf8().data(), escapedIdentifier.utf8().data(), escapedFirstParty.utf8().data(), ##__VA_ARGS__)
993
994     LOCAL_LOG(R"({ "url": "%{public}s",)", escapedURL.utf8().data());
995     LOCAL_LOG(R"(  "partition": "%{public}s",)", "BLOCKED");
996     LOCAL_LOG(R"(  "hasStorageAccess": %{public}s,)", "false");
997     LOCAL_LOG(R"(  "referer": "%{public}s",)", escapedReferrer.utf8().data());
998     LOCAL_LOG(R"(  "isSameSite": "%{public}s",)", sameSiteInfo.isSameSite ? "true" : "false");
999     LOCAL_LOG(R"(  "isTopSite": "%{public}s",)", sameSiteInfo.isTopSite ? "true" : "false");
1000     LOCAL_LOG(R"(  "cookies": [])");
1001     LOCAL_LOG(R"(  })");
1002 #undef LOCAL_LOG
1003 #undef LOCAL_LOG_IF_ALLOWED
1004 }
1005
1006 static void logCookieInformationInternal(NetworkConnectionToWebProcess& connection, const String& label, const void* loggedObject, const WebCore::NetworkStorageSession& networkStorageSession, const URL& firstParty, const WebCore::SameSiteInfo& sameSiteInfo, const URL& url, const String& referrer, Optional<uint64_t> frameID, Optional<uint64_t> pageID, Optional<uint64_t> identifier)
1007 {
1008     ASSERT(NetworkResourceLoader::shouldLogCookieInformation(connection, networkStorageSession.sessionID()));
1009
1010     Vector<WebCore::Cookie> cookies;
1011     if (!networkStorageSession.getRawCookies(firstParty, sameSiteInfo, url, frameID, pageID, cookies))
1012         return;
1013
1014     auto escapedURL = escapeForJSON(url.string());
1015     auto escapedPartition = escapeForJSON(emptyString());
1016     auto escapedReferrer = escapeForJSON(referrer);
1017     auto escapedFrameID = escapeIDForJSON(frameID);
1018     auto escapedPageID = escapeIDForJSON(pageID);
1019     auto escapedIdentifier = escapeIDForJSON(identifier);
1020     bool hasStorageAccess = (frameID && pageID) ? networkStorageSession.hasStorageAccess(url.string(), firstParty.string(), frameID.value(), pageID.value()) : false;
1021
1022 #define LOCAL_LOG_IF_ALLOWED(fmt, ...) RELEASE_LOG_IF(networkStorageSession.sessionID().isAlwaysOnLoggingAllowed(), Network, "%p - %s::" fmt, loggedObject, label.utf8().data(), ##__VA_ARGS__)
1023 #define LOCAL_LOG(str, ...) \
1024     LOCAL_LOG_IF_ALLOWED("logCookieInformation: pageID = %s, frameID = %s, resourceID = %s: " str, escapedPageID.utf8().data(), escapedFrameID.utf8().data(), escapedIdentifier.utf8().data(), ##__VA_ARGS__)
1025
1026     LOCAL_LOG(R"({ "url": "%{public}s",)", escapedURL.utf8().data());
1027     LOCAL_LOG(R"(  "partition": "%{public}s",)", escapedPartition.utf8().data());
1028     LOCAL_LOG(R"(  "hasStorageAccess": %{public}s,)", hasStorageAccess ? "true" : "false");
1029     LOCAL_LOG(R"(  "referer": "%{public}s",)", escapedReferrer.utf8().data());
1030     LOCAL_LOG(R"(  "isSameSite": "%{public}s",)", sameSiteInfo.isSameSite ? "true" : "false");
1031     LOCAL_LOG(R"(  "isTopSite": "%{public}s",)", sameSiteInfo.isTopSite ? "true" : "false");
1032     LOCAL_LOG(R"(  "cookies": [)");
1033
1034     auto size = cookies.size();
1035     decltype(size) count = 0;
1036     for (const auto& cookie : cookies) {
1037         const char* trailingComma = ",";
1038         if (++count == size)
1039             trailingComma = "";
1040
1041         auto escapedName = escapeForJSON(cookie.name);
1042         auto escapedValue = escapeForJSON(cookie.value);
1043         auto escapedDomain = escapeForJSON(cookie.domain);
1044         auto escapedPath = escapeForJSON(cookie.path);
1045         auto escapedComment = escapeForJSON(cookie.comment);
1046         auto escapedCommentURL = escapeForJSON(cookie.commentURL.string());
1047         // FIXME: Log Same-Site policy for each cookie. See <https://bugs.webkit.org/show_bug.cgi?id=184894>.
1048
1049         LOCAL_LOG(R"(  { "name": "%{public}s",)", escapedName.utf8().data());
1050         LOCAL_LOG(R"(    "value": "%{public}s",)", escapedValue.utf8().data());
1051         LOCAL_LOG(R"(    "domain": "%{public}s",)", escapedDomain.utf8().data());
1052         LOCAL_LOG(R"(    "path": "%{public}s",)", escapedPath.utf8().data());
1053         LOCAL_LOG(R"(    "created": %f,)", cookie.created);
1054         LOCAL_LOG(R"(    "expires": %f,)", cookie.expires);
1055         LOCAL_LOG(R"(    "httpOnly": %{public}s,)", cookie.httpOnly ? "true" : "false");
1056         LOCAL_LOG(R"(    "secure": %{public}s,)", cookie.secure ? "true" : "false");
1057         LOCAL_LOG(R"(    "session": %{public}s,)", cookie.session ? "true" : "false");
1058         LOCAL_LOG(R"(    "comment": "%{public}s",)", escapedComment.utf8().data());
1059         LOCAL_LOG(R"(    "commentURL": "%{public}s")", escapedCommentURL.utf8().data());
1060         LOCAL_LOG(R"(  }%{public}s)", trailingComma);
1061     }
1062     LOCAL_LOG(R"(]})");
1063 #undef LOCAL_LOG
1064 #undef LOCAL_LOG_IF_ALLOWED
1065 }
1066
1067 void NetworkResourceLoader::logCookieInformation(NetworkConnectionToWebProcess& connection, const String& label, const void* loggedObject, const NetworkStorageSession& networkStorageSession, const URL& firstParty, const SameSiteInfo& sameSiteInfo, const URL& url, const String& referrer, Optional<uint64_t> frameID, Optional<uint64_t> pageID, Optional<uint64_t> identifier)
1068 {
1069     ASSERT(shouldLogCookieInformation(connection, networkStorageSession.sessionID()));
1070
1071     if (networkStorageSession.shouldBlockCookies(firstParty, url, frameID, pageID))
1072         logBlockedCookieInformation(connection, label, loggedObject, networkStorageSession, firstParty, sameSiteInfo, url, referrer, frameID, pageID, identifier);
1073     else
1074         logCookieInformationInternal(connection, label, loggedObject, networkStorageSession, firstParty, sameSiteInfo, url, referrer, frameID, pageID, identifier);
1075 }
1076 #endif
1077
1078 void NetworkResourceLoader::addConsoleMessage(MessageSource messageSource, MessageLevel messageLevel, const String& message, unsigned long)
1079 {
1080     send(Messages::WebPage::AddConsoleMessage { m_parameters.webFrameID,  messageSource, messageLevel, message, identifier() }, m_parameters.webPageID);
1081 }
1082
1083 void NetworkResourceLoader::sendCSPViolationReport(URL&& reportURL, Ref<FormData>&& report)
1084 {
1085     send(Messages::WebPage::SendCSPViolationReport { m_parameters.webFrameID, WTFMove(reportURL), IPC::FormDataReference { WTFMove(report) } }, m_parameters.webPageID);
1086 }
1087
1088 void NetworkResourceLoader::enqueueSecurityPolicyViolationEvent(WebCore::SecurityPolicyViolationEvent::Init&& eventInit)
1089 {
1090     send(Messages::WebPage::EnqueueSecurityPolicyViolationEvent { m_parameters.webFrameID, WTFMove(eventInit) }, m_parameters.webPageID);
1091 }
1092
1093 void NetworkResourceLoader::logSlowCacheRetrieveIfNeeded(const NetworkCache::Cache::RetrieveInfo& info)
1094 {
1095 #if RELEASE_LOG_DISABLED
1096     UNUSED_PARAM(info);
1097 #else
1098     if (!isAlwaysOnLoggingAllowed())
1099         return;
1100     auto duration = info.completionTime - info.startTime;
1101     if (duration < 1_s)
1102         return;
1103     RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Took %.0fms, priority %d", duration.milliseconds(), info.priority);
1104     if (info.wasSpeculativeLoad)
1105         RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Was speculative load");
1106     if (!info.storageTimings.startTime)
1107         return;
1108     RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Storage retrieve time %.0fms", (info.storageTimings.completionTime - info.storageTimings.startTime).milliseconds());
1109     if (info.storageTimings.dispatchTime) {
1110         auto time = (info.storageTimings.dispatchTime - info.storageTimings.startTime).milliseconds();
1111         auto count = info.storageTimings.dispatchCountAtDispatch - info.storageTimings.dispatchCountAtStart;
1112         RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Dispatch delay %.0fms, dispatched %lu resources first", time, count);
1113     }
1114     if (info.storageTimings.recordIOStartTime)
1115         RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Record I/O time %.0fms", (info.storageTimings.recordIOEndTime - info.storageTimings.recordIOStartTime).milliseconds());
1116     if (info.storageTimings.blobIOStartTime)
1117         RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Blob I/O time %.0fms", (info.storageTimings.blobIOEndTime - info.storageTimings.blobIOStartTime).milliseconds());
1118     if (info.storageTimings.synchronizationInProgressAtDispatch)
1119         RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Synchronization was in progress");
1120     if (info.storageTimings.shrinkInProgressAtDispatch)
1121         RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Shrink was in progress");
1122     if (info.storageTimings.wasCanceled)
1123         RELEASE_LOG_IF_ALLOWED("logSlowCacheRetrieveIfNeeded: Retrieve was canceled");
1124 #endif
1125 }
1126
1127 } // namespace WebKit
1128
1129 #undef RELEASE_LOG_IF_ALLOWED
1130 #undef RELEASE_LOG_ERROR_IF_ALLOWED