Move URL from WebCore to WTF
[WebKit-https.git] / Source / WebKit / NetworkProcess / NetworkProcess.cpp
1 /*
2  * Copyright (C) 2012-2018 Apple Inc. All rights reserved.
3  * Copyright (C) 2018 Sony Interactive Entertainment Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
16  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "NetworkProcess.h"
29
30 #include "ArgumentCoders.h"
31 #include "Attachment.h"
32 #include "AuthenticationManager.h"
33 #include "ChildProcessMessages.h"
34 #include "DataReference.h"
35 #include "DownloadProxyMessages.h"
36 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
37 #include "LegacyCustomProtocolManager.h"
38 #endif
39 #include "Logging.h"
40 #include "NetworkBlobRegistry.h"
41 #include "NetworkConnectionToWebProcess.h"
42 #include "NetworkContentRuleListManagerMessages.h"
43 #include "NetworkProcessCreationParameters.h"
44 #include "NetworkProcessPlatformStrategies.h"
45 #include "NetworkProcessProxyMessages.h"
46 #include "NetworkProximityManager.h"
47 #include "NetworkResourceLoader.h"
48 #include "NetworkSession.h"
49 #include "NetworkSessionCreationParameters.h"
50 #include "PreconnectTask.h"
51 #include "RemoteNetworkingContext.h"
52 #include "SessionTracker.h"
53 #include "StatisticsData.h"
54 #include "WebCookieManager.h"
55 #include "WebCoreArgumentCoders.h"
56 #include "WebPageProxyMessages.h"
57 #include "WebProcessPoolMessages.h"
58 #include "WebSWOriginStore.h"
59 #include "WebSWServerConnection.h"
60 #include "WebSWServerToContextConnection.h"
61 #include "WebsiteData.h"
62 #include "WebsiteDataFetchOption.h"
63 #include "WebsiteDataStore.h"
64 #include "WebsiteDataStoreParameters.h"
65 #include "WebsiteDataType.h"
66 #include <WebCore/DNS.h>
67 #include <WebCore/DeprecatedGlobalSettings.h>
68 #include <WebCore/DiagnosticLoggingClient.h>
69 #include <WebCore/LogInitialization.h>
70 #include <WebCore/MIMETypeRegistry.h>
71 #include <WebCore/NetworkStateNotifier.h>
72 #include <WebCore/NetworkStorageSession.h>
73 #include <WebCore/ResourceRequest.h>
74 #include <WebCore/RuntimeApplicationChecks.h>
75 #include <WebCore/SchemeRegistry.h>
76 #include <WebCore/SecurityOriginData.h>
77 #include <WebCore/SecurityOriginHash.h>
78 #include <WebCore/Settings.h>
79 #include <pal/SessionID.h>
80 #include <wtf/Algorithms.h>
81 #include <wtf/CallbackAggregator.h>
82 #include <wtf/OptionSet.h>
83 #include <wtf/ProcessPrivilege.h>
84 #include <wtf/RunLoop.h>
85 #include <wtf/URLParser.h>
86 #include <wtf/text/AtomicString.h>
87 #include <wtf/text/CString.h>
88
89 #if ENABLE(SEC_ITEM_SHIM)
90 #include "SecItemShim.h"
91 #endif
92
93 #include "NetworkCache.h"
94 #include "NetworkCacheCoders.h"
95
96 #if ENABLE(NETWORK_CAPTURE)
97 #include "NetworkCaptureManager.h"
98 #endif
99
100 #if PLATFORM(COCOA)
101 #include "NetworkSessionCocoa.h"
102 #endif
103
104 #if ENABLE(SERVICE_WORKER)
105 #include "WebSWServerToContextConnectionMessages.h"
106 #endif
107
108 namespace WebKit {
109 using namespace WebCore;
110
111 static void callExitSoon(IPC::Connection*)
112 {
113     // If the connection has been closed and we haven't responded in the main thread for 10 seconds
114     // the process will exit forcibly.
115     auto watchdogDelay = 10_s;
116
117     WorkQueue::create("com.apple.WebKit.ChildProcess.WatchDogQueue")->dispatchAfter(watchdogDelay, [] {
118         // We use _exit here since the watchdog callback is called from another thread and we don't want
119         // global destructors or atexit handlers to be called from this thread while the main thread is busy
120         // doing its thing.
121         RELEASE_LOG_ERROR(IPC, "Exiting process early due to unacknowledged closed-connection");
122         _exit(EXIT_FAILURE);
123     });
124 }
125
126 NetworkProcess& NetworkProcess::singleton()
127 {
128     static NeverDestroyed<NetworkProcess> networkProcess;
129     return networkProcess;
130 }
131
132 NetworkProcess::NetworkProcess()
133     : m_hasSetCacheModel(false)
134     , m_cacheModel(CacheModelDocumentViewer)
135     , m_diskCacheIsDisabledForTesting(false)
136     , m_canHandleHTTPSServerTrustEvaluation(true)
137 #if PLATFORM(COCOA)
138     , m_clearCacheDispatchGroup(0)
139 #endif
140     , m_storageTaskQueue(WorkQueue::create("com.apple.WebKit.StorageTask"))
141 #if ENABLE(INDEXED_DATABASE)
142     , m_idbPerOriginQuota(IDBServer::defaultPerOriginQuota)
143 #endif
144 {
145     NetworkProcessPlatformStrategies::initialize();
146
147     addSupplement<AuthenticationManager>();
148     addSupplement<WebCookieManager>();
149 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
150     addSupplement<LegacyCustomProtocolManager>();
151 #endif
152 #if ENABLE(PROXIMITY_NETWORKING)
153     addSupplement<NetworkProximityManager>();
154 #endif
155
156     NetworkStateNotifier::singleton().addListener([this](bool isOnLine) {
157         auto webProcessConnections = m_webProcessConnections;
158         for (auto& webProcessConnection : webProcessConnections)
159             webProcessConnection->setOnLineState(isOnLine);
160     });
161 }
162
163 NetworkProcess::~NetworkProcess()
164 {
165     for (auto& callbacks : m_cacheStorageParametersCallbacks.values()) {
166         for (auto& callback : callbacks)
167             callback(String { }, 0);
168     }
169 }
170
171 AuthenticationManager& NetworkProcess::authenticationManager()
172 {
173     return *supplement<AuthenticationManager>();
174 }
175
176 DownloadManager& NetworkProcess::downloadManager()
177 {
178     static NeverDestroyed<DownloadManager> downloadManager(*this);
179     return downloadManager;
180 }
181
182 #if ENABLE(PROXIMITY_NETWORKING)
183 NetworkProximityManager& NetworkProcess::proximityManager()
184 {
185     return *supplement<NetworkProximityManager>();
186 }
187 #endif
188
189 void NetworkProcess::removeNetworkConnectionToWebProcess(NetworkConnectionToWebProcess* connection)
190 {
191     size_t vectorIndex = m_webProcessConnections.find(connection);
192     ASSERT(vectorIndex != notFound);
193
194     m_webProcessConnections.remove(vectorIndex);
195 }
196
197 bool NetworkProcess::shouldTerminate()
198 {
199     // Network process keeps session cookies and credentials, so it should never terminate (as long as UI process connection is alive).
200     return false;
201 }
202
203 void NetworkProcess::didReceiveMessage(IPC::Connection& connection, IPC::Decoder& decoder)
204 {
205     if (messageReceiverMap().dispatchMessage(connection, decoder))
206         return;
207
208     if (decoder.messageReceiverName() == Messages::ChildProcess::messageReceiverName()) {
209         ChildProcess::didReceiveMessage(connection, decoder);
210         return;
211     }
212
213 #if ENABLE(CONTENT_EXTENSIONS)
214     if (decoder.messageReceiverName() == Messages::NetworkContentRuleListManager::messageReceiverName()) {
215         m_NetworkContentRuleListManager.didReceiveMessage(connection, decoder);
216         return;
217     }
218 #endif
219
220 #if ENABLE(SERVICE_WORKER)
221     if (decoder.messageReceiverName() == Messages::WebSWServerToContextConnection::messageReceiverName()) {
222         ASSERT(parentProcessHasServiceWorkerEntitlement());
223         if (!parentProcessHasServiceWorkerEntitlement())
224             return;
225         if (auto* webSWConnection = connectionToContextProcessFromIPCConnection(connection)) {
226             webSWConnection->didReceiveMessage(connection, decoder);
227             return;
228         }
229     }
230 #endif
231     didReceiveNetworkProcessMessage(connection, decoder);
232 }
233
234 void NetworkProcess::didReceiveSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)
235 {
236     if (messageReceiverMap().dispatchSyncMessage(connection, decoder, replyEncoder))
237         return;
238
239     didReceiveSyncNetworkProcessMessage(connection, decoder, replyEncoder);
240 }
241
242 void NetworkProcess::didClose(IPC::Connection&)
243 {
244     ASSERT(RunLoop::isMain());
245
246     // Make sure we flush all cookies to disk before exiting.
247     platformSyncAllCookies([this] {
248         stopRunLoop();
249     });
250 }
251
252 void NetworkProcess::didCreateDownload()
253 {
254     disableTermination();
255 }
256
257 void NetworkProcess::didDestroyDownload()
258 {
259     enableTermination();
260 }
261
262 IPC::Connection* NetworkProcess::downloadProxyConnection()
263 {
264     return parentProcessConnection();
265 }
266
267 AuthenticationManager& NetworkProcess::downloadsAuthenticationManager()
268 {
269     return authenticationManager();
270 }
271
272 void NetworkProcess::lowMemoryHandler(Critical critical)
273 {
274     if (m_suppressMemoryPressureHandler)
275         return;
276
277     WTF::releaseFastMallocFreeMemory();
278 }
279
280 void NetworkProcess::initializeNetworkProcess(NetworkProcessCreationParameters&& parameters)
281 {
282 #if HAVE(SEC_KEY_PROXY)
283     WTF::setProcessPrivileges({ ProcessPrivilege::CanAccessRawCookies });
284 #else
285     WTF::setProcessPrivileges({ ProcessPrivilege::CanAccessRawCookies, ProcessPrivilege::CanAccessCredentials });
286 #endif
287     WebCore::NetworkStorageSession::permitProcessToUseCookieAPI(true);
288     WebCore::setPresentingApplicationPID(parameters.presentingApplicationPID);
289     platformInitializeNetworkProcess(parameters);
290
291     WTF::Thread::setCurrentThreadIsUserInitiated();
292     AtomicString::init();
293
294     m_suppressMemoryPressureHandler = parameters.shouldSuppressMemoryPressureHandler;
295     if (!m_suppressMemoryPressureHandler) {
296         auto& memoryPressureHandler = MemoryPressureHandler::singleton();
297         memoryPressureHandler.setLowMemoryHandler([this] (Critical critical, Synchronous) {
298             lowMemoryHandler(critical);
299         });
300         memoryPressureHandler.install();
301     }
302
303 #if ENABLE(NETWORK_CAPTURE)
304     NetworkCapture::Manager::singleton().initialize(
305         parameters.recordReplayMode,
306         parameters.recordReplayCacheLocation);
307 #endif
308
309     m_diskCacheIsDisabledForTesting = parameters.shouldUseTestingNetworkSession;
310
311     m_diskCacheSizeOverride = parameters.diskCacheSizeOverride;
312     setCacheModel(static_cast<uint32_t>(parameters.cacheModel));
313
314     setCanHandleHTTPSServerTrustEvaluation(parameters.canHandleHTTPSServerTrustEvaluation);
315
316     if (parameters.shouldUseTestingNetworkSession)
317         NetworkStorageSession::switchToNewTestingSession();
318
319     SessionTracker::setSession(PAL::SessionID::defaultSessionID(), NetworkSession::create(NetworkSessionCreationParameters()));
320
321 #if ENABLE(INDEXED_DATABASE)
322     addIndexedDatabaseSession(PAL::SessionID::defaultSessionID(), parameters.indexedDatabaseDirectory, parameters.indexedDatabaseDirectoryExtensionHandle);
323 #endif
324
325 #if ENABLE(SERVICE_WORKER)
326     if (parentProcessHasServiceWorkerEntitlement()) {
327         addServiceWorkerSession(PAL::SessionID::defaultSessionID(), parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
328
329         for (auto& scheme : parameters.urlSchemesServiceWorkersCanHandle)
330             registerURLSchemeServiceWorkersCanHandle(scheme);
331
332         m_shouldDisableServiceWorkerProcessTerminationDelay = parameters.shouldDisableServiceWorkerProcessTerminationDelay;
333     }
334 #endif
335
336     auto* defaultSession = SessionTracker::networkSession(PAL::SessionID::defaultSessionID());
337     for (const auto& cookie : parameters.defaultSessionPendingCookies)
338         defaultSession->networkStorageSession().setCookie(cookie);
339
340     for (auto& supplement : m_supplements.values())
341         supplement->initialize(parameters);
342
343     for (auto& scheme : parameters.urlSchemesRegisteredAsSecure)
344         registerURLSchemeAsSecure(scheme);
345
346     for (auto& scheme : parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy)
347         registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
348
349     for (auto& scheme : parameters.urlSchemesRegisteredAsLocal)
350         registerURLSchemeAsLocal(scheme);
351
352     for (auto& scheme : parameters.urlSchemesRegisteredAsNoAccess)
353         registerURLSchemeAsNoAccess(scheme);
354
355     for (auto& scheme : parameters.urlSchemesRegisteredAsDisplayIsolated)
356         registerURLSchemeAsDisplayIsolated(scheme);
357
358     for (auto& scheme : parameters.urlSchemesRegisteredAsCORSEnabled)
359         registerURLSchemeAsCORSEnabled(scheme);
360
361     for (auto& scheme : parameters.urlSchemesRegisteredAsCanDisplayOnlyIfCanRequest)
362         registerURLSchemeAsCanDisplayOnlyIfCanRequest(scheme);
363
364     RELEASE_LOG(Process, "%p - NetworkProcess::initializeNetworkProcess: Presenting process = %d", this, WebCore::presentingApplicationPID());
365 }
366
367 void NetworkProcess::initializeConnection(IPC::Connection* connection)
368 {
369     ChildProcess::initializeConnection(connection);
370
371     // We give a chance for didClose() to get called on the main thread but forcefully call _exit() after a delay
372     // in case the main thread is unresponsive or didClose() takes too long.
373     connection->setDidCloseOnConnectionWorkQueueCallback(callExitSoon);
374
375     for (auto& supplement : m_supplements.values())
376         supplement->initializeConnection(connection);
377 }
378
379 void NetworkProcess::createNetworkConnectionToWebProcess(bool isServiceWorkerProcess, WebCore::SecurityOriginData&& securityOrigin)
380 {
381 #if USE(UNIX_DOMAIN_SOCKETS)
382     IPC::Connection::SocketPair socketPair = IPC::Connection::createPlatformConnection();
383
384     auto connection = NetworkConnectionToWebProcess::create(socketPair.server);
385     m_webProcessConnections.append(WTFMove(connection));
386
387     IPC::Attachment clientSocket(socketPair.client);
388     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
389 #elif OS(DARWIN)
390     // Create the listening port.
391     mach_port_t listeningPort = MACH_PORT_NULL;
392     auto kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
393     if (kr != KERN_SUCCESS) {
394         RELEASE_LOG_ERROR(Process, "NetworkProcess::createNetworkConnectionToWebProcess: Could not allocate mach port, error %x", kr);
395         CRASH();
396     }
397     if (!MACH_PORT_VALID(listeningPort)) {
398         RELEASE_LOG_ERROR(Process, "NetworkProcess::createNetworkConnectionToWebProcess: Could not allocate mach port, returned port was invalid");
399         CRASH();
400     }
401
402     // Create a listening connection.
403     auto connection = NetworkConnectionToWebProcess::create(IPC::Connection::Identifier(listeningPort));
404     m_webProcessConnections.append(WTFMove(connection));
405
406     IPC::Attachment clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
407     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientPort), 0);
408 #elif OS(WINDOWS)
409     IPC::Connection::Identifier serverIdentifier, clientIdentifier;
410     if (!IPC::Connection::createServerAndClientIdentifiers(serverIdentifier, clientIdentifier)) {
411         LOG_ERROR("Failed to create server and client identifiers");
412         CRASH();
413     }
414
415     auto connection = NetworkConnectionToWebProcess::create(serverIdentifier);
416     m_webProcessConnections.append(WTFMove(connection));
417
418     IPC::Attachment clientSocket(clientIdentifier);
419     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidCreateNetworkConnectionToWebProcess(clientSocket), 0);
420 #else
421     notImplemented();
422 #endif
423
424     if (!m_webProcessConnections.isEmpty())
425         m_webProcessConnections.last()->setOnLineState(NetworkStateNotifier::singleton().onLine());
426     
427 #if ENABLE(SERVICE_WORKER)
428     if (isServiceWorkerProcess && !m_webProcessConnections.isEmpty()) {
429         ASSERT(parentProcessHasServiceWorkerEntitlement());
430         ASSERT(m_waitingForServerToContextProcessConnection);
431         auto contextConnection = WebSWServerToContextConnection::create(securityOrigin, m_webProcessConnections.last()->connection());
432         auto addResult = m_serverToContextConnections.add(WTFMove(securityOrigin), contextConnection.copyRef());
433         ASSERT_UNUSED(addResult, addResult.isNewEntry);
434
435         m_waitingForServerToContextProcessConnection = false;
436
437         for (auto* server : SWServer::allServers())
438             server->serverToContextConnectionCreated(contextConnection);
439     }
440 #else
441     UNUSED_PARAM(isServiceWorkerProcess);
442     UNUSED_PARAM(securityOrigin);
443 #endif
444 }
445
446 void NetworkProcess::clearCachedCredentials()
447 {
448     NetworkStorageSession::defaultStorageSession().credentialStorage().clearCredentials();
449     if (auto* networkSession = SessionTracker::networkSession(PAL::SessionID::defaultSessionID()))
450         networkSession->clearCredentials();
451     else
452         ASSERT_NOT_REACHED();
453 }
454
455 void NetworkProcess::addWebsiteDataStore(WebsiteDataStoreParameters&& parameters)
456 {
457 #if ENABLE(INDEXED_DATABASE)
458     addIndexedDatabaseSession(parameters.networkSessionParameters.sessionID, parameters.indexedDatabaseDirectory, parameters.indexedDatabaseDirectoryExtensionHandle);
459 #endif
460
461 #if ENABLE(SERVICE_WORKER)
462     if (parentProcessHasServiceWorkerEntitlement())
463         addServiceWorkerSession(parameters.networkSessionParameters.sessionID, parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
464 #endif
465
466     RemoteNetworkingContext::ensureWebsiteDataStoreSession(WTFMove(parameters));
467 }
468
469 void NetworkProcess::destroySession(PAL::SessionID sessionID)
470 {
471     SessionTracker::destroySession(sessionID);
472     m_sessionsControlledByAutomation.remove(sessionID);
473     CacheStorage::Engine::destroyEngine(sessionID);
474
475 #if ENABLE(SERVICE_WORKER)
476     m_swServers.remove(sessionID);
477     m_swDatabasePaths.remove(sessionID);
478 #endif
479 }
480
481 void NetworkProcess::writeBlobToFilePath(const URL& url, const String& path, SandboxExtension::Handle&& handleForWriting, CompletionHandler<void(bool)>&& completionHandler)
482 {
483     auto extension = SandboxExtension::create(WTFMove(handleForWriting));
484     if (!extension) {
485         completionHandler(false);
486         return;
487     }
488
489     extension->consume();
490     NetworkBlobRegistry::singleton().writeBlobToFilePath(url, path, [extension = WTFMove(extension), completionHandler = WTFMove(completionHandler)] (bool success) mutable {
491         extension->revoke();
492         completionHandler(success);
493     });
494 }
495
496 #if ENABLE(RESOURCE_LOAD_STATISTICS)
497 void NetworkProcess::updatePrevalentDomainsToBlockCookiesFor(PAL::SessionID sessionID, const Vector<String>& domainsToBlock, uint64_t contextId)
498 {
499     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
500         networkStorageSession->setPrevalentDomainsToBlockCookiesFor(domainsToBlock);
501     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidUpdateBlockCookies(contextId), 0);
502 }
503
504 void NetworkProcess::setAgeCapForClientSideCookies(PAL::SessionID sessionID, std::optional<Seconds> seconds, uint64_t contextId)
505 {
506     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
507         networkStorageSession->setAgeCapForClientSideCookies(seconds);
508     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidSetAgeCapForClientSideCookies(contextId), 0);
509 }
510
511 void NetworkProcess::hasStorageAccessForFrame(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, uint64_t frameID, uint64_t pageID, uint64_t contextId)
512 {
513     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
514         parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(networkStorageSession->hasStorageAccess(resourceDomain, firstPartyDomain, frameID, pageID), contextId), 0);
515     else
516         ASSERT_NOT_REACHED();
517 }
518
519 void NetworkProcess::getAllStorageAccessEntries(PAL::SessionID sessionID, uint64_t contextId)
520 {
521     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
522         parentProcessConnection()->send(Messages::NetworkProcessProxy::AllStorageAccessEntriesResult(networkStorageSession->getAllStorageAccessEntries(), contextId), 0);
523     else
524         ASSERT_NOT_REACHED();
525 }
526
527 void NetworkProcess::grantStorageAccess(PAL::SessionID sessionID, const String& resourceDomain, const String& firstPartyDomain, std::optional<uint64_t> frameID, uint64_t pageID, uint64_t contextId)
528 {
529     bool isStorageGranted = false;
530     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID)) {
531         networkStorageSession->grantStorageAccess(resourceDomain, firstPartyDomain, frameID, pageID);
532         ASSERT(networkStorageSession->hasStorageAccess(resourceDomain, firstPartyDomain, frameID, pageID));
533         isStorageGranted = true;
534     } else
535         ASSERT_NOT_REACHED();
536
537     parentProcessConnection()->send(Messages::NetworkProcessProxy::StorageAccessRequestResult(isStorageGranted, contextId), 0);
538 }
539
540 void NetworkProcess::removeAllStorageAccess(PAL::SessionID sessionID, uint64_t contextId)
541 {
542     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
543         networkStorageSession->removeAllStorageAccess();
544     else
545         ASSERT_NOT_REACHED();
546     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidRemoveAllStorageAccess(contextId), 0);
547 }
548
549 void NetworkProcess::removePrevalentDomains(PAL::SessionID sessionID, const Vector<String>& domains)
550 {
551     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
552         networkStorageSession->removePrevalentDomains(domains);
553 }
554
555 void NetworkProcess::setCacheMaxAgeCapForPrevalentResources(PAL::SessionID sessionID, Seconds seconds, uint64_t contextId)
556 {
557     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
558         networkStorageSession->setCacheMaxAgeCapForPrevalentResources(Seconds { seconds });
559     else
560         ASSERT_NOT_REACHED();
561     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidSetCacheMaxAgeCapForPrevalentResources(contextId), 0);
562 }
563
564 void NetworkProcess::resetCacheMaxAgeCapForPrevalentResources(PAL::SessionID sessionID, uint64_t contextId)
565 {
566     if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
567         networkStorageSession->resetCacheMaxAgeCapForPrevalentResources();
568     else
569         ASSERT_NOT_REACHED();
570     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidResetCacheMaxAgeCapForPrevalentResources(contextId), 0);
571 }
572 #endif // ENABLE(RESOURCE_LOAD_STATISTICS)
573
574 bool NetworkProcess::sessionIsControlledByAutomation(PAL::SessionID sessionID) const
575 {
576     return m_sessionsControlledByAutomation.contains(sessionID);
577 }
578
579 void NetworkProcess::setSessionIsControlledByAutomation(PAL::SessionID sessionID, bool controlled)
580 {
581     if (controlled)
582         m_sessionsControlledByAutomation.add(sessionID);
583     else
584         m_sessionsControlledByAutomation.remove(sessionID);
585 }
586
587 static void fetchDiskCacheEntries(PAL::SessionID sessionID, OptionSet<WebsiteDataFetchOption> fetchOptions, Function<void (Vector<WebsiteData::Entry>)>&& completionHandler)
588 {
589     if (auto* cache = NetworkProcess::singleton().cache()) {
590         HashMap<SecurityOriginData, uint64_t> originsAndSizes;
591         cache->traverse([fetchOptions, completionHandler = WTFMove(completionHandler), originsAndSizes = WTFMove(originsAndSizes)](auto* traversalEntry) mutable {
592             if (!traversalEntry) {
593                 Vector<WebsiteData::Entry> entries;
594
595                 for (auto& originAndSize : originsAndSizes)
596                     entries.append(WebsiteData::Entry { originAndSize.key, WebsiteDataType::DiskCache, originAndSize.value });
597
598                 RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler), entries = WTFMove(entries)] {
599                     completionHandler(entries);
600                 });
601
602                 return;
603             }
604
605             auto url = traversalEntry->entry.response().url();
606             auto result = originsAndSizes.add({url.protocol().toString(), url.host().toString(), url.port()}, 0);
607
608             if (fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes))
609                 result.iterator->value += traversalEntry->entry.sourceStorageRecord().header.size() + traversalEntry->recordInfo.bodySize;
610         });
611
612         return;
613     }
614
615     RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] {
616         completionHandler({ });
617     });
618 }
619
620 void NetworkProcess::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, uint64_t callbackID)
621 {
622     struct CallbackAggregator final : public RefCounted<CallbackAggregator> {
623         explicit CallbackAggregator(Function<void (WebsiteData)>&& completionHandler)
624             : m_completionHandler(WTFMove(completionHandler))
625         {
626         }
627
628         ~CallbackAggregator()
629         {
630             ASSERT(RunLoop::isMain());
631
632             RunLoop::main().dispatch([completionHandler = WTFMove(m_completionHandler), websiteData = WTFMove(m_websiteData)] {
633                 completionHandler(websiteData);
634             });
635         }
636
637         Function<void (WebsiteData)> m_completionHandler;
638         WebsiteData m_websiteData;
639     };
640
641     auto callbackAggregator = adoptRef(*new CallbackAggregator([this, callbackID] (WebsiteData websiteData) {
642         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidFetchWebsiteData(callbackID, websiteData), 0);
643     }));
644
645     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
646         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
647             networkStorageSession->getHostnamesWithCookies(callbackAggregator->m_websiteData.hostNamesWithCookies);
648     }
649
650     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
651         if (NetworkStorageSession::storageSession(sessionID))
652             callbackAggregator->m_websiteData.originsWithCredentials = NetworkStorageSession::storageSession(sessionID)->credentialStorage().originsWithCredentials();
653     }
654
655     if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
656         CacheStorage::Engine::fetchEntries(sessionID, fetchOptions.contains(WebsiteDataFetchOption::ComputeSizes), [callbackAggregator = callbackAggregator.copyRef()](auto entries) mutable {
657             callbackAggregator->m_websiteData.entries.appendVector(entries);
658         });
659     }
660
661 #if PLATFORM(COCOA)
662     if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
663         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
664             getHostNamesWithHSTSCache(*networkStorageSession, callbackAggregator->m_websiteData.hostNamesWithHSTSCache);
665     }
666 #endif
667
668 #if ENABLE(INDEXED_DATABASE)
669     auto path = m_idbDatabasePaths.get(sessionID);
670     if (!path.isEmpty() && websiteDataTypes.contains(WebsiteDataType::IndexedDBDatabases)) {
671         // FIXME: Pick the right database store based on the session ID.
672         postStorageTask(CrossThreadTask([this, callbackAggregator = callbackAggregator.copyRef(), path = WTFMove(path)]() mutable {
673             RunLoop::main().dispatch([callbackAggregator = WTFMove(callbackAggregator), securityOrigins = indexedDatabaseOrigins(path)] {
674                 for (const auto& securityOrigin : securityOrigins)
675                     callbackAggregator->m_websiteData.entries.append({ securityOrigin, WebsiteDataType::IndexedDBDatabases, 0 });
676             });
677         }));
678     }
679 #endif
680
681 #if ENABLE(SERVICE_WORKER)
682     path = m_swDatabasePaths.get(sessionID);
683     if (!path.isEmpty() && websiteDataTypes.contains(WebsiteDataType::ServiceWorkerRegistrations)) {
684         swServerForSession(sessionID).getOriginsWithRegistrations([callbackAggregator = callbackAggregator.copyRef()](const HashSet<SecurityOriginData>& securityOrigins) mutable {
685             for (auto& origin : securityOrigins)
686                 callbackAggregator->m_websiteData.entries.append({ origin, WebsiteDataType::ServiceWorkerRegistrations, 0 });
687         });
688     }
689 #endif
690
691     if (websiteDataTypes.contains(WebsiteDataType::DiskCache)) {
692         fetchDiskCacheEntries(sessionID, fetchOptions, [callbackAggregator = WTFMove(callbackAggregator)](auto entries) mutable {
693             callbackAggregator->m_websiteData.entries.appendVector(entries);
694         });
695     }
696 }
697
698 void NetworkProcess::deleteWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, WallTime modifiedSince, uint64_t callbackID)
699 {
700 #if PLATFORM(COCOA)
701     if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
702         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
703             clearHSTSCache(*networkStorageSession, modifiedSince);
704     }
705 #endif
706
707     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
708         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
709             networkStorageSession->deleteAllCookiesModifiedSince(modifiedSince);
710     }
711
712     if (websiteDataTypes.contains(WebsiteDataType::Credentials)) {
713         if (NetworkStorageSession::storageSession(sessionID))
714             NetworkStorageSession::storageSession(sessionID)->credentialStorage().clearCredentials();
715     }
716
717     auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
718         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteData(callbackID), 0);
719     });
720
721     if (websiteDataTypes.contains(WebsiteDataType::DOMCache))
722         CacheStorage::Engine::clearAllCaches(sessionID, [clearTasksHandler = clearTasksHandler.copyRef()] { });
723
724 #if ENABLE(INDEXED_DATABASE)
725     if (websiteDataTypes.contains(WebsiteDataType::IndexedDBDatabases) && !sessionID.isEphemeral())
726         idbServer(sessionID).closeAndDeleteDatabasesModifiedSince(modifiedSince, [clearTasksHandler = clearTasksHandler.copyRef()] { });
727 #endif
728
729 #if ENABLE(SERVICE_WORKER)
730     if (websiteDataTypes.contains(WebsiteDataType::ServiceWorkerRegistrations) && !sessionID.isEphemeral())
731         swServerForSession(sessionID).clearAll([clearTasksHandler = clearTasksHandler.copyRef()] { });
732 #endif
733
734     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
735         clearDiskCache(modifiedSince, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
736 }
737
738 static void clearDiskCacheEntries(const Vector<SecurityOriginData>& origins, Function<void ()>&& completionHandler)
739 {
740     if (auto* cache = NetworkProcess::singleton().cache()) {
741         HashSet<RefPtr<SecurityOrigin>> originsToDelete;
742         for (auto& origin : origins)
743             originsToDelete.add(origin.securityOrigin());
744
745         Vector<NetworkCache::Key> cacheKeysToDelete;
746         cache->traverse([cache, completionHandler = WTFMove(completionHandler), originsToDelete = WTFMove(originsToDelete), cacheKeysToDelete = WTFMove(cacheKeysToDelete)](auto* traversalEntry) mutable {
747             if (traversalEntry) {
748                 if (originsToDelete.contains(SecurityOrigin::create(traversalEntry->entry.response().url())))
749                     cacheKeysToDelete.append(traversalEntry->entry.key());
750                 return;
751             }
752
753             cache->remove(cacheKeysToDelete, WTFMove(completionHandler));
754             return;
755         });
756
757         return;
758     }
759
760     RunLoop::main().dispatch(WTFMove(completionHandler));
761 }
762
763 void NetworkProcess::deleteWebsiteDataForOrigins(PAL::SessionID sessionID, OptionSet<WebsiteDataType> websiteDataTypes, const Vector<SecurityOriginData>& originDatas, const Vector<String>& cookieHostNames, const Vector<String>& HSTSCacheHostNames, uint64_t callbackID)
764 {
765     if (websiteDataTypes.contains(WebsiteDataType::Cookies)) {
766         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
767             networkStorageSession->deleteCookiesForHostnames(cookieHostNames);
768     }
769
770 #if PLATFORM(COCOA)
771     if (websiteDataTypes.contains(WebsiteDataType::HSTSCache)) {
772         if (auto* networkStorageSession = NetworkStorageSession::storageSession(sessionID))
773             deleteHSTSCacheForHostNames(*networkStorageSession, HSTSCacheHostNames);
774     }
775 #endif
776
777     auto clearTasksHandler = WTF::CallbackAggregator::create([this, callbackID] {
778         parentProcessConnection()->send(Messages::NetworkProcessProxy::DidDeleteWebsiteDataForOrigins(callbackID), 0);
779     });
780
781     if (websiteDataTypes.contains(WebsiteDataType::DOMCache)) {
782         for (auto& originData : originDatas)
783             CacheStorage::Engine::clearCachesForOrigin(sessionID, SecurityOriginData { originData }, [clearTasksHandler = clearTasksHandler.copyRef()] { });
784     }
785
786 #if ENABLE(INDEXED_DATABASE)
787     if (websiteDataTypes.contains(WebsiteDataType::IndexedDBDatabases) && !sessionID.isEphemeral())
788         idbServer(sessionID).closeAndDeleteDatabasesForOrigins(originDatas, [clearTasksHandler = clearTasksHandler.copyRef()] { });
789 #endif
790
791 #if ENABLE(SERVICE_WORKER)
792     if (websiteDataTypes.contains(WebsiteDataType::ServiceWorkerRegistrations) && !sessionID.isEphemeral()) {
793         auto& server = swServerForSession(sessionID);
794         for (auto& originData : originDatas)
795             server.clear(originData, [clearTasksHandler = clearTasksHandler.copyRef()] { });
796     }
797 #endif
798
799     if (websiteDataTypes.contains(WebsiteDataType::DiskCache) && !sessionID.isEphemeral())
800         clearDiskCacheEntries(originDatas, [clearTasksHandler = WTFMove(clearTasksHandler)] { });
801 }
802
803 void NetworkProcess::downloadRequest(PAL::SessionID sessionID, DownloadID downloadID, const ResourceRequest& request, const String& suggestedFilename)
804 {
805     downloadManager().startDownload(nullptr, sessionID, downloadID, request, suggestedFilename);
806 }
807
808 void NetworkProcess::resumeDownload(PAL::SessionID sessionID, DownloadID downloadID, const IPC::DataReference& resumeData, const String& path, WebKit::SandboxExtension::Handle&& sandboxExtensionHandle)
809 {
810     downloadManager().resumeDownload(sessionID, downloadID, resumeData, path, WTFMove(sandboxExtensionHandle));
811 }
812
813 void NetworkProcess::cancelDownload(DownloadID downloadID)
814 {
815     downloadManager().cancelDownload(downloadID);
816 }
817
818 #if PLATFORM(COCOA)
819 void NetworkProcess::publishDownloadProgress(DownloadID downloadID, const URL& url, SandboxExtension::Handle&& sandboxExtensionHandle)
820 {
821     downloadManager().publishDownloadProgress(downloadID, url, WTFMove(sandboxExtensionHandle));
822 }
823 #endif
824
825 void NetworkProcess::continueWillSendRequest(DownloadID downloadID, WebCore::ResourceRequest&& request)
826 {
827     downloadManager().continueWillSendRequest(downloadID, WTFMove(request));
828 }
829
830 void NetworkProcess::pendingDownloadCanceled(DownloadID downloadID)
831 {
832     downloadProxyConnection()->send(Messages::DownloadProxy::DidCancel({ }), downloadID.downloadID());
833 }
834
835 void NetworkProcess::findPendingDownloadLocation(NetworkDataTask& networkDataTask, ResponseCompletionHandler&& completionHandler, const ResourceResponse& response)
836 {
837     uint64_t destinationID = networkDataTask.pendingDownloadID().downloadID();
838     downloadProxyConnection()->send(Messages::DownloadProxy::DidReceiveResponse(response), destinationID);
839
840     downloadManager().willDecidePendingDownloadDestination(networkDataTask, WTFMove(completionHandler));
841
842     // As per https://html.spec.whatwg.org/#as-a-download (step 2), the filename from the Content-Disposition header
843     // should override the suggested filename from the download attribute.
844     String suggestedFilename = response.isAttachmentWithFilename() ? response.suggestedFilename() : networkDataTask.suggestedFilename();
845     suggestedFilename = MIMETypeRegistry::appendFileExtensionIfNecessary(suggestedFilename, response.mimeType());
846
847     downloadProxyConnection()->send(Messages::DownloadProxy::DecideDestinationWithSuggestedFilenameAsync(networkDataTask.pendingDownloadID(), suggestedFilename), destinationID);
848 }
849
850 void NetworkProcess::continueDecidePendingDownloadDestination(DownloadID downloadID, String destination, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
851 {
852     if (destination.isEmpty())
853         downloadManager().cancelDownload(downloadID);
854     else
855         downloadManager().continueDecidePendingDownloadDestination(downloadID, destination, WTFMove(sandboxExtensionHandle), allowOverwrite);
856 }
857
858 void NetworkProcess::setCacheModel(uint32_t cm)
859 {
860     CacheModel cacheModel = static_cast<CacheModel>(cm);
861
862     if (m_hasSetCacheModel && (cacheModel == m_cacheModel))
863         return;
864
865     m_hasSetCacheModel = true;
866     m_cacheModel = cacheModel;
867
868     unsigned urlCacheMemoryCapacity = 0;
869     uint64_t urlCacheDiskCapacity = 0;
870     uint64_t diskFreeSize = 0;
871     if (WebCore::FileSystem::getVolumeFreeSpace(m_diskCacheDirectory, diskFreeSize)) {
872         // As a fudge factor, use 1000 instead of 1024, in case the reported byte
873         // count doesn't align exactly to a megabyte boundary.
874         diskFreeSize /= KB * 1000;
875         calculateURLCacheSizes(cacheModel, diskFreeSize, urlCacheMemoryCapacity, urlCacheDiskCapacity);
876     }
877
878     if (m_diskCacheSizeOverride >= 0)
879         urlCacheDiskCapacity = m_diskCacheSizeOverride;
880
881     if (m_cache)
882         m_cache->setCapacity(urlCacheDiskCapacity);
883 }
884
885 void NetworkProcess::setCanHandleHTTPSServerTrustEvaluation(bool value)
886 {
887     m_canHandleHTTPSServerTrustEvaluation = value;
888 }
889
890 void NetworkProcess::getNetworkProcessStatistics(uint64_t callbackID)
891 {
892     StatisticsData data;
893
894     auto& networkProcess = NetworkProcess::singleton();
895     data.statisticsNumbers.set("DownloadsActiveCount", networkProcess.downloadManager().activeDownloadCount());
896     data.statisticsNumbers.set("OutstandingAuthenticationChallengesCount", networkProcess.authenticationManager().outstandingAuthenticationChallengeCount());
897
898     parentProcessConnection()->send(Messages::WebProcessPool::DidGetStatistics(data, callbackID), 0);
899 }
900
901 void NetworkProcess::setAllowsAnySSLCertificateForWebSocket(bool allows)
902 {
903     DeprecatedGlobalSettings::setAllowsAnySSLCertificate(allows);
904 }
905
906 void NetworkProcess::logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, ShouldSample shouldSample)
907 {
908     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
909         return;
910
911     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessage(webPageID, message, description, ShouldSample::No), 0);
912 }
913
914 void NetworkProcess::logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, DiagnosticLoggingResultType result, ShouldSample shouldSample)
915 {
916     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
917         return;
918
919     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithResult(webPageID, message, description, result, ShouldSample::No), 0);
920 }
921
922 void NetworkProcess::logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, ShouldSample shouldSample)
923 {
924     if (!DiagnosticLoggingClient::shouldLogAfterSampling(shouldSample))
925         return;
926
927     parentProcessConnection()->send(Messages::NetworkProcessProxy::LogDiagnosticMessageWithValue(webPageID, message, description, value, significantFigures, ShouldSample::No), 0);
928 }
929
930 void NetworkProcess::terminate()
931 {
932 #if ENABLE(NETWORK_CAPTURE)
933     NetworkCapture::Manager::singleton().terminate();
934 #endif
935
936     platformTerminate();
937     ChildProcess::terminate();
938 }
939
940 void NetworkProcess::processDidTransitionToForeground()
941 {
942     platformProcessDidTransitionToForeground();
943 }
944
945 void NetworkProcess::processDidTransitionToBackground()
946 {
947     platformProcessDidTransitionToBackground();
948 }
949
950 // FIXME: We can remove this one by adapting RefCounter.
951 class TaskCounter : public RefCounted<TaskCounter> {
952 public:
953     explicit TaskCounter(Function<void()>&& callback) : m_callback(WTFMove(callback)) { }
954     ~TaskCounter() { m_callback(); };
955
956 private:
957     Function<void()> m_callback;
958 };
959
960 void NetworkProcess::actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend shouldAcknowledgeWhenReadyToSuspend)
961 {
962     lowMemoryHandler(Critical::Yes);
963
964     RefPtr<TaskCounter> delayedTaskCounter;
965     if (shouldAcknowledgeWhenReadyToSuspend == ShouldAcknowledgeWhenReadyToSuspend::Yes) {
966         delayedTaskCounter = adoptRef(new TaskCounter([this] {
967             RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::notifyProcessReadyToSuspend() Sending ProcessReadyToSuspend IPC message", this);
968             if (parentProcessConnection())
969                 parentProcessConnection()->send(Messages::NetworkProcessProxy::ProcessReadyToSuspend(), 0);
970         }));
971     }
972
973     platformPrepareToSuspend([delayedTaskCounter] { });
974     platformSyncAllCookies([delayedTaskCounter] { });
975
976     for (auto& connection : m_webProcessConnections)
977         connection->cleanupForSuspension([delayedTaskCounter] { });
978 }
979
980 void NetworkProcess::processWillSuspendImminently(bool& handled)
981 {
982     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::No);
983     handled = true;
984 }
985
986 void NetworkProcess::prepareToSuspend()
987 {
988     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::prepareToSuspend()", this);
989     actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend::Yes);
990 }
991
992 void NetworkProcess::cancelPrepareToSuspend()
993 {
994     // Although it is tempting to send a NetworkProcessProxy::DidCancelProcessSuspension message from here
995     // we do not because prepareToSuspend() already replied with a NetworkProcessProxy::ProcessReadyToSuspend
996     // message. And NetworkProcessProxy expects to receive either a NetworkProcessProxy::ProcessReadyToSuspend-
997     // or NetworkProcessProxy::DidCancelProcessSuspension- message, but not both.
998     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::cancelPrepareToSuspend()", this);
999     platformProcessDidResume();
1000     for (auto& connection : m_webProcessConnections)
1001         connection->endSuspension();
1002 }
1003
1004 void NetworkProcess::processDidResume()
1005 {
1006     RELEASE_LOG(ProcessSuspension, "%p - NetworkProcess::processDidResume()", this);
1007     platformProcessDidResume();
1008     for (auto& connection : m_webProcessConnections)
1009         connection->endSuspension();
1010 }
1011
1012 void NetworkProcess::prefetchDNS(const String& hostname)
1013 {
1014     WebCore::prefetchDNS(hostname);
1015 }
1016
1017 void NetworkProcess::cacheStorageParameters(PAL::SessionID sessionID, CacheStorageParametersCallback&& callback)
1018 {
1019     m_cacheStorageParametersCallbacks.ensure(sessionID, [&] {
1020         parentProcessConnection()->send(Messages::NetworkProcessProxy::RetrieveCacheStorageParameters { sessionID }, 0);
1021         return Vector<CacheStorageParametersCallback> { };
1022     }).iterator->value.append(WTFMove(callback));
1023 }
1024
1025 void NetworkProcess::setCacheStorageParameters(PAL::SessionID sessionID, uint64_t quota, String&& cacheStorageDirectory, SandboxExtension::Handle&& handle)
1026 {
1027     auto iterator = m_cacheStorageParametersCallbacks.find(sessionID);
1028     if (iterator == m_cacheStorageParametersCallbacks.end())
1029         return;
1030
1031     SandboxExtension::consumePermanently(handle);
1032     auto callbacks = WTFMove(iterator->value);
1033     m_cacheStorageParametersCallbacks.remove(iterator);
1034     for (auto& callback : callbacks)
1035         callback(String { cacheStorageDirectory }, quota);
1036 }
1037
1038 void NetworkProcess::preconnectTo(const URL& url, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
1039 {
1040 #if ENABLE(SERVER_PRECONNECT)
1041     NetworkLoadParameters parameters;
1042     parameters.request = ResourceRequest { url };
1043     parameters.sessionID = PAL::SessionID::defaultSessionID();
1044     parameters.storedCredentialsPolicy = storedCredentialsPolicy;
1045     parameters.shouldPreconnectOnly = PreconnectOnly::Yes;
1046
1047     new PreconnectTask(WTFMove(parameters));
1048 #else
1049     UNUSED_PARAM(url);
1050     UNUSED_PARAM(storedCredentialsPolicy);
1051 #endif
1052 }
1053
1054 void NetworkProcess::registerURLSchemeAsSecure(const String& scheme) const
1055 {
1056     SchemeRegistry::registerURLSchemeAsSecure(scheme);
1057 }
1058
1059 void NetworkProcess::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme) const
1060 {
1061     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
1062 }
1063
1064 void NetworkProcess::registerURLSchemeAsLocal(const String& scheme) const
1065 {
1066     SchemeRegistry::registerURLSchemeAsLocal(scheme);
1067 }
1068
1069 void NetworkProcess::registerURLSchemeAsNoAccess(const String& scheme) const
1070 {
1071     SchemeRegistry::registerURLSchemeAsNoAccess(scheme);
1072 }
1073
1074 void NetworkProcess::registerURLSchemeAsDisplayIsolated(const String& scheme) const
1075 {
1076     SchemeRegistry::registerURLSchemeAsDisplayIsolated(scheme);
1077 }
1078
1079 void NetworkProcess::registerURLSchemeAsCORSEnabled(const String& scheme) const
1080 {
1081     SchemeRegistry::registerURLSchemeAsCORSEnabled(scheme);
1082 }
1083
1084 void NetworkProcess::registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String& scheme) const
1085 {
1086     SchemeRegistry::registerAsCanDisplayOnlyIfCanRequest(scheme);
1087 }
1088
1089 void NetworkProcess::didSyncAllCookies()
1090 {
1091     parentProcessConnection()->send(Messages::NetworkProcessProxy::DidSyncAllCookies(), 0);
1092 }
1093
1094 #if ENABLE(INDEXED_DATABASE)
1095 IDBServer::IDBServer& NetworkProcess::idbServer(PAL::SessionID sessionID)
1096 {
1097     auto addResult = m_idbServers.add(sessionID, nullptr);
1098     if (!addResult.isNewEntry) {
1099         ASSERT(addResult.iterator->value);
1100         return *addResult.iterator->value;
1101     }
1102     
1103     auto path = m_idbDatabasePaths.get(sessionID);
1104     // There should already be a registered path for this PAL::SessionID.
1105     // If there's not, then where did this PAL::SessionID come from?
1106     ASSERT(!path.isEmpty());
1107     
1108     addResult.iterator->value = IDBServer::IDBServer::create(path, NetworkProcess::singleton());
1109     addResult.iterator->value->setPerOriginQuota(m_idbPerOriginQuota);
1110     return *addResult.iterator->value;
1111 }
1112
1113 void NetworkProcess::ensurePathExists(const String& path)
1114 {
1115     ASSERT(!RunLoop::isMain());
1116     
1117     if (!FileSystem::makeAllDirectories(path))
1118         LOG_ERROR("Failed to make all directories for path '%s'", path.utf8().data());
1119 }
1120
1121 void NetworkProcess::postStorageTask(CrossThreadTask&& task)
1122 {
1123     ASSERT(RunLoop::isMain());
1124     
1125     LockHolder locker(m_storageTaskMutex);
1126     
1127     m_storageTasks.append(WTFMove(task));
1128     
1129     m_storageTaskQueue->dispatch([this] {
1130         performNextStorageTask();
1131     });
1132 }
1133
1134 void NetworkProcess::performNextStorageTask()
1135 {
1136     ASSERT(!RunLoop::isMain());
1137     
1138     CrossThreadTask task;
1139     {
1140         LockHolder locker(m_storageTaskMutex);
1141         ASSERT(!m_storageTasks.isEmpty());
1142         task = m_storageTasks.takeFirst();
1143     }
1144     
1145     task.performTask();
1146 }
1147
1148 void NetworkProcess::accessToTemporaryFileComplete(const String& path)
1149 {
1150     // We've either hard linked the temporary blob file to the database directory, copied it there,
1151     // or the transaction is being aborted.
1152     // In any of those cases, we can delete the temporary blob file now.
1153     FileSystem::deleteFile(path);
1154 }
1155
1156 HashSet<WebCore::SecurityOriginData> NetworkProcess::indexedDatabaseOrigins(const String& path)
1157 {
1158     if (path.isEmpty())
1159         return { };
1160     
1161     HashSet<WebCore::SecurityOriginData> securityOrigins;
1162     for (auto& topOriginPath : FileSystem::listDirectory(path, "*")) {
1163         auto databaseIdentifier = FileSystem::pathGetFileName(topOriginPath);
1164         if (auto securityOrigin = SecurityOriginData::fromDatabaseIdentifier(databaseIdentifier))
1165             securityOrigins.add(WTFMove(*securityOrigin));
1166         
1167         for (auto& originPath : FileSystem::listDirectory(topOriginPath, "*")) {
1168             databaseIdentifier = FileSystem::pathGetFileName(originPath);
1169             if (auto securityOrigin = SecurityOriginData::fromDatabaseIdentifier(databaseIdentifier))
1170                 securityOrigins.add(WTFMove(*securityOrigin));
1171         }
1172     }
1173
1174     return securityOrigins;
1175 }
1176
1177 void NetworkProcess::addIndexedDatabaseSession(PAL::SessionID sessionID, String& indexedDatabaseDirectory, SandboxExtension::Handle& handle)
1178 {
1179     // *********
1180     // IMPORTANT: Do not change the directory structure for indexed databases on disk without first consulting a reviewer from Apple (<rdar://problem/17454712>)
1181     // *********
1182     auto addResult = m_idbDatabasePaths.add(sessionID, indexedDatabaseDirectory);
1183     if (addResult.isNewEntry) {
1184         SandboxExtension::consumePermanently(handle);
1185         if (!indexedDatabaseDirectory.isEmpty())
1186             postStorageTask(createCrossThreadTask(*this, &NetworkProcess::ensurePathExists, indexedDatabaseDirectory));
1187     }
1188 }
1189
1190 void NetworkProcess::setIDBPerOriginQuota(uint64_t quota)
1191 {
1192     m_idbPerOriginQuota = quota;
1193     
1194     for (auto& server : m_idbServers.values())
1195         server->setPerOriginQuota(quota);
1196 }
1197 #endif // ENABLE(INDEXED_DATABASE)
1198
1199 #if ENABLE(SANDBOX_EXTENSIONS)
1200 void NetworkProcess::getSandboxExtensionsForBlobFiles(const Vector<String>& filenames, CompletionHandler<void(SandboxExtension::HandleArray&&)>&& completionHandler)
1201 {
1202     parentProcessConnection()->sendWithAsyncReply(Messages::NetworkProcessProxy::GetSandboxExtensionsForBlobFiles(filenames), WTFMove(completionHandler));
1203 }
1204 #endif // ENABLE(SANDBOX_EXTENSIONS)
1205
1206 #if ENABLE(SERVICE_WORKER)
1207 WebSWServerToContextConnection* NetworkProcess::connectionToContextProcessFromIPCConnection(IPC::Connection& connection)
1208 {
1209     for (auto& serverToContextConnection : m_serverToContextConnections.values()) {
1210         if (serverToContextConnection->ipcConnection() == &connection)
1211             return serverToContextConnection.get();
1212     }
1213     return nullptr;
1214 }
1215
1216 void NetworkProcess::connectionToContextProcessWasClosed(Ref<WebSWServerToContextConnection>&& serverToContextConnection)
1217 {
1218     auto& securityOrigin = serverToContextConnection->securityOrigin();
1219     
1220     serverToContextConnection->connectionClosed();
1221     m_serverToContextConnections.remove(securityOrigin);
1222     
1223     for (auto& swServer : m_swServers.values())
1224         swServer->markAllWorkersForOriginAsTerminated(securityOrigin);
1225     
1226     if (needsServerToContextConnectionForOrigin(securityOrigin)) {
1227         RELEASE_LOG(ServiceWorker, "Connection to service worker process was closed but is still needed, relaunching it");
1228         createServerToContextConnection(securityOrigin, std::nullopt);
1229     }
1230 }
1231
1232 bool NetworkProcess::needsServerToContextConnectionForOrigin(const SecurityOriginData& securityOrigin) const
1233 {
1234     return WTF::anyOf(m_swServers.values(), [&](auto& swServer) {
1235         return swServer->needsServerToContextConnectionForOrigin(securityOrigin);
1236     });
1237 }
1238
1239 SWServer& NetworkProcess::swServerForSession(PAL::SessionID sessionID)
1240 {
1241     ASSERT(sessionID.isValid());
1242     
1243     auto result = m_swServers.ensure(sessionID, [&] {
1244         auto path = m_swDatabasePaths.get(sessionID);
1245         // There should already be a registered path for this PAL::SessionID.
1246         // If there's not, then where did this PAL::SessionID come from?
1247         ASSERT(sessionID.isEphemeral() || !path.isEmpty());
1248         
1249         auto value = std::make_unique<SWServer>(makeUniqueRef<WebSWOriginStore>(), WTFMove(path), sessionID);
1250         if (m_shouldDisableServiceWorkerProcessTerminationDelay)
1251             value->disableServiceWorkerProcessTerminationDelay();
1252         return value;
1253     });
1254
1255     return *result.iterator->value;
1256 }
1257
1258 WebSWOriginStore& NetworkProcess::swOriginStoreForSession(PAL::SessionID sessionID)
1259 {
1260     return static_cast<WebSWOriginStore&>(swServerForSession(sessionID).originStore());
1261 }
1262
1263 WebSWOriginStore* NetworkProcess::existingSWOriginStoreForSession(PAL::SessionID sessionID) const
1264 {
1265     auto* swServer = m_swServers.get(sessionID);
1266     if (!swServer)
1267         return nullptr;
1268     return &static_cast<WebSWOriginStore&>(swServer->originStore());
1269 }
1270
1271 WebSWServerToContextConnection* NetworkProcess::serverToContextConnectionForOrigin(const SecurityOriginData& securityOrigin)
1272 {
1273     return m_serverToContextConnections.get(securityOrigin);
1274 }
1275
1276 void NetworkProcess::createServerToContextConnection(const SecurityOriginData& securityOrigin, std::optional<PAL::SessionID> sessionID)
1277 {
1278     if (m_waitingForServerToContextProcessConnection)
1279         return;
1280     
1281     m_waitingForServerToContextProcessConnection = true;
1282     if (sessionID)
1283         parentProcessConnection()->send(Messages::NetworkProcessProxy::EstablishWorkerContextConnectionToNetworkProcessForExplicitSession(securityOrigin, *sessionID), 0);
1284     else
1285         parentProcessConnection()->send(Messages::NetworkProcessProxy::EstablishWorkerContextConnectionToNetworkProcess(securityOrigin), 0);
1286 }
1287
1288 void NetworkProcess::didFailFetch(SWServerConnectionIdentifier serverConnectionIdentifier, FetchIdentifier fetchIdentifier, const ResourceError& error)
1289 {
1290     if (auto* connection = m_swServerConnections.get(serverConnectionIdentifier))
1291         connection->didFailFetch(fetchIdentifier, error);
1292 }
1293
1294 void NetworkProcess::didNotHandleFetch(SWServerConnectionIdentifier serverConnectionIdentifier, FetchIdentifier fetchIdentifier)
1295 {
1296     if (auto* connection = m_swServerConnections.get(serverConnectionIdentifier))
1297         connection->didNotHandleFetch(fetchIdentifier);
1298 }
1299
1300 void NetworkProcess::didReceiveFetchResponse(SWServerConnectionIdentifier serverConnectionIdentifier, FetchIdentifier fetchIdentifier, const WebCore::ResourceResponse& response)
1301 {
1302     if (auto* connection = m_swServerConnections.get(serverConnectionIdentifier))
1303         connection->didReceiveFetchResponse(fetchIdentifier, response);
1304 }
1305
1306 void NetworkProcess::didReceiveFetchData(SWServerConnectionIdentifier serverConnectionIdentifier, FetchIdentifier fetchIdentifier, const IPC::DataReference& data, int64_t encodedDataLength)
1307 {
1308     if (auto* connection = m_swServerConnections.get(serverConnectionIdentifier))
1309         connection->didReceiveFetchData(fetchIdentifier, data, encodedDataLength);
1310 }
1311
1312 void NetworkProcess::didReceiveFetchFormData(SWServerConnectionIdentifier serverConnectionIdentifier, FetchIdentifier fetchIdentifier, const IPC::FormDataReference& formData)
1313 {
1314     if (auto* connection = m_swServerConnections.get(serverConnectionIdentifier))
1315         connection->didReceiveFetchFormData(fetchIdentifier, formData);
1316 }
1317
1318 void NetworkProcess::didFinishFetch(SWServerConnectionIdentifier serverConnectionIdentifier, FetchIdentifier fetchIdentifier)
1319 {
1320     if (auto* connection = m_swServerConnections.get(serverConnectionIdentifier))
1321         connection->didFinishFetch(fetchIdentifier);
1322 }
1323
1324 void NetworkProcess::postMessageToServiceWorkerClient(const ServiceWorkerClientIdentifier& destinationIdentifier, MessageWithMessagePorts&& message, ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin)
1325 {
1326     if (auto* connection = m_swServerConnections.get(destinationIdentifier.serverConnectionIdentifier))
1327         connection->postMessageToServiceWorkerClient(destinationIdentifier.contextIdentifier, WTFMove(message), sourceIdentifier, sourceOrigin);
1328 }
1329
1330 void NetworkProcess::postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&& message, const WebCore::ServiceWorkerOrClientIdentifier& source, SWServerConnectionIdentifier connectionIdentifier)
1331 {
1332     if (auto* connection = m_swServerConnections.get(connectionIdentifier))
1333         connection->postMessageToServiceWorker(destination, WTFMove(message), source);
1334 }
1335
1336 void NetworkProcess::registerSWServerConnection(WebSWServerConnection& connection)
1337 {
1338     ASSERT(parentProcessHasServiceWorkerEntitlement());
1339     ASSERT(!m_swServerConnections.contains(connection.identifier()));
1340     m_swServerConnections.add(connection.identifier(), &connection);
1341     swOriginStoreForSession(connection.sessionID()).registerSWServerConnection(connection);
1342 }
1343
1344 void NetworkProcess::unregisterSWServerConnection(WebSWServerConnection& connection)
1345 {
1346     ASSERT(m_swServerConnections.get(connection.identifier()) == &connection);
1347     m_swServerConnections.remove(connection.identifier());
1348     if (auto* store = existingSWOriginStoreForSession(connection.sessionID()))
1349         store->unregisterSWServerConnection(connection);
1350 }
1351
1352 void NetworkProcess::swContextConnectionMayNoLongerBeNeeded(WebSWServerToContextConnection& serverToContextConnection)
1353 {
1354     auto& securityOrigin = serverToContextConnection.securityOrigin();
1355     if (needsServerToContextConnectionForOrigin(securityOrigin))
1356         return;
1357     
1358     RELEASE_LOG(ServiceWorker, "Service worker process is no longer needed, terminating it");
1359     serverToContextConnection.terminate();
1360     
1361     for (auto& swServer : m_swServers.values())
1362         swServer->markAllWorkersForOriginAsTerminated(securityOrigin);
1363     
1364     serverToContextConnection.connectionClosed();
1365     m_serverToContextConnections.remove(securityOrigin);
1366 }
1367
1368 void NetworkProcess::disableServiceWorkerProcessTerminationDelay()
1369 {
1370     if (m_shouldDisableServiceWorkerProcessTerminationDelay)
1371         return;
1372     
1373     m_shouldDisableServiceWorkerProcessTerminationDelay = true;
1374     for (auto& swServer : m_swServers.values())
1375         swServer->disableServiceWorkerProcessTerminationDelay();
1376 }
1377
1378 void NetworkProcess::addServiceWorkerSession(PAL::SessionID sessionID, String& serviceWorkerRegistrationDirectory, const SandboxExtension::Handle& handle)
1379 {
1380     auto addResult = m_swDatabasePaths.add(sessionID, serviceWorkerRegistrationDirectory);
1381     if (addResult.isNewEntry) {
1382         SandboxExtension::consumePermanently(handle);
1383         if (!serviceWorkerRegistrationDirectory.isEmpty())
1384             postStorageTask(createCrossThreadTask(*this, &NetworkProcess::ensurePathExists, serviceWorkerRegistrationDirectory));
1385     }
1386 }
1387 #endif // ENABLE(SERVICE_WORKER)
1388
1389 #if !PLATFORM(COCOA)
1390 void NetworkProcess::initializeProcess(const ChildProcessInitializationParameters&)
1391 {
1392 }
1393
1394 void NetworkProcess::initializeProcessName(const ChildProcessInitializationParameters&)
1395 {
1396 }
1397
1398 void NetworkProcess::initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&)
1399 {
1400 }
1401
1402 void NetworkProcess::syncAllCookies()
1403 {
1404 }
1405
1406 void NetworkProcess::platformSyncAllCookies(CompletionHandler<void()>&& completionHandler)
1407 {
1408     completionHandler();
1409 }
1410
1411 #endif
1412
1413 } // namespace WebKit