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