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