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