Unreviewed, reverting r267608.
authorachristensen@apple.com <achristensen@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Sat, 26 Sep 2020 06:39:41 +0000 (06:39 +0000)
committerachristensen@apple.com <achristensen@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Sat, 26 Sep 2020 06:39:41 +0000 (06:39 +0000)
Caused API test failures

Reverted changeset:

"Move NetworkProcessProxy ownership from WebProcessPool to
WebsiteDataStore"
https://bugs.webkit.org/show_bug.cgi?id=216041
https://trac.webkit.org/changeset/267608

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@267618 268f45cc-cd09-0410-ab3c-d52691b4dbfc

87 files changed:
Source/WebKit/ChangeLog
Source/WebKit/NetworkProcess/Cookies/WebCookieManager.cpp
Source/WebKit/NetworkProcess/Cookies/WebCookieManager.h
Source/WebKit/NetworkProcess/Cookies/WebCookieManager.messages.in
Source/WebKit/NetworkProcess/Cookies/curl/WebCookieManagerCurl.cpp
Source/WebKit/NetworkProcess/Cookies/mac/WebCookieManagerMac.mm
Source/WebKit/NetworkProcess/Cookies/soup/WebCookieManagerSoup.cpp
Source/WebKit/NetworkProcess/NetworkProcess.cpp
Source/WebKit/NetworkProcess/NetworkProcess.h
Source/WebKit/NetworkProcess/NetworkProcessCreationParameters.cpp
Source/WebKit/NetworkProcess/NetworkProcessCreationParameters.h
Source/WebKit/NetworkProcess/WebStorage/LocalStorageDatabase.cpp
Source/WebKit/NetworkProcess/cocoa/NetworkProcessCocoa.mm
Source/WebKit/NetworkProcess/curl/NetworkProcessCurl.cpp
Source/WebKit/NetworkProcess/mac/RemoteNetworkingContext.mm
Source/WebKit/NetworkProcess/soup/NetworkProcessMainSoup.cpp
Source/WebKit/NetworkProcess/soup/NetworkProcessSoup.cpp
Source/WebKit/Platform/IPC/Attachment.h
Source/WebKit/Shared/WebsiteDataStoreParameters.cpp
Source/WebKit/Shared/WebsiteDataStoreParameters.h
Source/WebKit/UIProcess/API/APIHTTPCookieStore.cpp
Source/WebKit/UIProcess/API/APIHTTPCookieStore.h
Source/WebKit/UIProcess/API/C/WKContext.cpp
Source/WebKit/UIProcess/API/C/WKContext.h
Source/WebKit/UIProcess/API/C/WKContextPrivate.h
Source/WebKit/UIProcess/API/C/WKPage.cpp
Source/WebKit/UIProcess/API/C/WKPage.h
Source/WebKit/UIProcess/API/C/WKWebsiteDataStoreRef.cpp
Source/WebKit/UIProcess/API/C/WKWebsiteDataStoreRef.h
Source/WebKit/UIProcess/API/Cocoa/WKProcessPool.mm
Source/WebKit/UIProcess/API/Cocoa/WKProcessPoolPrivate.h
Source/WebKit/UIProcess/API/Cocoa/WKWebsiteDataStore.mm
Source/WebKit/UIProcess/API/Cocoa/WKWebsiteDataStorePrivate.h
Source/WebKit/UIProcess/API/glib/WebKitCookieManager.cpp
Source/WebKit/UIProcess/API/glib/WebKitWebContext.cpp
Source/WebKit/UIProcess/API/glib/WebKitWebView.cpp
Source/WebKit/UIProcess/API/glib/WebKitWebsiteDataManager.cpp
Source/WebKit/UIProcess/API/glib/WebKitWebsiteDataManagerPrivate.h
Source/WebKit/UIProcess/Automation/WebAutomationSession.cpp
Source/WebKit/UIProcess/AuxiliaryProcessProxy.h
Source/WebKit/UIProcess/Cocoa/LegacyCustomProtocolManagerClient.h
Source/WebKit/UIProcess/Cocoa/WebProcessPoolCocoa.mm
Source/WebKit/UIProcess/Downloads/DownloadProxy.cpp
Source/WebKit/UIProcess/Downloads/DownloadProxyMap.cpp
Source/WebKit/UIProcess/Downloads/DownloadProxyMap.h
Source/WebKit/UIProcess/Network/CustomProtocols/LegacyCustomProtocolManagerProxy.cpp
Source/WebKit/UIProcess/Network/NetworkProcessProxy.cpp
Source/WebKit/UIProcess/Network/NetworkProcessProxy.h
Source/WebKit/UIProcess/Network/NetworkProcessProxyCocoa.mm
Source/WebKit/UIProcess/WebCookieManagerProxy.cpp
Source/WebKit/UIProcess/WebCookieManagerProxy.h
Source/WebKit/UIProcess/WebPageProxy.cpp
Source/WebKit/UIProcess/WebProcessPool.cpp
Source/WebKit/UIProcess/WebProcessPool.h
Source/WebKit/UIProcess/WebProcessProxy.cpp
Source/WebKit/UIProcess/WebsiteData/Cocoa/WebsiteDataStoreCocoa.mm
Source/WebKit/UIProcess/WebsiteData/WebsiteDataStore.cpp
Source/WebKit/UIProcess/WebsiteData/WebsiteDataStore.h
Source/WebKit/UIProcess/WebsiteData/curl/WebsiteDataStoreCurl.cpp
Source/WebKit/UIProcess/WebsiteData/soup/WebsiteDataStoreSoup.cpp
Source/WebKit/UIProcess/glib/WebProcessProxyGLib.cpp
Source/WebKit/UIProcess/soup/WebCookieManagerProxySoup.cpp
Source/WebKit/UIProcess/soup/WebProcessPoolSoup.cpp
Source/WebKit/WebProcess/Network/NetworkProcessConnectionInfo.h
Tools/ChangeLog
Tools/TestWebKitAPI/Tests/WebKit/NetworkProcessCrashWithPendingConnection.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/Download.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IDBCheckpointWAL.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IDBDeleteRecovery.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IDBIndexUpgradeToV2.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IDBObjectStoreInfoUpgradeToV2.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IndexedDBDatabaseProcessKill.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IndexedDBMultiProcess.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IndexedDBPersistence.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IndexedDBSuspendImminently.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/IndexedDBTempFileSize.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/LocalStoragePersistence.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/NetworkProcess.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/NetworkProcessCrashNonPersistentDataStore.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/ProcessSwapOnNavigation.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/ResourceLoadStatistics.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/WKHTTPCookieStore.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/WKURLSchemeHandler-leaks.mm
Tools/TestWebKitAPI/Tests/WebKitCocoa/WebsiteDataStoreCustomPaths.mm
Tools/TestWebKitAPI/Tests/WebKitObjC/CustomProtocolsTest.mm
Tools/WebKitTestRunner/TestController.cpp

index ca031a9..17d3060 100644 (file)
@@ -1,3 +1,16 @@
+2020-09-25  Alex Christensen  <achristensen@webkit.org>
+
+        Unreviewed, reverting r267608.
+
+        Caused API test failures
+
+        Reverted changeset:
+
+        "Move NetworkProcessProxy ownership from WebProcessPool to
+        WebsiteDataStore"
+        https://bugs.webkit.org/show_bug.cgi?id=216041
+        https://trac.webkit.org/changeset/267608
+
 2020-09-25  Tim Horton  <timothy_horton@apple.com>
 
         Crunchyroll playback controls do not work on iPad with trackpad
index 5c9b771..fce2389 100644 (file)
@@ -32,7 +32,6 @@
 #include "WebCoreArgumentCoders.h"
 #include <WebCore/Cookie.h>
 #include <WebCore/CookieStorage.h>
-#include <WebCore/HTTPCookieAcceptPolicy.h>
 #include <WebCore/NetworkStorageSession.h>
 #include <wtf/MainThread.h>
 #include <wtf/URL.h>
@@ -144,18 +143,15 @@ void WebCookieManager::stopObservingCookieChanges(PAL::SessionID sessionID)
 
 void WebCookieManager::setHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy, CompletionHandler<void()>&& completionHandler)
 {
-    platformSetHTTPCookieAcceptPolicy(policy, [policy, process = makeRef(m_process), completionHandler = WTFMove(completionHandler)] () mutable {
-        process->cookieAcceptPolicyChanged(policy);
-        completionHandler();
-    });
+    platformSetHTTPCookieAcceptPolicy(policy);
+    m_process.cookieAcceptPolicyChanged(policy);
+
+    completionHandler();
 }
 
-void WebCookieManager::getHTTPCookieAcceptPolicy(PAL::SessionID sessionID, CompletionHandler<void(HTTPCookieAcceptPolicy)>&& completionHandler)
+void WebCookieManager::getHTTPCookieAcceptPolicy(CompletionHandler<void(HTTPCookieAcceptPolicy)>&& completionHandler)
 {
-    if (auto* storageSession = m_process.storageSession(sessionID))
-        completionHandler(storageSession->cookieAcceptPolicy());
-    else
-        completionHandler(HTTPCookieAcceptPolicy::Never);
+    completionHandler(m_process.defaultStorageSession().cookieAcceptPolicy());
 }
 
 } // namespace WebKit
index 35ce8a9..ca7f55e 100644 (file)
@@ -37,8 +37,6 @@
 #include "SoupCookiePersistentStorageType.h"
 #endif
 
-OBJC_CLASS NSHTTPCookieStorage;
-
 namespace WebCore {
 struct Cookie;
 enum class HTTPCookieAcceptPolicy : uint8_t;
@@ -81,8 +79,8 @@ private:
     void getAllCookies(PAL::SessionID, CompletionHandler<void(Vector<WebCore::Cookie>&&)>&&);
     void getCookies(PAL::SessionID, const URL&, CompletionHandler<void(Vector<WebCore::Cookie>&&)>&&);
 
-    void platformSetHTTPCookieAcceptPolicy(WebCore::HTTPCookieAcceptPolicy, CompletionHandler<void()>&&);
-    void getHTTPCookieAcceptPolicy(PAL::SessionID, CompletionHandler<void(WebCore::HTTPCookieAcceptPolicy)>&&);
+    void platformSetHTTPCookieAcceptPolicy(WebCore::HTTPCookieAcceptPolicy);
+    void getHTTPCookieAcceptPolicy(CompletionHandler<void(WebCore::HTTPCookieAcceptPolicy)>&&);
 
     void startObservingCookieChanges(PAL::SessionID);
     void stopObservingCookieChanges(PAL::SessionID);
@@ -90,8 +88,4 @@ private:
     NetworkProcess& m_process;
 };
 
-#if PLATFORM(COCOA)
-void saveCookies(NSHTTPCookieStorage *, CompletionHandler<void()>&&);
-#endif
-
 } // namespace WebKit
index 6fdf577..acd7544 100644 (file)
@@ -36,7 +36,7 @@ messages -> WebCookieManager NotRefCounted {
     void DeleteAllCookiesModifiedSince(PAL::SessionID sessionID, WallTime time) -> () Async
 
     void SetHTTPCookieAcceptPolicy(enum:uint8_t WebCore::HTTPCookieAcceptPolicy policy) -> () Async
-    void GetHTTPCookieAcceptPolicy(PAL::SessionID sessionID) -> (enum:uint8_t WebCore::HTTPCookieAcceptPolicy policy) Async
+    void GetHTTPCookieAcceptPolicy() -> (enum:uint8_t WebCore::HTTPCookieAcceptPolicy policy) Async
     
     void StartObservingCookieChanges(PAL::SessionID sessionID)
     void StopObservingCookieChanges(PAL::SessionID sessionID)
index faada50..c2ef156 100644 (file)
@@ -34,7 +34,7 @@ namespace WebKit {
 
 using namespace WebCore;
 
-void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy, CompletionHandler<void()>&& completionHandler)
+void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy)
 {
     CookieAcceptPolicy curlPolicy = CookieAcceptPolicy::OnlyFromMainDocumentDomain;
     switch (policy) {
@@ -55,7 +55,6 @@ void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy
     m_process.forEachNetworkStorageSession([curlPolicy] (const auto& networkStorageSession) {
         networkStorageSession.setCookieAcceptPolicy(curlPolicy);
     });
-    completionHandler();
 }
 
 } // namespace WebKit
index 7f9120c..19f5878 100644 (file)
@@ -31,7 +31,6 @@
 #import <WebCore/HTTPCookieAcceptPolicy.h>
 #import <WebCore/NetworkStorageSession.h>
 #import <pal/spi/cf/CFNetworkSPI.h>
-#import <wtf/CallbackAggregator.h>
 #import <wtf/ProcessPrivilege.h>
 
 namespace WebKit {
@@ -54,19 +53,15 @@ static CFHTTPCookieStorageAcceptPolicy toCFHTTPCookieStorageAcceptPolicy(HTTPCoo
     return CFHTTPCookieStorageAcceptPolicyAlways;
 }
 
-void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy, CompletionHandler<void()>&& completionHandler)
+void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy)
 {
     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
 
-    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:static_cast<NSHTTPCookieAcceptPolicy>(policy)];
-    saveCookies([NSHTTPCookieStorage sharedHTTPCookieStorage], [callbackAggregator] { });
 
     m_process.forEachNetworkStorageSession([&] (const auto& networkStorageSession) {
         if (auto cookieStorage = networkStorageSession.cookieStorage())
             CFHTTPCookieStorageSetCookieAcceptPolicy(cookieStorage.get(), toCFHTTPCookieStorageAcceptPolicy(policy));
-        if (auto *storage = networkStorageSession.nsCookieStorage())
-            saveCookies(storage, [callbackAggregator] { });
     });
 }
 
index d576afd..754d0bb 100644 (file)
 namespace WebKit {
 using namespace WebCore;
 
-void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy, CompletionHandler<void()>&& completionHandler)
+void WebCookieManager::platformSetHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy)
 {
     m_process.forEachNetworkStorageSession([policy] (auto& session) {
         session.setCookieAcceptPolicy(policy);
     });
-    completionHandler();
 }
 
 void WebCookieManager::setCookiePersistentStorage(PAL::SessionID sessionID, const String& storagePath, SoupCookiePersistentStorageType storageType)
index 3e859eb..be8d966 100644 (file)
@@ -173,7 +173,6 @@ NetworkProcess::NetworkProcess(AuxiliaryProcessInitializationParameters&& parame
 #endif
 
 #if USE(SOUP)
-    // FIXME: Do not use the default session ID.
     DNSResolveQueueSoup::setGlobalDefaultSoupSessionAccessor([this]() -> SoupSession* {
         return static_cast<NetworkSessionSoup&>(*networkSession(PAL::SessionID::defaultSessionID())).soupSession();
     });
@@ -348,6 +347,30 @@ void NetworkProcess::initializeNetworkProcess(NetworkProcessCreationParameters&&
 
     setAdClickAttributionDebugMode(parameters.enableAdClickAttributionDebugMode);
 
+    SandboxExtension::consumePermanently(parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsParameters.directoryExtensionHandle);
+
+    auto sessionID = parameters.defaultDataStoreParameters.networkSessionParameters.sessionID;
+    setSession(sessionID, NetworkSession::create(*this, WTFMove(parameters.defaultDataStoreParameters.networkSessionParameters)));
+
+    SandboxExtension::consumePermanently(parameters.defaultDataStoreParameters.cacheStorageDirectoryExtensionHandle);
+    addSessionStorageQuotaManager(sessionID, parameters.defaultDataStoreParameters.perOriginStorageQuota, parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota, parameters.defaultDataStoreParameters.cacheStorageDirectory, parameters.defaultDataStoreParameters.cacheStorageDirectoryExtensionHandle);
+
+#if ENABLE(INDEXED_DATABASE)
+    addIndexedDatabaseSession(sessionID, parameters.defaultDataStoreParameters.indexedDatabaseDirectory, parameters.defaultDataStoreParameters.indexedDatabaseDirectoryExtensionHandle);
+#endif
+
+#if ENABLE(SERVICE_WORKER)
+    bool serviceWorkerProcessTerminationDelayEnabled = true;
+    addServiceWorkerSession(PAL::SessionID::defaultSessionID(), serviceWorkerProcessTerminationDelayEnabled, WTFMove(parameters.serviceWorkerRegistrationDirectory), parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
+#endif
+
+    m_storageManagerSet->add(sessionID, parameters.defaultDataStoreParameters.localStorageDirectory, parameters.defaultDataStoreParameters.localStorageDirectoryExtensionHandle);
+
+    auto* defaultSession = networkSession(PAL::SessionID::defaultSessionID());
+    auto* defaultStorageSession = defaultSession->networkStorageSession();
+    for (const auto& cookie : parameters.defaultDataStoreParameters.pendingCookies)
+        defaultStorageSession->setCookie(cookie);
+
     for (auto& supplement : m_supplements.values())
         supplement->initialize(parameters);
 
@@ -482,6 +505,8 @@ void NetworkProcess::ensureSession(const PAL::SessionID& sessionID, bool shouldU
 void NetworkProcess::ensureSession(const PAL::SessionID& sessionID, bool shouldUseTestingNetworkSession, const String& identifierBase)
 #endif
 {
+    ASSERT(sessionID != PAL::SessionID::defaultSessionID());
+
     auto addResult = m_networkStorageSessions.add(sessionID, nullptr);
     if (!addResult.isNewEntry)
         return;
@@ -496,7 +521,7 @@ void NetworkProcess::ensureSession(const PAL::SessionID& sessionID, bool shouldU
     RetainPtr<CFStringRef> cfIdentifier = makeString(identifierBase, ".PrivateBrowsing.", createCanonicalUUIDString()).createCFString();
     if (sessionID.isEphemeral())
         storageSession = adoptCF(createPrivateStorageSession(cfIdentifier.get()));
-    else if (sessionID != PAL::SessionID::defaultSessionID())
+    else
         storageSession = WebCore::NetworkStorageSession::createCFStorageSessionForIdentifier(cfIdentifier.get());
 
     if (NetworkStorageSession::processMayUseCookieAPI()) {
@@ -519,11 +544,21 @@ void NetworkProcess::cookieAcceptPolicyChanged(HTTPCookieAcceptPolicy newPolicy)
 
 WebCore::NetworkStorageSession* NetworkProcess::storageSession(const PAL::SessionID& sessionID) const
 {
+    if (sessionID == PAL::SessionID::defaultSessionID())
+        return &defaultStorageSession();
     return m_networkStorageSessions.get(sessionID);
 }
 
+WebCore::NetworkStorageSession& NetworkProcess::defaultStorageSession() const
+{
+    if (!m_defaultNetworkStorageSession)
+        m_defaultNetworkStorageSession = platformCreateDefaultStorageSession();
+    return *m_defaultNetworkStorageSession;
+}
+
 void NetworkProcess::forEachNetworkStorageSession(const Function<void(WebCore::NetworkStorageSession&)>& functor)
 {
+    functor(defaultStorageSession());
     for (auto& storageSession : m_networkStorageSessions.values())
         functor(*storageSession);
 }
index c8b4577..6ad3d69 100644 (file)
@@ -170,6 +170,7 @@ public:
 
     void forEachNetworkStorageSession(const Function<void(WebCore::NetworkStorageSession&)>&);
     WebCore::NetworkStorageSession* storageSession(const PAL::SessionID&) const;
+    WebCore::NetworkStorageSession& defaultStorageSession() const;
     std::unique_ptr<WebCore::NetworkStorageSession> newTestingSession(const PAL::SessionID&);
 #if PLATFORM(COCOA)
     void ensureSession(const PAL::SessionID&, bool shouldUseTestingNetworkSession, const String& identifier, RetainPtr<CFHTTPCookieStorageRef>&&);
@@ -374,6 +375,7 @@ public:
 
 private:
     void platformInitializeNetworkProcess(const NetworkProcessCreationParameters&);
+    std::unique_ptr<WebCore::NetworkStorageSession> platformCreateDefaultStorageSession() const;
 
     void didReceiveNetworkProcessMessage(IPC::Connection&, IPC::Decoder&);
 
@@ -542,6 +544,7 @@ private:
 
     HashMap<PAL::SessionID, std::unique_ptr<NetworkSession>> m_networkSessions;
     HashMap<PAL::SessionID, std::unique_ptr<WebCore::NetworkStorageSession>> m_networkStorageSessions;
+    mutable std::unique_ptr<WebCore::NetworkStorageSession> m_defaultNetworkStorageSession;
 
     RefPtr<StorageManagerSet> m_storageManagerSet;
 
index 90639b6..cc5c44b 100644 (file)
@@ -55,6 +55,7 @@ void NetworkProcessCreationParameters::encode(IPC::Encoder& encoder) const
     encoder << uiProcessSDKVersion;
     IPC::encode(encoder, networkATSContext.get());
 #endif
+    encoder << defaultDataStoreParameters;
 #if USE(SOUP)
     encoder << cookieAcceptPolicy;
     encoder << languages;
@@ -65,6 +66,9 @@ void NetworkProcessCreationParameters::encode(IPC::Encoder& encoder) const
     encoder << urlSchemesRegisteredAsLocal;
     encoder << urlSchemesRegisteredAsNoAccess;
 
+#if ENABLE(SERVICE_WORKER)
+    encoder << serviceWorkerRegistrationDirectory << serviceWorkerRegistrationDirectoryExtensionHandle << shouldDisableServiceWorkerProcessTerminationDelay;
+#endif
     encoder << shouldEnableITPDatabase;
     encoder << enableAdClickAttributionDebugMode;
 }
@@ -110,6 +114,12 @@ bool NetworkProcessCreationParameters::decode(IPC::Decoder& decoder, NetworkProc
         return false;
 #endif
 
+    Optional<WebsiteDataStoreParameters> defaultDataStoreParameters;
+    decoder >> defaultDataStoreParameters;
+    if (!defaultDataStoreParameters)
+        return false;
+    result.defaultDataStoreParameters = WTFMove(*defaultDataStoreParameters);
+
 #if USE(SOUP)
     if (!decoder.decode(result.cookieAcceptPolicy))
         return false;
@@ -126,6 +136,20 @@ bool NetworkProcessCreationParameters::decode(IPC::Decoder& decoder, NetworkProc
     if (!decoder.decode(result.urlSchemesRegisteredAsNoAccess))
         return false;
 
+#if ENABLE(SERVICE_WORKER)
+    if (!decoder.decode(result.serviceWorkerRegistrationDirectory))
+        return false;
+    
+    Optional<SandboxExtension::Handle> serviceWorkerRegistrationDirectoryExtensionHandle;
+    decoder >> serviceWorkerRegistrationDirectoryExtensionHandle;
+    if (!serviceWorkerRegistrationDirectoryExtensionHandle)
+        return false;
+    result.serviceWorkerRegistrationDirectoryExtensionHandle = WTFMove(*serviceWorkerRegistrationDirectoryExtensionHandle);
+
+    if (!decoder.decode(result.shouldDisableServiceWorkerProcessTerminationDelay))
+        return false;
+#endif
+
     if (!decoder.decode(result.shouldEnableITPDatabase))
         return false;
 
index ce03ab3..dff3e5f 100644 (file)
@@ -27,6 +27,7 @@
 
 #include "CacheModel.h"
 #include "SandboxExtension.h"
+#include "WebsiteDataStoreParameters.h"
 #include <WebCore/Cookie.h>
 #include <wtf/ProcessID.h>
 #include <wtf/Vector.h>
@@ -69,6 +70,8 @@ struct NetworkProcessCreationParameters {
     RetainPtr<CFDataRef> networkATSContext;
 #endif
 
+    WebsiteDataStoreParameters defaultDataStoreParameters;
+    
 #if USE(SOUP)
     WebCore::HTTPCookieAcceptPolicy cookieAcceptPolicy { WebCore::HTTPCookieAcceptPolicy::AlwaysAccept };
     Vector<String> languages;
@@ -79,6 +82,11 @@ struct NetworkProcessCreationParameters {
     Vector<String> urlSchemesRegisteredAsLocal;
     Vector<String> urlSchemesRegisteredAsNoAccess;
 
+#if ENABLE(SERVICE_WORKER)
+    String serviceWorkerRegistrationDirectory;
+    SandboxExtension::Handle serviceWorkerRegistrationDirectoryExtensionHandle;
+    bool shouldDisableServiceWorkerProcessTerminationDelay { false };
+#endif
     bool shouldEnableITPDatabase { false };
     bool enableAdClickAttributionDebugMode { false };
 };
index 02c8673..f995e01 100644 (file)
@@ -214,8 +214,7 @@ void LocalStorageDatabase::clear()
 
 void LocalStorageDatabase::close()
 {
-    if (m_isClosed)
-        return;
+    ASSERT(!m_isClosed);
     m_isClosed = true;
 
     if (m_didScheduleDatabaseUpdate) {
index 82d4420..da63591 100644 (file)
@@ -33,7 +33,6 @@
 #import "NetworkResourceLoader.h"
 #import "NetworkSessionCocoa.h"
 #import "SandboxExtension.h"
-#import "WebCookieManager.h"
 #import <WebCore/NetworkStorageSession.h>
 #import <WebCore/PublicSuffix.h>
 #import <WebCore/ResourceRequestCFNet.h>
@@ -79,6 +78,9 @@ void NetworkProcess::platformInitializeNetworkProcessCocoa(const NetworkProcessC
     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
     SandboxExtension::consumePermanently(parameters.parentBundleDirectoryExtensionHandle);
+#if ENABLE(INDEXED_DATABASE)
+    SandboxExtension::consumePermanently(parameters.defaultDataStoreParameters.indexedDatabaseTempBlobDirectoryExtensionHandle);
+#endif
 #endif
 
     _CFNetworkSetATSContext(parameters.networkATSContext.get());
@@ -103,6 +105,11 @@ void NetworkProcess::platformInitializeNetworkProcessCocoa(const NetworkProcessC
     [NSURLCache setSharedURLCache:urlCache.get()];
 }
 
+std::unique_ptr<WebCore::NetworkStorageSession> NetworkProcess::platformCreateDefaultStorageSession() const
+{
+    return makeUnique<WebCore::NetworkStorageSession>(PAL::SessionID::defaultSessionID());
+}
+
 RetainPtr<CFDataRef> NetworkProcess::sourceApplicationAuditData() const
 {
 #if USE(SOURCE_APPLICATION_AUDIT_DATA)
@@ -214,7 +221,7 @@ void NetworkProcess::flushCookies(const PAL::SessionID& sessionID, CompletionHan
     platformFlushCookies(sessionID, WTFMove(completionHandler));
 }
 
-void saveCookies(NSHTTPCookieStorage *cookieStorage, CompletionHandler<void()>&& completionHandler)
+static void saveCookies(NSHTTPCookieStorage *cookieStorage, CompletionHandler<void()>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
     ASSERT(cookieStorage);
index 4953811..d99f9dd 100644 (file)
@@ -39,6 +39,11 @@ void NetworkProcess::platformInitializeNetworkProcess(const NetworkProcessCreati
 {
 }
 
+std::unique_ptr<WebCore::NetworkStorageSession> NetworkProcess::platformCreateDefaultStorageSession() const
+{
+    return makeUnique<WebCore::NetworkStorageSession>(PAL::SessionID::defaultSessionID());
+}
+
 void NetworkProcess::allowSpecificHTTPSCertificateForHost(const CertificateInfo& certificateInfo, const String& host)
 {
     notImplemented();
index 1e18489..c2736e0 100644 (file)
@@ -55,11 +55,15 @@ void RemoteNetworkingContext::ensureWebsiteDataStoreSession(NetworkProcess& netw
         SandboxExtension::consumePermanently(parameters.cookieStoragePathExtensionHandle);
 
     RetainPtr<CFHTTPCookieStorageRef> uiProcessCookieStorage;
-    if (!sessionID.isEphemeral() && !parameters.uiProcessCookieStorageIdentifier.isEmpty() && parameters.networkSessionParameters.sessionID != PAL::SessionID::defaultSessionID())
+    if (!sessionID.isEphemeral() && !parameters.uiProcessCookieStorageIdentifier.isEmpty())
         uiProcessCookieStorage = cookieStorageFromIdentifyingData(parameters.uiProcessCookieStorageIdentifier);
 
     networkProcess.ensureSession(sessionID, parameters.networkSessionParameters.shouldUseTestingNetworkSession, makeString(base, '.', sessionID.toUInt64()), WTFMove(uiProcessCookieStorage));
 
+    auto* session = networkProcess.storageSession(sessionID);
+    for (const auto& cookie : parameters.pendingCookies)
+        session->setCookie(cookie);
+
     networkProcess.setSession(sessionID, NetworkSession::create(networkProcess, WTFMove(parameters.networkSessionParameters)));
 }
 
index a4c031d..0d31b3d 100644 (file)
@@ -39,7 +39,6 @@ class NetworkProcessMainSoup final: public AuxiliaryProcessMainBase {
 public:
     void platformFinalize() override
     {
-        // FIXME: Is this still needed? We should probably destroy all existing sessions at this point instead.
         // Needed to destroy the SoupSession and SoupCookieJar, e.g. to avoid
         // leaking SQLite temporary journaling files.
         globalNetworkProcess->destroySession(PAL::SessionID::defaultSessionID());
index 00ff8b2..a212845 100644 (file)
@@ -135,6 +135,11 @@ void NetworkProcess::platformInitializeNetworkProcess(const NetworkProcessCreati
         userPreferredLanguagesChanged(parameters.languages);
 }
 
+std::unique_ptr<WebCore::NetworkStorageSession> NetworkProcess::platformCreateDefaultStorageSession() const
+{
+    return makeUnique<WebCore::NetworkStorageSession>(PAL::SessionID::defaultSessionID());
+}
+
 void NetworkProcess::setIgnoreTLSErrors(PAL::SessionID sessionID, bool ignoreTLSErrors)
 {
     if (auto* session = networkSession(sessionID))
index d6ff3c1..1743c3b 100644 (file)
@@ -95,8 +95,8 @@ private:
     int m_fileDescriptor { -1 };
     size_t m_size;
 #elif OS(DARWIN)
-    mach_port_name_t m_port { 0 };
-    mach_msg_type_name_t m_disposition { 0 };
+    mach_port_name_t m_port;
+    mach_msg_type_name_t m_disposition;
 #elif OS(WINDOWS)
     HANDLE m_handle { INVALID_HANDLE_VALUE };
 #endif
index 04810b3..6d0c129 100644 (file)
@@ -40,9 +40,13 @@ void WebsiteDataStoreParameters::encode(IPC::Encoder& encoder) const
     encoder << networkSessionParameters;
     encoder << uiProcessCookieStorageIdentifier;
     encoder << cookieStoragePathExtensionHandle;
+    encoder << pendingCookies;
 
 #if ENABLE(INDEXED_DATABASE)
     encoder << indexedDatabaseDirectory << indexedDatabaseDirectoryExtensionHandle;
+#if PLATFORM(IOS_FAMILY)
+    encoder << indexedDatabaseTempBlobDirectoryExtensionHandle;
+#endif
 #endif
 
 #if ENABLE(SERVICE_WORKER)
@@ -79,6 +83,12 @@ Optional<WebsiteDataStoreParameters> WebsiteDataStoreParameters::decode(IPC::Dec
         return WTF::nullopt;
     parameters.cookieStoragePathExtensionHandle = WTFMove(*cookieStoragePathExtensionHandle);
 
+    Optional<Vector<WebCore::Cookie>> pendingCookies;
+    decoder >> pendingCookies;
+    if (!pendingCookies)
+        return WTF::nullopt;
+    parameters.pendingCookies = WTFMove(*pendingCookies);
+
 #if ENABLE(INDEXED_DATABASE)
     Optional<String> indexedDatabaseDirectory;
     decoder >> indexedDatabaseDirectory;
@@ -91,6 +101,14 @@ Optional<WebsiteDataStoreParameters> WebsiteDataStoreParameters::decode(IPC::Dec
     if (!indexedDatabaseDirectoryExtensionHandle)
         return WTF::nullopt;
     parameters.indexedDatabaseDirectoryExtensionHandle = WTFMove(*indexedDatabaseDirectoryExtensionHandle);
+
+#if PLATFORM(IOS_FAMILY)
+    Optional<SandboxExtension::Handle> indexedDatabaseTempBlobDirectoryExtensionHandle;
+    decoder >> indexedDatabaseTempBlobDirectoryExtensionHandle;
+    if (!indexedDatabaseTempBlobDirectoryExtensionHandle)
+        return WTF::nullopt;
+    parameters.indexedDatabaseTempBlobDirectoryExtensionHandle = WTFMove(*indexedDatabaseTempBlobDirectoryExtensionHandle);
+#endif
 #endif
 
 #if ENABLE(SERVICE_WORKER)
index e1b2337..f27df48 100644 (file)
@@ -51,11 +51,15 @@ struct WebsiteDataStoreParameters {
 
     Vector<uint8_t> uiProcessCookieStorageIdentifier;
     SandboxExtension::Handle cookieStoragePathExtensionHandle;
+    Vector<WebCore::Cookie> pendingCookies;
     NetworkSessionCreationParameters networkSessionParameters;
 
 #if ENABLE(INDEXED_DATABASE)
     String indexedDatabaseDirectory;
     SandboxExtension::Handle indexedDatabaseDirectoryExtensionHandle;
+#if PLATFORM(IOS_FAMILY)
+    SandboxExtension::Handle indexedDatabaseTempBlobDirectoryExtensionHandle;
+#endif
 #endif
 
 #if ENABLE(SERVICE_WORKER)
index ff95589..bc07866 100644 (file)
@@ -46,6 +46,8 @@ namespace API {
 HTTPCookieStore::HTTPCookieStore(WebKit::WebsiteDataStore& websiteDataStore)
     : m_owningDataStore(websiteDataStore)
 {
+    if (!m_owningDataStore->processPoolForCookieStorageOperations())
+        registerForNewProcessPoolNotifications();
 }
 
 HTTPCookieStore::~HTTPCookieStore()
@@ -53,6 +55,8 @@ HTTPCookieStore::~HTTPCookieStore()
     ASSERT(m_observers.isEmpty());
     ASSERT(!m_observedCookieManagerProxy);
     ASSERT(!m_cookieManagerProxyObserver);
+
+    unregisterForNewProcessPoolNotifications();
 }
 
 void HTTPCookieStore::filterAppBoundCookies(const Vector<WebCore::Cookie>& cookies, CompletionHandler<void(Vector<WebCore::Cookie>&&)>&& completionHandler)
@@ -77,16 +81,33 @@ void HTTPCookieStore::filterAppBoundCookies(const Vector<WebCore::Cookie>& cooki
 
 void HTTPCookieStore::cookies(CompletionHandler<void(const Vector<WebCore::Cookie>&)>&& completionHandler)
 {
-    auto& cookieManager = m_owningDataStore->networkProcess().cookieManager();
-    cookieManager.getAllCookies(m_owningDataStore->sessionID(), [this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)] (const Vector<WebCore::Cookie>& cookies) mutable {
+    auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+    if (!pool) {
+        Vector<WebCore::Cookie> allCookies;
+        if (m_owningDataStore->sessionID() == PAL::SessionID::defaultSessionID())
+            allCookies = getAllDefaultUIProcessCookieStoreCookies();
+        allCookies.appendVector(m_owningDataStore->pendingCookies());
+
+        RunLoop::main().dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler), allCookies] () mutable {
+            filterAppBoundCookies(allCookies, WTFMove(completionHandler));
+        });
+        return;
+    }
+
+    auto* cookieManager = pool->supplement<WebKit::WebCookieManagerProxy>();
+    cookieManager->getAllCookies(m_owningDataStore->sessionID(), [this, protectedThis = makeRef(*this), pool = WTFMove(pool), completionHandler = WTFMove(completionHandler)] (const Vector<WebCore::Cookie>& cookies) mutable {
         filterAppBoundCookies(cookies, WTFMove(completionHandler));
     });
 }
 
 void HTTPCookieStore::cookiesForURL(WTF::URL&& url, CompletionHandler<void(Vector<WebCore::Cookie>&&)>&& completionHandler)
 {
-    auto& cookieManager = m_owningDataStore->networkProcess().cookieManager();
-    cookieManager.getCookies(m_owningDataStore->sessionID(), url, [this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)] (Vector<WebCore::Cookie>&& cookies) mutable {
+    auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+    if (!pool)
+        return completionHandler({ });
+
+    auto* cookieManager = pool->supplement<WebKit::WebCookieManagerProxy>();
+    cookieManager->getCookies(m_owningDataStore->sessionID(), url, [this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)] (Vector<WebCore::Cookie>&& cookies) mutable {
         filterAppBoundCookies(cookies, WTFMove(completionHandler));
     });
 }
@@ -94,29 +115,78 @@ void HTTPCookieStore::cookiesForURL(WTF::URL&& url, CompletionHandler<void(Vecto
 void HTTPCookieStore::setCookies(const Vector<WebCore::Cookie>& cookies, CompletionHandler<void()>&& completionHandler)
 {
     filterAppBoundCookies(cookies, [this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)] (auto&& appBoundCookies) mutable {
-        auto& cookieManager = m_owningDataStore->networkProcess().cookieManager();
-        cookieManager.setCookies(m_owningDataStore->sessionID(), appBoundCookies, WTFMove(completionHandler));
+        auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+        if (!pool) {
+            for (auto& cookie : appBoundCookies) {
+                // FIXME: pendingCookies used for defaultSession because session cookies cannot be propagated to Network Process with uiProcessCookieStorageIdentifier.
+                if (m_owningDataStore->sessionID() == PAL::SessionID::defaultSessionID() && !cookie.session)
+                    setCookieInDefaultUIProcessCookieStore(cookie);
+                else
+                    m_owningDataStore->addPendingCookie(cookie);
+            }
+
+            RunLoop::main().dispatch(WTFMove(completionHandler));
+            return;
+        }
+
+        auto* cookieManager = pool->supplement<WebKit::WebCookieManagerProxy>();
+        cookieManager->setCookies(m_owningDataStore->sessionID(), appBoundCookies, [pool = WTFMove(pool), completionHandler = WTFMove(completionHandler)] () mutable {
+            completionHandler();
+        });
     });
 }
 
 void HTTPCookieStore::deleteCookie(const WebCore::Cookie& cookie, CompletionHandler<void()>&& completionHandler)
 {
-    auto& cookieManager = m_owningDataStore->networkProcess().cookieManager();
-    cookieManager.deleteCookie(m_owningDataStore->sessionID(), cookie, WTFMove(completionHandler));
+    auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+    if (!pool) {
+        if (m_owningDataStore->sessionID() == PAL::SessionID::defaultSessionID() && !cookie.session)
+            deleteCookieFromDefaultUIProcessCookieStore(cookie);
+        else
+            m_owningDataStore->removePendingCookie(cookie);
+
+        RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)] () mutable {
+            completionHandler();
+        });
+        return;
+    }
+
+    auto* cookieManager = pool->supplement<WebKit::WebCookieManagerProxy>();
+    cookieManager->deleteCookie(m_owningDataStore->sessionID(), cookie, [pool = WTFMove(pool), completionHandler = WTFMove(completionHandler)]() mutable {
+        completionHandler();
+    });
 }
 
 void HTTPCookieStore::deleteAllCookies(CompletionHandler<void()>&& completionHandler)
 {
-    auto& cookieManager = m_owningDataStore->networkProcess().cookieManager();
-    cookieManager.deleteAllCookies(m_owningDataStore->sessionID());
+    auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+    if (!pool) {
+        if (!m_owningDataStore->sessionID().isEphemeral())
+            deleteCookiesInDefaultUIProcessCookieStore();
+        RunLoop::main().dispatch(WTFMove(completionHandler));
+        return;
+    }
+
+    auto* cookieManager = pool->supplement<WebKit::WebCookieManagerProxy>();
+    cookieManager->deleteAllCookies(m_owningDataStore->sessionID());
     // FIXME: The CompletionHandler should be passed to WebCookieManagerProxy::deleteAllCookies.
     RunLoop::main().dispatch(WTFMove(completionHandler));
 }
 
 void HTTPCookieStore::setHTTPCookieAcceptPolicy(WebCore::HTTPCookieAcceptPolicy policy, CompletionHandler<void()>&& completionHandler)
 {
-    auto& cookieManager = m_owningDataStore->networkProcess().cookieManager();
-    cookieManager.setHTTPCookieAcceptPolicy(m_owningDataStore->sessionID(), policy, WTFMove(completionHandler));
+    auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+    if (!pool) {
+        if (!m_owningDataStore->sessionID().isEphemeral())
+            setHTTPCookieAcceptPolicyInDefaultUIProcessCookieStore(policy);
+        RunLoop::main().dispatch(WTFMove(completionHandler));
+        return;
+    }
+
+    auto* cookieManager = pool->supplement<WebKit::WebCookieManagerProxy>();
+    cookieManager->setHTTPCookieAcceptPolicy(m_owningDataStore->sessionID(), policy, [completionHandler = WTFMove(completionHandler)] () mutable {
+        completionHandler();
+    });
 }
 
 void HTTPCookieStore::flushCookies(CompletionHandler<void()>&& completionHandler)
@@ -157,7 +227,21 @@ void HTTPCookieStore::registerObserver(Observer& observer)
 
     m_cookieManagerProxyObserver = makeUnique<APIWebCookieManagerProxyObserver>(*this);
 
-    m_observedCookieManagerProxy = &m_owningDataStore->networkProcess().cookieManager();
+    auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+
+    if (!pool) {
+        ASSERT(!m_observingUIProcessCookies);
+
+        // Listen for cookie notifications in the UIProcess in the meantime.
+        startObservingChangesToDefaultUIProcessCookieStore([this] () {
+            cookiesDidChange();
+        });
+
+        m_observingUIProcessCookies = true;
+        return;
+    }
+
+    m_observedCookieManagerProxy = pool->supplement<WebKit::WebCookieManagerProxy>();
     m_observedCookieManagerProxy->registerObserver(m_owningDataStore->sessionID(), *m_cookieManagerProxyObserver);
 }
 
@@ -192,10 +276,46 @@ void HTTPCookieStore::cookiesDidChange()
 void HTTPCookieStore::cookieManagerDestroyed()
 {
     m_observedCookieManagerProxy->unregisterObserver(m_owningDataStore->sessionID(), *m_cookieManagerProxyObserver);
-    m_observedCookieManagerProxy = &m_owningDataStore->networkProcess().cookieManager();
+    m_observedCookieManagerProxy = nullptr;
+
+    auto* pool = m_owningDataStore->processPoolForCookieStorageOperations();
+
+    if (!pool)
+        return;
+
+    m_observedCookieManagerProxy = pool->supplement<WebKit::WebCookieManagerProxy>();
     m_observedCookieManagerProxy->registerObserver(m_owningDataStore->sessionID(), *m_cookieManagerProxyObserver);
 }
 
+void HTTPCookieStore::registerForNewProcessPoolNotifications()
+{
+    ASSERT(!m_processPoolCreationListenerIdentifier);
+
+    m_processPoolCreationListenerIdentifier = WebProcessPool::registerProcessPoolCreationListener([this](WebProcessPool& newProcessPool) {
+        if (!m_owningDataStore->isAssociatedProcessPool(newProcessPool))
+            return;
+
+        // Now that an associated process pool exists, we need to flush the UI process cookie store
+        // to make sure any changes are reflected within the new process pool.
+        flushDefaultUIProcessCookieStore();
+        newProcessPool.ensureNetworkProcess();
+
+        if (m_cookieManagerProxyObserver) {
+            m_observedCookieManagerProxy = newProcessPool.supplement<WebKit::WebCookieManagerProxy>();
+            m_observedCookieManagerProxy->registerObserver(m_owningDataStore->sessionID(), *m_cookieManagerProxyObserver);
+        }
+        unregisterForNewProcessPoolNotifications();
+    });
+}
+
+void HTTPCookieStore::unregisterForNewProcessPoolNotifications()
+{
+    if (m_processPoolCreationListenerIdentifier)
+        WebProcessPool::unregisterProcessPoolCreationListener(m_processPoolCreationListenerIdentifier);
+
+    m_processPoolCreationListenerIdentifier = 0;
+}
+
 #if !PLATFORM(COCOA)
 void HTTPCookieStore::flushDefaultUIProcessCookieStore() { }
 Vector<WebCore::Cookie> HTTPCookieStore::getAllDefaultUIProcessCookieStoreCookies() { return { }; }
index a05f414..d620add 100644 (file)
@@ -83,6 +83,9 @@ public:
 private:
     HTTPCookieStore(WebKit::WebsiteDataStore&);
 
+    void registerForNewProcessPoolNotifications();
+    void unregisterForNewProcessPoolNotifications();
+
     void flushDefaultUIProcessCookieStore();
     static Vector<WebCore::Cookie> getAllDefaultUIProcessCookieStoreCookies();
     static void setCookieInDefaultUIProcessCookieStore(const WebCore::Cookie&);
index 37baa68..58c5453 100644 (file)
@@ -411,6 +411,11 @@ void WKContextPreconnectToServer(WKContextRef, WKURLRef)
 {
 }
 
+WKCookieManagerRef WKContextGetCookieManager(WKContextRef contextRef)
+{
+    return WebKit::toAPI(WebKit::toImpl(contextRef)->supplement<WebKit::WebCookieManagerProxy>());
+}
+
 WKWebsiteDataStoreRef WKContextGetWebsiteDataStore(WKContextRef)
 {
     return WKWebsiteDataStoreGetDefaultDataStore();
@@ -522,6 +527,13 @@ void WKContextSetJavaScriptGarbageCollectorTimerEnabled(WKContextRef contextRef,
     WebKit::toImpl(contextRef)->setJavaScriptGarbageCollectorTimerEnabled(enable);
 }
 
+void WKContextSetAllowsAnySSLCertificateForServiceWorkerTesting(WKContextRef context, bool allows)
+{
+#if ENABLE(SERVICE_WORKER)
+    WebKit::toImpl(context)->setAllowsAnySSLCertificateForServiceWorker(allows);
+#endif
+}
+
 WKDictionaryRef WKContextCopyPlugInAutoStartOriginHashes(WKContextRef contextRef)
 {
     return WebKit::toAPI(&WebKit::toImpl(contextRef)->plugInAutoStartOriginHashes().leakRef());
@@ -563,11 +575,21 @@ void WKContextSetFontAllowList(WKContextRef contextRef, WKArrayRef arrayRef)
     WebKit::toImpl(contextRef)->setFontAllowList(WebKit::toImpl(arrayRef));
 }
 
+void WKContextTerminateNetworkProcess(WKContextRef context)
+{
+    WebKit::toImpl(context)->terminateNetworkProcess();
+}
+
 void WKContextTerminateServiceWorkers(WKContextRef context)
 {
     WebKit::toImpl(context)->terminateServiceWorkers();
 }
 
+ProcessID WKContextGetNetworkProcessIdentifier(WKContextRef contextRef)
+{
+    return WebKit::toImpl(contextRef)->networkProcessIdentifier();
+}
+
 void WKContextAddSupportedPlugin(WKContextRef contextRef, WKStringRef domainRef, WKStringRef nameRef, WKArrayRef mimeTypesRef, WKArrayRef extensionsRef)
 {
 #if ENABLE(NETSCAPE_PLUGIN_API)
@@ -597,11 +619,12 @@ void WKContextClearCurrentModifierStateForTesting(WKContextRef contextRef)
     WebKit::toImpl(contextRef)->clearCurrentModifierStateForTesting();
 }
 
-void WKContextSetUseSeparateServiceWorkerProcess(WKContextRef, bool useSeparateServiceWorkerProcess)
+void WKContextSetUseSeparateServiceWorkerProcess(WKContextRef contextRef, bool useSeparateServiceWorkerProcess)
 {
-    WebKit::WebProcessPool::setUseSeparateServiceWorkerProcess(useSeparateServiceWorkerProcess);
+    WebKit::toImpl(contextRef)->setUseSeparateServiceWorkerProcess(useSeparateServiceWorkerProcess);
 }
 
-void WKContextSetPrimaryWebsiteDataStore(WKContextRef, WKWebsiteDataStoreRef)
+void WKContextSetPrimaryWebsiteDataStore(WKContextRef contextRef, WKWebsiteDataStoreRef websiteDataStore)
 {
+    WebKit::toImpl(contextRef)->setPrimaryDataStore(*WebKit::toImpl(websiteDataStore));
 }
index 2ab6ef8..1d8fab8 100644 (file)
@@ -168,6 +168,7 @@ WK_EXPORT void WKContextStopMemorySampler(WKContextRef context);
 WK_EXPORT WKWebsiteDataStoreRef WKContextGetWebsiteDataStore(WKContextRef context) WK_C_API_DEPRECATED_WITH_REPLACEMENT(WKWebsiteDataStoreGetDefaultDataStore);
 
 WK_EXPORT WKApplicationCacheManagerRef WKContextGetApplicationCacheManager(WKContextRef context) WK_C_API_DEPRECATED_WITH_REPLACEMENT(WKWebsiteDataStoreGetDefaultDataStore);
+WK_EXPORT WKCookieManagerRef WKContextGetCookieManager(WKContextRef context) WK_C_API_DEPRECATED;
 WK_EXPORT WKGeolocationManagerRef WKContextGetGeolocationManager(WKContextRef context);
 WK_EXPORT WKIconDatabaseRef WKContextGetIconDatabase(WKContextRef context);
 WK_EXPORT WKKeyValueStorageManagerRef WKContextGetKeyValueStorageManager(WKContextRef context) WK_C_API_DEPRECATED_WITH_REPLACEMENT(WKWebsiteDataStoreGetDefaultDataStore);
index 48a29c4..a025011 100644 (file)
@@ -83,8 +83,11 @@ WK_EXPORT void WKContextWarmInitialProcess(WKContextRef context);
 // At some point it should be removed.
 WK_EXPORT void WKContextSetUsesNetworkProcess(WKContextRef, bool);
 
+WK_EXPORT void WKContextTerminateNetworkProcess(WKContextRef);
 WK_EXPORT void WKContextTerminateServiceWorkers(WKContextRef);
 
+WK_EXPORT void WKContextSetAllowsAnySSLCertificateForServiceWorkerTesting(WKContextRef, bool);
+
 typedef void (*WKContextInvalidMessageFunction)(WKStringRef messageName);
 WK_EXPORT void WKContextSetInvalidMessageFunction(WKContextInvalidMessageFunction invalidMessageFunction);
     
@@ -94,6 +97,8 @@ WK_EXPORT void WKContextSetFontAllowList(WKContextRef, WKArrayRef);
 
 WK_EXPORT void WKContextPreconnectToServer(WKContextRef context, WKURLRef serverURL) WK_C_API_DEPRECATED;
 
+WK_EXPORT WKProcessID WKContextGetNetworkProcessIdentifier(WKContextRef context);
+
 WK_EXPORT void WKContextAddSupportedPlugin(WKContextRef context, WKStringRef domain, WKStringRef name, WKArrayRef mimeTypes, WKArrayRef extensions);
 WK_EXPORT void WKContextClearSupportedPlugins(WKContextRef context);
 
index b447342..648f300 100644 (file)
@@ -398,11 +398,6 @@ uint64_t WKPageGetRenderTreeSize(WKPageRef page)
     return toImpl(page)->renderTreeSize();
 }
 
-WKWebsiteDataStoreRef WKPageGetWebsiteDataStore(WKPageRef page)
-{
-    return toAPI(&toImpl(page)->websiteDataStore());
-}
-
 WKInspectorRef WKPageGetInspector(WKPageRef pageRef)
 {
     return toAPI(toImpl(pageRef)->inspector());
index c51b816..670b5e9 100644 (file)
@@ -118,8 +118,6 @@ WK_EXPORT double WKPageGetEstimatedProgress(WKPageRef page);
 
 WK_EXPORT uint64_t WKPageGetRenderTreeSize(WKPageRef page);
 
-WK_EXPORT WKWebsiteDataStoreRef WKPageGetWebsiteDataStore(WKPageRef page);
-
 WK_EXPORT WKInspectorRef WKPageGetInspector(WKPageRef page);
 
 WK_EXPORT WKStringRef WKPageCopyUserAgent(WKPageRef page);
index 686114a..9dda591 100644 (file)
@@ -28,7 +28,6 @@
 
 #include "APIArray.h"
 #include "APIHTTPCookieStore.h"
-#include "NetworkProcessProxy.h"
 #include "ShouldGrandfatherStatistics.h"
 #include "WKAPICast.h"
 #include "WKDictionary.h"
@@ -70,16 +69,6 @@ WKWebsiteDataStoreRef WKWebsiteDataStoreCreateWithConfiguration(WKWebsiteDataSto
     return WebKit::toAPI(&WebKit::WebsiteDataStore::create(*WebKit::toImpl(configuration), sessionID).leakRef());
 }
 
-void WKWebsiteDataStoreTerminateNetworkProcess(WKWebsiteDataStoreRef dataStore)
-{
-    WebKit::toImpl(dataStore)->terminateNetworkProcess();
-}
-
-WKProcessID WKWebsiteDataStoreGetNetworkProcessIdentifier(WKWebsiteDataStoreRef dataStore)
-{
-    return WebKit::toImpl(dataStore)->networkProcess().processIdentifier();
-}
-
 void WKWebsiteDataStoreRemoveITPDataForDomain(WKWebsiteDataStoreRef dataStoreRef, WKStringRef host, void* context, WKWebsiteDataStoreRemoveITPDataForDomainFunction callback)
 {
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
index ab26774..e77d09c 100644 (file)
 #include <WebKit/WKBase.h>
 #include <WebKit/WKDeprecated.h>
 
-#if defined(WIN32) || defined(_WIN32)
-typedef int WKProcessID;
-#else
-#include <unistd.h>
-typedef pid_t WKProcessID;
-#endif
-
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -57,11 +50,6 @@ WK_EXPORT void WKWebsiteDataStoreSetAllowsAnySSLCertificateForWebSocketTesting(W
 
 WK_EXPORT void WKWebsiteDataStoreClearCachedCredentials(WKWebsiteDataStoreRef dataStoreRef);
 
-WK_EXPORT void WKWebsiteDataStoreClearCachedCredentials(WKWebsiteDataStoreRef dataStore);
-WK_EXPORT void WKWebsiteDataStoreTerminateNetworkProcess(WKWebsiteDataStoreRef dataStore);
-
-WK_EXPORT WKProcessID WKWebsiteDataStoreGetNetworkProcessIdentifier(WKWebsiteDataStoreRef dataStore);
-
 WK_EXPORT bool WKWebsiteDataStoreGetResourceLoadStatisticsEnabled(WKWebsiteDataStoreRef dataStoreRef);
 WK_EXPORT void WKWebsiteDataStoreSetResourceLoadStatisticsEnabled(WKWebsiteDataStoreRef dataStoreRef, bool enable);
 typedef void (*WKWebsiteDataStoreStatisticsEphemeralFunction)(bool isEphemeral, void* functionContext);
index 1f56fbf..ff30949 100644 (file)
@@ -406,6 +406,28 @@ static NSDictionary *policiesHashMapToDictionary(const HashMap<String, HashMap<S
     _processPool->clearSupportedPlugins();
 }
 
+- (void)_terminateNetworkProcess
+{
+    _processPool->terminateNetworkProcess();
+}
+
+- (void)_sendNetworkProcessWillSuspendImminently
+{
+    _processPool->sendNetworkProcessWillSuspendImminentlyForTesting();
+}
+
+- (void)_sendNetworkProcessPrepareToSuspend:(void(^)(void))completionHandler
+{
+    _processPool->sendNetworkProcessPrepareToSuspendForTesting([completionHandler = makeBlockPtr(completionHandler)] {
+        completionHandler();
+    });
+}
+
+- (void)_sendNetworkProcessDidResume
+{
+    _processPool->sendNetworkProcessDidResume();
+}
+
 - (void)_terminateServiceWorkers
 {
     _processPool->terminateServiceWorkers();
@@ -413,7 +435,12 @@ static NSDictionary *policiesHashMapToDictionary(const HashMap<String, HashMap<S
 
 - (void)_setUseSeparateServiceWorkerProcess:(BOOL)useSeparateServiceWorkerProcess
 {
-    WebKit::WebProcessPool::setUseSeparateServiceWorkerProcess(useSeparateServiceWorkerProcess);
+    _processPool->setUseSeparateServiceWorkerProcess(useSeparateServiceWorkerProcess);
+}
+
+- (pid_t)_networkProcessIdentifier
+{
+    return _processPool->networkProcessIdentifier();
 }
 
 - (pid_t)_prewarmedProcessIdentifier
@@ -440,6 +467,11 @@ static NSDictionary *policiesHashMapToDictionary(const HashMap<String, HashMap<S
     _processPool->setShouldMakeNextWebProcessLaunchFailForTesting(true);
 }
 
+- (void)_makeNextNetworkProcessLaunchFailForTesting
+{
+    _processPool->setShouldMakeNextNetworkProcessLaunchFailForTesting(true);
+}
+
 - (BOOL)_hasPrewarmedWebProcess
 {
     for (auto& process : _processPool->processes()) {
@@ -528,6 +560,18 @@ static NSDictionary *policiesHashMapToDictionary(const HashMap<String, HashMap<S
     _processPool->setCookieStoragePartitioningEnabled(enabled);
 }
 
+- (void)_synthesizeAppIsBackground:(BOOL)background
+{
+    _processPool->synthesizeAppIsBackground(background);
+}
+
+- (void)_setAllowsAnySSLCertificateForServiceWorker:(BOOL)allows
+{
+#if ENABLE(SERVICE_WORKER)
+    _processPool->setAllowsAnySSLCertificateForServiceWorker(allows);
+#endif
+}
+
 #if PLATFORM(IOS_FAMILY)
 - (id <_WKGeolocationCoreLocationProvider>)_coreLocationProvider
 {
@@ -560,6 +604,11 @@ static NSDictionary *policiesHashMapToDictionary(const HashMap<String, HashMap<S
     });
 }
 
+- (BOOL)_networkProcessHasEntitlementForTesting:(NSString *)entitlement
+{
+    return _processPool->networkProcessHasEntitlementForTesting(entitlement);
+}
+
 - (void)_clearPermanentCredentialsForProtectionSpace:(NSURLProtectionSpace *)protectionSpace
 {
     _processPool->clearPermanentCredentialsForProtectionSpace(WebCore::ProtectionSpace(protectionSpace));
index 3b93140..6769015 100644 (file)
 - (_WKDownload *)_resumeDownloadFromData:(NSData *)resumeData websiteDataStore:(WKWebsiteDataStore *)dataStore  path:(NSString *)path originatingWebView:(WKWebView *)webView WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
 
 // Test only. Should be called only while no web content processes are running.
+- (void)_terminateNetworkProcess WK_API_AVAILABLE(macos(10.15), ios(13.0));
+- (void)_sendNetworkProcessPrepareToSuspend:(void(^)(void))completionHandler WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
+- (void)_sendNetworkProcessWillSuspendImminently WK_API_AVAILABLE(macos(10.15), ios(13.0));
+- (void)_sendNetworkProcessDidResume WK_API_AVAILABLE(macos(10.15), ios(13.0));
 - (void)_terminateServiceWorkers WK_API_AVAILABLE(macos(10.14), ios(12.0));
 
 // Test only.
+- (pid_t)_networkProcessIdentifier WK_API_AVAILABLE(macos(10.13), ios(11.0));
 - (pid_t)_prewarmedProcessIdentifier WK_API_AVAILABLE(macos(10.15), ios(13.0));
 
 // Test only.
 - (size_t)_serviceWorkerProcessCount WK_API_AVAILABLE(macos(10.14), ios(12.0));
 - (void)_syncNetworkProcessCookies WK_API_DEPRECATED_WITH_REPLACEMENT("WKHTTPCookieStore._flushCookiesToDiskWithCompletionHandler:", macos(10.13, WK_MAC_TBA), ios(11.0, WK_IOS_TBA));
 - (void)_makeNextWebProcessLaunchFailForTesting WK_API_AVAILABLE(macos(10.14), ios(12.0));
+- (void)_makeNextNetworkProcessLaunchFailForTesting WK_API_AVAILABLE(macos(10.14), ios(12.0));
 - (NSUInteger)_maximumSuspendedPageCount WK_API_AVAILABLE(macos(10.14.4), ios(12.2));
 - (NSUInteger)_processCacheCapacity WK_API_AVAILABLE(macos(10.14.4), ios(12.2));
 - (NSUInteger)_processCacheSize WK_API_AVAILABLE(macos(10.15), ios(13.0));
 - (void)_preconnectToServer:(NSURL *)serverURL WK_API_DEPRECATED_WITH_REPLACEMENT("WKWebView._preconnectToServer", macos(10.13.4, WK_MAC_TBA), ios(11.3, WK_IOS_TBA));
 
 // Test only.
+- (void)_setAllowsAnySSLCertificateForServiceWorker:(BOOL)allows WK_API_AVAILABLE(macos(10.13.4), ios(11.3));
 - (void)_getActivePagesOriginsInWebProcessForTesting:(pid_t)pid completionHandler:(void(^)(NSArray<NSString *> *))completionHandler WK_API_AVAILABLE(macos(10.14.4), ios(12.2));
+- (BOOL)_networkProcessHasEntitlementForTesting:(NSString *)entitlement WK_API_AVAILABLE(macos(10.14.4), ios(12.2));
 - (void)_clearPermanentCredentialsForProtectionSpace:(NSURLProtectionSpace *)protectionSpace WK_API_AVAILABLE(macos(10.15), ios(13.0));
 
 @property (nonatomic, getter=_isCookieStoragePartitioningEnabled, setter=_setCookieStoragePartitioningEnabled:) BOOL _cookieStoragePartitioningEnabled WK_API_DEPRECATED("Partitioned cookies are no longer supported", macos(10.12.3, 10.14.4), ios(10.3, 12.2));
+- (void)_synthesizeAppIsBackground:(BOOL)background WK_API_AVAILABLE(macos(10.15), ios(13.0));
 
 // Test only.
 - (void)_seedResourceLoadStatisticsForTestingWithFirstParty:(NSURL *)firstPartyURL thirdParty:(NSURL *)thirdPartyURL shouldScheduleNotification:(BOOL)shouldScheduleNotification completionHandler:(void(^)(void))completionHandler  WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
index 80d330f..298d9ce 100644 (file)
@@ -617,11 +617,6 @@ static Vector<WebKit::WebsiteDataRecord> toWebsiteDataRecords(NSArray *dataRecor
     });
 }
 
-- (BOOL)_networkProcessHasEntitlementForTesting:(NSString *)entitlement
-{
-    return _websiteDataStore->networkProcessHasEntitlementForTesting(entitlement);
-}
-
 - (id <_WKWebsiteDataStoreDelegate>)_delegate
 {
     return _delegate.get().get();
@@ -673,42 +668,4 @@ static Vector<WebKit::WebsiteDataRecord> toWebsiteDataRecords(NSArray *dataRecor
 #endif
 }
 
-- (void)_terminateNetworkProcess
-{
-    _websiteDataStore->terminateNetworkProcess();
-}
-
-- (void)_sendNetworkProcessPrepareToSuspend:(void(^)(void))completionHandler
-{
-    _websiteDataStore->sendNetworkProcessPrepareToSuspendForTesting([completionHandler = makeBlockPtr(completionHandler)] {
-        completionHandler();
-    });
-}
-
-- (void)_sendNetworkProcessWillSuspendImminently
-{
-    _websiteDataStore->sendNetworkProcessWillSuspendImminentlyForTesting();
-
-}
-
-- (void)_sendNetworkProcessDidResume
-{
-    _websiteDataStore->sendNetworkProcessDidResume();
-}
-
-- (void)_synthesizeAppIsBackground:(BOOL)background
-{
-    _websiteDataStore->networkProcess().synthesizeAppIsBackground(background);
-}
-
-- (pid_t)_networkProcessIdentifier
-{
-    return _websiteDataStore->networkProcess().processIdentifier();
-}
-
-+ (void)_makeNextNetworkProcessLaunchFailForTesting
-{
-    WebKit::WebsiteDataStore::makeNextNetworkProcessLaunchFailForTesting();
-}
-
 @end
index a856be6..9932010 100644 (file)
@@ -85,19 +85,9 @@ typedef NS_OPTIONS(NSUInteger, _WKWebsiteDataStoreFetchOptions) {
 
 - (void)_renameOrigin:(NSURL *)oldName to:(NSURL *)newName forDataOfTypes:(NSSet<NSString *> *)dataTypes completionHandler:(void (^)(void))completionHandler;
 
-- (BOOL)_networkProcessHasEntitlementForTesting:(NSString *)entitlement WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-
 @property (nullable, nonatomic, weak) id <_WKWebsiteDataStoreDelegate> _delegate WK_API_AVAILABLE(macos(10.15), ios(13.0));
 @property (nonatomic, readonly, copy) _WKWebsiteDataStoreConfiguration *_configuration;
 
-- (void)_terminateNetworkProcess WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-- (void)_sendNetworkProcessPrepareToSuspend:(void(^)(void))completionHandler WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-- (void)_sendNetworkProcessWillSuspendImminently WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-- (void)_sendNetworkProcessDidResume WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-- (void)_synthesizeAppIsBackground:(BOOL)background WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-- (pid_t)_networkProcessIdentifier WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-+ (void)_makeNextNetworkProcessLaunchFailForTesting WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
-
 @end
 
 NS_ASSUME_NONNULL_END
index d10db29..1ee73eb 100644 (file)
@@ -21,7 +21,6 @@
 #include "config.h"
 #include "WebKitCookieManager.h"
 
-#include "NetworkProcessProxy.h"
 #include "SoupCookiePersistentStorageType.h"
 #include "WebCookieManagerProxy.h"
 #include "WebKitCookieManagerPrivate.h"
@@ -57,12 +56,6 @@ enum {
 };
 
 struct _WebKitCookieManagerPrivate {
-    WebCookieManagerProxy& cookieManager() const
-    {
-        ASSERT(dataManager);
-        return webkitWebsiteDataManagerGetDataStore(dataManager).networkProcess().cookieManager();
-    }
-
     PAL::SessionID sessionID() const
     {
         ASSERT(dataManager);
@@ -71,7 +64,8 @@ struct _WebKitCookieManagerPrivate {
 
     ~_WebKitCookieManagerPrivate()
     {
-        cookieManager().setCookieObserverCallback(sessionID(), nullptr);
+        for (auto* processPool : webkitWebsiteDataManagerGetProcessPools(dataManager))
+            processPool->supplement<WebCookieManagerProxy>()->setCookieObserverCallback(sessionID(), nullptr);
     }
 
     WebKitWebsiteDataManager* dataManager;
@@ -145,9 +139,11 @@ WebKitCookieManager* webkitCookieManagerCreate(WebKitWebsiteDataManager* dataMan
 {
     WebKitCookieManager* manager = WEBKIT_COOKIE_MANAGER(g_object_new(WEBKIT_TYPE_COOKIE_MANAGER, nullptr));
     manager->priv->dataManager = dataManager;
-    manager->priv->cookieManager().setCookieObserverCallback(manager->priv->sessionID(), [manager] {
-        g_signal_emit(manager, signals[CHANGED], 0);
-    });
+    for (auto* processPool : webkitWebsiteDataManagerGetProcessPools(manager->priv->dataManager)) {
+        processPool->supplement<WebCookieManagerProxy>()->setCookieObserverCallback(manager->priv->sessionID(), [manager] {
+            g_signal_emit(manager, signals[CHANGED], 0);
+        });
+    }
     return manager;
 }
 
@@ -177,7 +173,8 @@ void webkit_cookie_manager_set_persistent_storage(WebKitCookieManager* manager,
     if (sessionID.isEphemeral())
         return;
 
-    manager->priv->cookieManager().setCookiePersistentStorage(sessionID, String::fromUTF8(filename), toSoupCookiePersistentStorageType(storage));
+    for (auto* processPool : webkitWebsiteDataManagerGetProcessPools(manager->priv->dataManager))
+        processPool->supplement<WebCookieManagerProxy>()->setCookiePersistentStorage(sessionID, String::fromUTF8(filename), toSoupCookiePersistentStorageType(storage));
 }
 
 /**
@@ -195,7 +192,8 @@ void webkit_cookie_manager_set_accept_policy(WebKitCookieManager* manager, WebKi
 {
     g_return_if_fail(WEBKIT_IS_COOKIE_MANAGER(manager));
 
-    manager->priv->cookieManager().setHTTPCookieAcceptPolicy(manager->priv->sessionID(), toHTTPCookieAcceptPolicy(policy), []() { });
+    for (auto* processPool : webkitWebsiteDataManagerGetProcessPools(manager->priv->dataManager))
+        processPool->supplement<WebCookieManagerProxy>()->setHTTPCookieAcceptPolicy(manager->priv->sessionID(), toHTTPCookieAcceptPolicy(policy), []() { });
 }
 
 /**
@@ -219,7 +217,14 @@ void webkit_cookie_manager_get_accept_policy(WebKitCookieManager* manager, GCanc
 
     GRefPtr<GTask> task = adoptGRef(g_task_new(manager, cancellable, callback, userData));
 
-    manager->priv->cookieManager().getHTTPCookieAcceptPolicy(manager->priv->sessionID(), [task = WTFMove(task)](WebCore::HTTPCookieAcceptPolicy policy) {
+    // The policy is the same in all process pools having the same session ID, so just ask any.
+    const auto& processPools = webkitWebsiteDataManagerGetProcessPools(manager->priv->dataManager);
+    if (processPools.isEmpty()) {
+        g_task_return_int(task.get(), WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY);
+        return;
+    }
+
+    processPools[0]->supplement<WebCookieManagerProxy>()->getHTTPCookieAcceptPolicy(manager->priv->sessionID(), [task = WTFMove(task)](WebCore::HTTPCookieAcceptPolicy policy) {
         g_task_return_int(task.get(), toWebKitCookieAcceptPolicy(policy));
     });
 }
@@ -264,7 +269,11 @@ void webkit_cookie_manager_add_cookie(WebKitCookieManager* manager, SoupCookie*
     g_return_if_fail(cookie);
 
     GRefPtr<GTask> task = adoptGRef(g_task_new(manager, cancellable, callback, userData));
-    manager->priv->cookieManager().setCookies(manager->priv->sessionID(), { WebCore::Cookie(cookie) }, [task = WTFMove(task)]() {
+
+    // Cookies are read/written from/to the same SQLite database on disk regardless
+    // of the process we access them from, so just use the first process pool.
+    const auto& processPools = webkitWebsiteDataManagerGetProcessPools(manager->priv->dataManager);
+    processPools[0]->supplement<WebCookieManagerProxy>()->setCookies(manager->priv->sessionID(), { WebCore::Cookie(cookie) }, [task = WTFMove(task)]() {
         g_task_return_boolean(task.get(), TRUE);
     });
 }
@@ -311,7 +320,11 @@ void webkit_cookie_manager_get_cookies(WebKitCookieManager* manager, const gchar
     g_return_if_fail(uri);
 
     GRefPtr<GTask> task = adoptGRef(g_task_new(manager, cancellable, callback, userData));
-    manager->priv->cookieManager().getCookies(manager->priv->sessionID(), URL(URL(), String::fromUTF8(uri)), [task = WTFMove(task)](const Vector<WebCore::Cookie>& cookies) {
+
+    // Cookies are read/written from/to the same SQLite database on disk regardless
+    // of the process we access them from, so just use the first process pool.
+    const auto& processPools = webkitWebsiteDataManagerGetProcessPools(manager->priv->dataManager);
+    processPools[0]->supplement<WebCookieManagerProxy>()->getCookies(manager->priv->sessionID(), URL(URL(), String::fromUTF8(uri)), [task = WTFMove(task)](const Vector<WebCore::Cookie>& cookies) {
         GList* cookiesList = nullptr;
         for (auto& cookie : cookies)
             cookiesList = g_list_prepend(cookiesList, cookie.toSoupCookie());
@@ -365,7 +378,11 @@ void webkit_cookie_manager_delete_cookie(WebKitCookieManager* manager, SoupCooki
     g_return_if_fail(cookie);
 
     GRefPtr<GTask> task = adoptGRef(g_task_new(manager, cancellable, callback, userData));
-    manager->priv->cookieManager().deleteCookie(manager->priv->sessionID(), WebCore::Cookie(cookie), [task = WTFMove(task)]() {
+
+    // Cookies are read/written from/to the same SQLite database on disk regardless
+    // of the process we access them from, so just use the first process pool.
+    const auto& processPools = webkitWebsiteDataManagerGetProcessPools(manager->priv->dataManager);
+    processPools[0]->supplement<WebCookieManagerProxy>()->deleteCookie(manager->priv->sessionID(), WebCore::Cookie(cookie), [task = WTFMove(task)]() {
         g_task_return_boolean(task.get(), TRUE);
     });
 }
index 36d0008..71667cf 100644 (file)
@@ -402,6 +402,7 @@ static void webkitWebContextConstructed(GObject* object)
         priv->websiteDataManager = adoptGRef(webkit_website_data_manager_new("local-storage-directory", priv->localStorageDirectory.data(), nullptr));
 
     priv->processPool = WebProcessPool::create(configuration);
+    priv->processPool->setPrimaryDataStore(webkitWebsiteDataManagerGetDataStore(priv->websiteDataManager.get()));
     priv->processPool->setUserMessageHandler([webContext](UserMessage&& message, CompletionHandler<void(UserMessage&&)>&& completionHandler) {
         // Sink the floating ref.
         GRefPtr<WebKitUserMessage> userMessage = webkitUserMessageCreate(WTFMove(message), WTFMove(completionHandler));
@@ -409,6 +410,8 @@ static void webkitWebContextConstructed(GObject* object)
         g_signal_emit(webContext, signals[USER_MESSAGE_RECEIVED], 0, userMessage.get(), &returnValue);
     });
 
+    webkitWebsiteDataManagerAddProcessPool(priv->websiteDataManager.get(), *priv->processPool);
+
     priv->processModel = WEBKIT_PROCESS_MODEL_MULTIPLE_SECONDARY_PROCESSES;
 
 #if ENABLE(MEMORY_SAMPLER)
@@ -436,6 +439,11 @@ static void webkitWebContextDispose(GObject* object)
         priv->processPool->setDownloadClient(makeUniqueRef<API::DownloadClient>());
     }
 
+    if (priv->websiteDataManager) {
+        webkitWebsiteDataManagerRemoveProcessPool(priv->websiteDataManager.get(), *priv->processPool);
+        priv->websiteDataManager = nullptr;
+    }
+
     if (priv->faviconDatabase) {
         webkitFaviconDatabaseClose(priv->faviconDatabase.get());
         priv->faviconDatabase = nullptr;
@@ -1573,8 +1581,8 @@ void webkit_web_context_prefetch_dns(WebKitWebContext* context, const char* host
     g_return_if_fail(WEBKIT_IS_WEB_CONTEXT(context));
     g_return_if_fail(hostname);
 
-    auto& websiteDataStore = webkitWebsiteDataManagerGetDataStore(context->priv->websiteDataManager.get());
-    websiteDataStore.networkProcess().send(Messages::NetworkProcess::PrefetchDNS(String::fromUTF8(hostname)), 0);
+    if (context->priv->dnsPrefetchedHosts.add(hostname).isNewEntry)
+        context->priv->processPool->sendToNetworkingProcess(Messages::NetworkProcess::PrefetchDNS(String::fromUTF8(hostname)));
     context->priv->dnsPrefetchHystereris.impulse();
 }
 
index d8b3f3c..4135c26 100644 (file)
@@ -759,6 +759,7 @@ static void webkitWebViewConstructed(GObject* object)
         webkit_website_data_manager_set_tls_errors_policy(priv->websiteDataManager.get(), webkit_website_data_manager_get_tls_errors_policy(contextDataManager));
         auto proxySettings = webkitWebsiteDataManagerGetDataStore(contextDataManager).networkProxySettings();
         webkitWebsiteDataManagerGetDataStore(priv->websiteDataManager.get()).setNetworkProxySettings(WTFMove(proxySettings));
+        webkitWebsiteDataManagerAddProcessPool(priv->websiteDataManager.get(), webkitWebContextGetProcessPool(priv->context.get()));
     }
 
     if (!priv->websitePolicies)
@@ -944,6 +945,11 @@ static void webkitWebViewDispose(GObject* object)
         webkitWebContextWebViewDestroyed(webView->priv->context.get(), webView);
     }
 
+    if (webView->priv->websiteDataManager) {
+        webkitWebsiteDataManagerRemoveProcessPool(webView->priv->websiteDataManager.get(), webkitWebContextGetProcessPool(webView->priv->context.get()));
+        webView->priv->websiteDataManager = nullptr;
+    }
+
     if (webView->priv->currentScriptDialog) {
         webkit_script_dialog_close(webView->priv->currentScriptDialog);
         ASSERT(!webView->priv->currentScriptDialog);
index 4c4ef5d..da9a3aa 100644 (file)
@@ -95,6 +95,11 @@ enum {
 };
 
 struct _WebKitWebsiteDataManagerPrivate {
+    ~_WebKitWebsiteDataManagerPrivate()
+    {
+        ASSERT(processPools.isEmpty());
+    }
+
     RefPtr<WebKit::WebsiteDataStore> websiteDataStore;
     GUniquePtr<char> baseDataDirectory;
     GUniquePtr<char> baseCacheDirectory;
@@ -110,6 +115,7 @@ struct _WebKitWebsiteDataManagerPrivate {
     WebKitTLSErrorsPolicy tlsErrorsPolicy;
 
     GRefPtr<WebKitCookieManager> cookieManager;
+    Vector<WebProcessPool*> processPools;
 };
 
 WEBKIT_DEFINE_TYPE(WebKitWebsiteDataManager, webkit_website_data_manager, G_TYPE_OBJECT)
@@ -488,13 +494,30 @@ WebKit::WebsiteDataStore& webkitWebsiteDataManagerGetDataStore(WebKitWebsiteData
             configuration->setServiceWorkerRegistrationDirectory(FileSystem::stringFromFileSystemRepresentation(priv->swRegistrationsDirectory.get()));
         if (priv->domCacheDirectory)
             configuration->setCacheStorageDirectory(FileSystem::stringFromFileSystemRepresentation(priv->domCacheDirectory.get()));
-        priv->websiteDataStore = WebKit::WebsiteDataStore::create(WTFMove(configuration), PAL::SessionID::generatePersistentSessionID());
+        priv->websiteDataStore = WebKit::WebsiteDataStore::create(WTFMove(configuration), PAL::SessionID::defaultSessionID());
         priv->websiteDataStore->setIgnoreTLSErrors(priv->tlsErrorsPolicy == WEBKIT_TLS_ERRORS_POLICY_IGNORE);
     }
 
     return *priv->websiteDataStore;
 }
 
+void webkitWebsiteDataManagerAddProcessPool(WebKitWebsiteDataManager* manager, WebProcessPool& processPool)
+{
+    ASSERT(!manager->priv->processPools.contains(&processPool));
+    manager->priv->processPools.append(&processPool);
+}
+
+void webkitWebsiteDataManagerRemoveProcessPool(WebKitWebsiteDataManager* manager, WebProcessPool& processPool)
+{
+    ASSERT(manager->priv->processPools.contains(&processPool));
+    manager->priv->processPools.removeFirst(&processPool);
+}
+
+const Vector<WebProcessPool*>& webkitWebsiteDataManagerGetProcessPools(WebKitWebsiteDataManager* manager)
+{
+    return manager->priv->processPools;
+}
+
 /**
  * webkit_website_data_manager_new:
  * @first_option_name: name of the first option to set
index fc9e822..2a589e2 100644 (file)
 
 #pragma once
 
+#include "WebProcessPool.h"
 #include "WebsiteDataStore.h"
 
 WebKit::WebsiteDataStore& webkitWebsiteDataManagerGetDataStore(WebKitWebsiteDataManager*);
+void webkitWebsiteDataManagerAddProcessPool(WebKitWebsiteDataManager*, WebKit::WebProcessPool&);
+void webkitWebsiteDataManagerRemoveProcessPool(WebKitWebsiteDataManager*, WebKit::WebProcessPool&);
+const Vector<WebKit::WebProcessPool*>& webkitWebsiteDataManagerGetProcessPools(WebKitWebsiteDataManager*);
+
index 2cd88c5..ab64a45 100644 (file)
@@ -1392,8 +1392,8 @@ void WebAutomationSession::addSingleCookie(const Inspector::Protocol::Automation
 
     cookie.httpOnly = *httpOnly;
 
-    WebCookieManagerProxy& cookieManager = page->websiteDataStore().networkProcess().cookieManager();
-    cookieManager.setCookies(page->websiteDataStore().sessionID(), { cookie }, [callback]() {
+    WebCookieManagerProxy* cookieManager = m_processPool->supplement<WebCookieManagerProxy>();
+    cookieManager->setCookies(page->websiteDataStore().sessionID(), { cookie }, [callback]() {
         callback->sendSuccess();
     });
 }
@@ -1409,8 +1409,8 @@ Inspector::Protocol::ErrorStringOr<void> WebAutomationSession::deleteAllCookies(
 
     String host = activeURL.host().toString();
 
-    WebCookieManagerProxy& cookieManager = page->websiteDataStore().networkProcess().cookieManager();
-    cookieManager.deleteCookiesForHostnames(page->websiteDataStore().sessionID(), { host, domainByAddingDotPrefixIfNeeded(host) });
+    WebCookieManagerProxy* cookieManager = m_processPool->supplement<WebCookieManagerProxy>();
+    cookieManager->deleteCookiesForHostnames(page->websiteDataStore().sessionID(), { host, domainByAddingDotPrefixIfNeeded(host) });
 
     return { };
 }
index 4f398b5..41c0a0f 100644 (file)
@@ -48,7 +48,7 @@ public:
     virtual ~AuxiliaryProcessProxy();
 
     void connect();
-    virtual void terminate();
+    void terminate();
 
     virtual ProcessThrottler& throttler() = 0;
 
index 4c845a0..dbe44f9 100644 (file)
@@ -41,11 +41,11 @@ namespace WebKit {
 class LegacyCustomProtocolManagerProxy;
 
 class LegacyCustomProtocolManagerClient final : public API::CustomProtocolManagerClient {
-public:
+private:
     void startLoading(LegacyCustomProtocolManagerProxy&, LegacyCustomProtocolID, const WebCore::ResourceRequest&) final;
     void stopLoading(LegacyCustomProtocolManagerProxy&, LegacyCustomProtocolID) final;
     void invalidate(LegacyCustomProtocolManagerProxy&) final;
-private:
+
     HashMap<LegacyCustomProtocolID, RetainPtr<WKCustomProtocolLoader>> m_loaderMap;
 };
 
index 3313bde..92ad1c8 100644 (file)
@@ -134,9 +134,8 @@ static void registerUserDefaultsIfNeeded()
 
 void WebProcessPool::updateProcessSuppressionState()
 {
-    WebsiteDataStore::forEachWebsiteDataStore([enabled = processSuppressionEnabled()] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().setProcessSuppressionEnabled(enabled);
-    });
+    if (m_networkProcess)
+        m_networkProcess->setProcessSuppressionEnabled(processSuppressionEnabled());
 
 #if ENABLE(NETSCAPE_PLUGIN_API)
     if (!m_processSuppressionDisabledForPageCounter.value())
@@ -167,6 +166,8 @@ void WebProcessPool::platformInitialize()
     if (![[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitSuppressMemoryPressureHandler"])
         installMemoryPressureHandler();
 
+    setLegacyCustomProtocolManagerClient(makeUnique<LegacyCustomProtocolManagerClient>());
+
 #if PLATFORM(IOS_FAMILY) && !PLATFORM(MACCATALYST)
     if (!_MGCacheValid()) {
         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
@@ -494,6 +495,22 @@ void WebProcessPool::platformInitializeNetworkProcess(NetworkProcessCreationPara
 
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 
+    {
+        bool isSafari = false;
+        bool isMiniBrowser = false;
+#if PLATFORM(IOS_FAMILY)
+        isSafari = WebCore::IOSApplication::isMobileSafari();
+        isMiniBrowser = WebCore::IOSApplication::isMiniBrowser();
+#elif PLATFORM(MAC)
+        isSafari = WebCore::MacApplication::isSafari();
+        isMiniBrowser = WebCore::MacApplication::isMiniBrowser();
+#endif
+        if (isSafari || isMiniBrowser) {
+            parameters.defaultDataStoreParameters.networkSessionParameters.httpProxy = URL(URL(), [defaults stringForKey:(NSString *)WebKit2HTTPProxyDefaultsKey]);
+            parameters.defaultDataStoreParameters.networkSessionParameters.httpsProxy = URL(URL(), [defaults stringForKey:(NSString *)WebKit2HTTPSProxyDefaultsKey]);
+        }
+    }
+
     parameters.networkATSContext = adoptCF(_CFNetworkCopyATSContext());
 
     parameters.shouldSuppressMemoryPressureHandler = [defaults boolForKey:WebKitSuppressMemoryPressureHandlerDefaultsKey];
@@ -507,8 +524,12 @@ void WebProcessPool::platformInitializeNetworkProcess(NetworkProcessCreationPara
     NSNumber *databaseEnabledValue = [defaults objectForKey:[NSString stringWithFormat:@"InternalDebug%@", WebPreferencesKey::isITPDatabaseEnabledKey().createCFString().get()]];
     if (databaseEnabledValue)
         parameters.shouldEnableITPDatabase = databaseEnabledValue.boolValue;
+    else
+        parameters.shouldEnableITPDatabase = m_defaultPageGroup->preferences().isITPDatabaseEnabled();
 
     parameters.enableAdClickAttributionDebugMode = [defaults boolForKey:[NSString stringWithFormat:@"Experimental%@", WebPreferencesKey::adClickAttributionDebugModeEnabledKey().createCFString().get()]];
+
+    parameters.defaultDataStoreParameters.networkSessionParameters.appHasRequestedCrossWebsiteTrackingPermission = hasRequestedCrossWebsiteTrackingPermission();
 }
 
 void WebProcessPool::platformInvalidateContext()
@@ -587,6 +608,11 @@ bool WebProcessPool::processSuppressionEnabled() const
     return !m_userObservablePageCounter.value() && !m_processSuppressionDisabledForPageCounter.value();
 }
 
+bool WebProcessPool::networkProcessHasEntitlementForTesting(const String& entitlement)
+{
+    return WTF::hasEntitlement(ensureNetworkProcess().connection()->xpcConnection(), entitlement.utf8().data());
+}
+
 #if PLATFORM(IOS_FAMILY) && !PLATFORM(MACCATALYST)
 float WebProcessPool::displayBrightness()
 {
@@ -923,4 +949,23 @@ void WebProcessPool::registerHighDynamicRangeChangeCallback()
 }
 #endif
 
+OSObjectPtr<xpc_object_t> WebProcessPool::xpcEndpointMessage() const
+{
+    return m_endpointMessage;
+}
+
+void WebProcessPool::sendNetworkProcessXPCEndpointToWebProcess(OSObjectPtr<xpc_object_t> endpointMessage)
+{
+    m_endpointMessage = endpointMessage;
+
+    for (auto process : m_processes) {
+        if (process->state() != AuxiliaryProcessProxy::State::Running)
+            continue;
+        if (!process->connection())
+            continue;
+        auto connection = process->connection()->xpcConnection();
+        xpc_connection_send_message(connection, endpointMessage.get());
+    }
+}
+
 } // namespace WebKit
index f7cff85..c5de4e7 100644 (file)
@@ -75,8 +75,8 @@ void DownloadProxy::cancel()
     if (!m_processPool)
         return;
 
-    if (m_dataStore)
-        m_dataStore->networkProcess().send(Messages::NetworkProcess::CancelDownload(m_downloadID), 0);
+    if (NetworkProcessProxy* networkProcess = m_processPool->networkProcess())
+        networkProcess->send(Messages::NetworkProcess::CancelDownload(m_downloadID), 0);
 }
 
 void DownloadProxy::invalidate()
@@ -103,13 +103,15 @@ WebPageProxy* DownloadProxy::originatingPage() const
 #if PLATFORM(COCOA)
 void DownloadProxy::publishProgress(const URL& URL)
 {
-    if (!m_dataStore)
+    if (!m_processPool)
         return;
 
-    SandboxExtension::Handle handle;
-    bool createdSandboxExtension = SandboxExtension::createHandle(URL.fileSystemPath(), SandboxExtension::Type::ReadWrite, handle);
-    ASSERT_UNUSED(createdSandboxExtension, createdSandboxExtension);
-    m_dataStore->networkProcess().send(Messages::NetworkProcess::PublishDownloadProgress(m_downloadID, URL, handle), 0);
+    if (auto* networkProcess = m_processPool->networkProcess()) {
+        SandboxExtension::Handle handle;
+        bool createdSandboxExtension = SandboxExtension::createHandle(URL.fileSystemPath(), SandboxExtension::Type::ReadWrite, handle);
+        ASSERT_UNUSED(createdSandboxExtension, createdSandboxExtension);
+        networkProcess->send(Messages::NetworkProcess::PublishDownloadProgress(m_downloadID, URL, handle), 0);
+    }
 }
 #endif // PLATFORM(COCOA)
 
@@ -129,10 +131,11 @@ void DownloadProxy::didStart(const ResourceRequest& request, const String& sugge
 
 void DownloadProxy::didReceiveAuthenticationChallenge(AuthenticationChallenge&& authenticationChallenge, uint64_t challengeID)
 {
-    if (!m_processPool || !m_dataStore)
+    if (!m_processPool)
         return;
 
-    auto authenticationChallengeProxy = AuthenticationChallengeProxy::create(WTFMove(authenticationChallenge), challengeID, makeRef(*m_dataStore->networkProcess().connection()), nullptr);
+    auto authenticationChallengeProxy = AuthenticationChallengeProxy::create(WTFMove(authenticationChallenge), challengeID, makeRef(*m_processPool->networkingProcessConnection()), nullptr);
+
     m_processPool->downloadClient().didReceiveAuthenticationChallenge(*this, authenticationChallengeProxy.get());
 }
 
@@ -143,10 +146,15 @@ void DownloadProxy::willSendRequest(ResourceRequest&& proposedRequest, const Res
 
     m_processPool->downloadClient().willSendRequest(*this, WTFMove(proposedRequest), redirectResponse, [this, protectedThis = makeRef(*this)](ResourceRequest&& newRequest) {
         m_redirectChain.append(newRequest.url());
-        if (!protectedThis->m_dataStore)
+
+        if (!protectedThis->m_processPool)
             return;
-        auto& networkProcessProxy = protectedThis->m_dataStore->networkProcess();
-        networkProcessProxy.send(Messages::NetworkProcess::ContinueWillSendRequest(protectedThis->m_downloadID, newRequest), 0);
+
+        auto* networkProcessProxy = protectedThis->m_processPool->networkProcess();
+        if (!networkProcessProxy)
+            return;
+
+        networkProcessProxy->send(Messages::NetworkProcess::ContinueWillSendRequest(protectedThis->m_downloadID, newRequest), 0);
     });
 }
 
@@ -171,14 +179,16 @@ void DownloadProxy::decideDestinationWithSuggestedFilenameAsync(DownloadID downl
     if (!m_processPool)
         return;
     
-    m_processPool->downloadClient().decideDestinationWithSuggestedFilename(*this, ResourceResponseBase::sanitizeSuggestedFilename(suggestedFilename), [this, protectedThis = makeRef(*this), downloadID] (AllowOverwrite allowOverwrite, String destination) {
+    m_processPool->downloadClient().decideDestinationWithSuggestedFilename(*this, ResourceResponseBase::sanitizeSuggestedFilename(suggestedFilename), [this, protectedThis = makeRef(*this), downloadID = downloadID] (AllowOverwrite allowOverwrite, String destination) {
         SandboxExtension::Handle sandboxExtensionHandle;
         if (!destination.isNull())
             SandboxExtension::createHandle(destination, SandboxExtension::Type::ReadWrite, sandboxExtensionHandle);
 
-        if (!m_dataStore)
+        if (!m_processPool)
             return;
-        m_dataStore->networkProcess().send(Messages::NetworkProcess::ContinueDecidePendingDownloadDestination(downloadID, destination, sandboxExtensionHandle, allowOverwrite == AllowOverwrite::Yes), 0);
+
+        if (auto* networkProcess = m_processPool->networkProcess())
+            networkProcess->send(Messages::NetworkProcess::ContinueDecidePendingDownloadDestination(downloadID, destination, sandboxExtensionHandle, allowOverwrite == AllowOverwrite::Yes), 0);
     });
 }
 
index d74a8fa..76a0715 100644 (file)
@@ -44,7 +44,7 @@
 namespace WebKit {
 
 DownloadProxyMap::DownloadProxyMap(NetworkProcessProxy& process)
-    : m_process(process)
+    : m_process(makeWeakPtr(process))
 #if PLATFORM(COCOA)
     , m_shouldTakeAssertion(WTF::processHasEntitlement("com.apple.multitasking.systemappassertions"))
 #endif
@@ -70,12 +70,14 @@ void DownloadProxyMap::platformDestroy()
 
 void DownloadProxyMap::applicationDidEnterBackground()
 {
-    m_process.send(Messages::NetworkProcess::ApplicationDidEnterBackground(), 0);
+    if (m_process)
+        m_process->send(Messages::NetworkProcess::ApplicationDidEnterBackground(), 0);
 }
 
 void DownloadProxyMap::applicationWillEnterForeground()
 {
-    m_process.send(Messages::NetworkProcess::ApplicationWillEnterForeground(), 0);
+    if (m_process)
+        m_process->send(Messages::NetworkProcess::ApplicationWillEnterForeground(), 0);
 }
 
 DownloadProxy& DownloadProxyMap::createDownloadProxy(WebsiteDataStore& dataStore, WebProcessPool& processPool, const WebCore::ResourceRequest& resourceRequest, const FrameInfoData& frameInfo, WebPageProxy* originatingPage)
@@ -90,12 +92,13 @@ DownloadProxy& DownloadProxyMap::createDownloadProxy(WebsiteDataStore& dataStore
         m_downloadUIAssertion = makeUnique<ProcessAssertion>(getCurrentProcessID(), "WebKit downloads"_s, ProcessAssertionType::UnboundedNetworking);
 
         ASSERT(!m_downloadNetworkingAssertion);
-        m_downloadNetworkingAssertion = makeUnique<ProcessAssertion>(m_process.processIdentifier(), "WebKit downloads"_s, ProcessAssertionType::UnboundedNetworking);
+        RELEASE_ASSERT(m_process);
+        m_downloadNetworkingAssertion = makeUnique<ProcessAssertion>(m_process->processIdentifier(), "WebKit downloads"_s, ProcessAssertionType::UnboundedNetworking);
 
         RELEASE_LOG(ProcessSuspension, "UIProcess took 'WebKit downloads' assertions for UIProcess and NetworkProcess");
     }
 
-    m_process.addMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID().downloadID(), downloadProxy.get());
+    m_process->addMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadProxy->downloadID().downloadID(), downloadProxy.get());
 
     return downloadProxy;
 }
@@ -106,9 +109,12 @@ void DownloadProxyMap::downloadFinished(DownloadProxy& downloadProxy)
 
     RELEASE_LOG(Loading, "Removing download %" PRIu64 " from UIProcess DownloadProxyMap", downloadID.downloadID());
 
+    // The DownloadProxy may be holding the last reference to the process pool.
+    auto protectedProcessPool = makeRefPtr(m_process->processPool());
+
     ASSERT(m_downloads.contains(downloadID));
 
-    m_process.removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadID.downloadID());
+    m_process->removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), downloadID.downloadID());
     downloadProxy.invalidate();
     m_downloads.remove(downloadID);
 
@@ -127,13 +133,15 @@ void DownloadProxyMap::invalidate()
     for (const auto& download : m_downloads.values()) {
         download->processDidClose();
         download->invalidate();
-        m_process.removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), download->downloadID().downloadID());
+        m_process->removeMessageReceiver(Messages::DownloadProxy::messageReceiverName(), download->downloadID().downloadID());
     }
 
     m_downloads.clear();
     m_downloadUIAssertion = nullptr;
     m_downloadNetworkingAssertion = nullptr;
     RELEASE_LOG(ProcessSuspension, "UIProcess DownloadProxyMap invalidated - Released 'WebKit downloads' assertions for UIProcess and NetworkProcess");
+
+    m_process = nullptr;
 }
 
 } // namespace WebKit
index 4fa001b..3be2079 100644 (file)
@@ -71,7 +71,7 @@ private:
     void platformCreate();
     void platformDestroy();
 
-    NetworkProcessProxy& m_process;
+    WeakPtr<NetworkProcessProxy> m_process;
     HashMap<DownloadID, RefPtr<DownloadProxy>> m_downloads;
 
     bool m_shouldTakeAssertion { false };
index d6c3323..8c23bbe 100644 (file)
@@ -44,17 +44,17 @@ LegacyCustomProtocolManagerProxy::~LegacyCustomProtocolManagerProxy()
 
 void LegacyCustomProtocolManagerProxy::startLoading(LegacyCustomProtocolID customProtocolID, const WebCore::ResourceRequest& request)
 {
-    m_networkProcessProxy.customProtocolManagerClient().startLoading(*this, customProtocolID, request);
+    m_networkProcessProxy.processPool().customProtocolManagerClient().startLoading(*this, customProtocolID, request);
 }
 
 void LegacyCustomProtocolManagerProxy::stopLoading(LegacyCustomProtocolID customProtocolID)
 {
-    m_networkProcessProxy.customProtocolManagerClient().stopLoading(*this, customProtocolID);
+    m_networkProcessProxy.processPool().customProtocolManagerClient().stopLoading(*this, customProtocolID);
 }
 
 void LegacyCustomProtocolManagerProxy::invalidate()
 {
-    m_networkProcessProxy.customProtocolManagerClient().invalidate(*this);
+    m_networkProcessProxy.processPool().customProtocolManagerClient().invalidate(*this);
 }
 
 void LegacyCustomProtocolManagerProxy::wasRedirectedToRequest(LegacyCustomProtocolID customProtocolID, const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& redirectResponse)
index 01a1571..c1f4708 100644 (file)
@@ -27,7 +27,6 @@
 #include "NetworkProcessProxy.h"
 
 #include "APIContentRuleList.h"
-#include "APICustomProtocolManagerClient.h"
 #include "AuthenticationChallengeProxy.h"
 #include "AuthenticationManager.h"
 #include "DownloadProxyMap.h"
@@ -36,7 +35,6 @@
 #include "LegacyCustomProtocolManagerMessages.h"
 #include "LegacyCustomProtocolManagerProxyMessages.h"
 #endif
-#include "LegacyGlobalSettings.h"
 #include "Logging.h"
 #include "NetworkContentRuleListManagerMessages.h"
 #include "NetworkProcessConnectionInfo.h"
@@ -50,7 +48,6 @@
 #include "ShouldGrandfatherStatistics.h"
 #include "StorageAccessStatus.h"
 #include "WebCompiledContentRuleList.h"
-#include "WebCookieManagerProxy.h"
 #include "WebPageMessages.h"
 #include "WebPageProxy.h"
 #include "WebProcessMessages.h"
 #include "WebUserContentControllerProxy.h"
 #include "WebsiteData.h"
 #include "WebsiteDataStoreClient.h"
-#include "WebsiteDataStoreParameters.h"
 #include <WebCore/ClientOrigin.h>
 #include <WebCore/RegistrableDomain.h>
-#include <wtf/CallbackAggregator.h>
 #include <wtf/CompletionHandler.h>
 
 #if ENABLE(SEC_ITEM_SHIM)
 #include <wtf/spi/darwin/XPCSPI.h>
 #endif
 
-#if PLATFORM(COCOA)
-#include "LegacyCustomProtocolManagerClient.h"
-#endif
-
 #define MESSAGE_CHECK(assertion) MESSAGE_CHECK_BASE(assertion, connection())
 
 namespace WebKit {
 using namespace WebCore;
 
-static HashSet<NetworkProcessProxy*>& networkProcessesSet()
-{
-    RELEASE_ASSERT(RunLoop::isMain());
-    static NeverDestroyed<HashSet<NetworkProcessProxy*>> set;
-    return set;
-}
-
-Vector<Ref<NetworkProcessProxy>> NetworkProcessProxy::allNetworkProcesses()
-{
-    Vector<Ref<NetworkProcessProxy>> processes;
-    processes.reserveInitialCapacity(networkProcessesSet().size());
-    for (auto* networkProcess : networkProcessesSet())
-        processes.uncheckedAppend(*networkProcess);
-    return processes;
-}
-
-static RefPtr<NetworkProcessProxy>& defaultProcess()
-{
-    static NeverDestroyed<RefPtr<NetworkProcessProxy>> process;
-    return process.get();
-}
-
-Ref<NetworkProcessProxy> NetworkProcessProxy::defaultNetworkProcess()
-{
-    if (!defaultProcess())
-        defaultProcess() = NetworkProcessProxy::create();
-    return *defaultProcess();
-}
-
-void NetworkProcessProxy::terminate()
-{
-    AuxiliaryProcessProxy::terminate();
-    if (auto* connection = this->connection())
-        connection->invalidate();
-    didTerminate();
-}
-
-void NetworkProcessProxy::didTerminate()
-{
-    if (this == defaultProcess().get())
-        defaultProcess() = nullptr;
-}
-
-void NetworkProcessProxy::sendCreationParametersToNewProcess()
-{
-    ASSERT(RunLoop::isMain());
-
-    // FIXME: This is a temporary workaround for apps using WebKit API on non-main threads.
-    // We should remove this once we enforce threading violation check on our APIs.
-    // https://bugs.webkit.org/show_bug.cgi?id=200246.
-    if (!RunLoop::isMain()) {
-        callOnMainRunLoopAndWait([this] {
-            sendCreationParametersToNewProcess();
-        });
-    }
-
-    NetworkProcessCreationParameters parameters;
-    parameters.urlSchemesRegisteredAsSecure = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsSecure());
-    parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsBypassingContentSecurityPolicy());
-    parameters.urlSchemesRegisteredAsLocal = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsLocal());
-    parameters.urlSchemesRegisteredAsNoAccess = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsNoAccess());
-    parameters.cacheModel = LegacyGlobalSettings::singleton().cacheModel();
-    for (auto& scheme : WebProcessPool::urlSchemesWithCustomProtocolHandlers())
-        parameters.urlSchemesRegisteredForCustomProtocols.append(scheme);
-#if PLATFORM(IOS_FAMILY)
-    if (String cookieStorageDirectory = WebProcessPool::cookieStorageDirectory(); !cookieStorageDirectory.isEmpty())
-        SandboxExtension::createHandleForReadWriteDirectory(cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle);
-    if (String containerCachesDirectory = WebProcessPool::networkingCachesDirectory(); !containerCachesDirectory.isEmpty())
-        SandboxExtension::createHandleForReadWriteDirectory(containerCachesDirectory, parameters.containerCachesDirectoryExtensionHandle);
-    if (String parentBundleDirectory = WebProcessPool::parentBundleDirectory(); !parentBundleDirectory.isEmpty())
-        SandboxExtension::createHandle(parentBundleDirectory, SandboxExtension::Type::ReadOnly, parameters.parentBundleDirectoryExtensionHandle);
-#endif
-    WebProcessPool::platformInitializeNetworkProcess(parameters);
-    send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0);
-}
-
-static bool anyProcessPoolAlwaysRunsAtBackgroundPriority()
-{
-    for (auto* processPool : WebProcessPool::allProcessPools()) {
-        if (processPool->alwaysRunsAtBackgroundPriority())
-            return true;
-    }
-    return false;
-}
-
-static bool anyProcessPoolShouldTakeUIBackgroundAssertion()
-{
-    for (auto* processPool : WebProcessPool::allProcessPools()) {
-        if (processPool->shouldTakeUIBackgroundAssertion())
-            return true;
-    }
-    return false;
-}
-
-NetworkProcessProxy::NetworkProcessProxy()
-    : AuxiliaryProcessProxy(anyProcessPoolAlwaysRunsAtBackgroundPriority())
+NetworkProcessProxy::NetworkProcessProxy(WebProcessPool& processPool)
+    : AuxiliaryProcessProxy(processPool.alwaysRunsAtBackgroundPriority())
+    , m_processPool(processPool)
 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
-    , m_customProtocolManagerClient(makeUniqueRef<LegacyCustomProtocolManagerClient>())
     , m_customProtocolManagerProxy(*this)
-#else
-    , m_customProtocolManagerClient(makeUniqueRef<API::CustomProtocolManagerClient>())
 #endif
-    , m_throttler(*this, anyProcessPoolShouldTakeUIBackgroundAssertion())
-    , m_cookieManager(WebCookieManagerProxy::create(*this))
+    , m_throttler(*this, processPool.shouldTakeUIBackgroundAssertion())
 {
     connect();
-    sendCreationParametersToNewProcess();
-    updateProcessAssertion();
-    networkProcessesSet().add(this);
 }
 
 NetworkProcessProxy::~NetworkProcessProxy()
@@ -207,7 +98,6 @@ NetworkProcessProxy::~NetworkProcessProxy()
 
     if (m_downloadProxyMap)
         m_downloadProxyMap->invalidate();
-    networkProcessesSet().remove(this);
 }
 
 void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions)
@@ -215,8 +105,15 @@ void NetworkProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launc
     launchOptions.processType = ProcessLauncher::ProcessType::Network;
     AuxiliaryProcessProxy::getLaunchOptions(launchOptions);
 
-    if (WebsiteDataStore::shouldMakeNextNetworkProcessLaunchFailForTesting())
+    if (processPool().shouldMakeNextNetworkProcessLaunchFailForTesting()) {
+        processPool().setShouldMakeNextNetworkProcessLaunchFailForTesting(false);
         launchOptions.shouldMakeProcessLaunchFailForTesting = true;
+    }
+
+#if PLATFORM(PLAYSTATION)
+    launchOptions.processPath = m_processPool.networkProcessPath();
+    launchOptions.userId = m_processPool.userId();
+#endif
 }
 
 void NetworkProcessProxy::connectionWillOpen(IPC::Connection& connection)
@@ -269,12 +166,12 @@ void NetworkProcessProxy::synthesizeAppIsBackground(bool background)
     }
 }
 
-DownloadProxy& NetworkProcessProxy::createDownloadProxy(WebsiteDataStore& dataStore, WebProcessPool& processPool, const ResourceRequest& resourceRequest, const FrameInfoData& frameInfo, WebPageProxy* originatingPage)
+DownloadProxy& NetworkProcessProxy::createDownloadProxy(WebsiteDataStore& dataStore, const ResourceRequest& resourceRequest, const FrameInfoData& frameInfo, WebPageProxy* originatingPage)
 {
     if (!m_downloadProxyMap)
         m_downloadProxyMap = makeUnique<DownloadProxyMap>(*this);
 
-    return m_downloadProxyMap->createDownloadProxy(dataStore, processPool, resourceRequest, frameInfo, originatingPage);
+    return m_downloadProxyMap->createDownloadProxy(dataStore, m_processPool, resourceRequest, frameInfo, originatingPage);
 }
 
 void NetworkProcessProxy::fetchWebsiteData(PAL::SessionID sessionID, OptionSet<WebsiteDataType> dataTypes, OptionSet<WebsiteDataFetchOption> fetchOptions, CompletionHandler<void (WebsiteData)>&& completionHandler)
@@ -340,11 +237,8 @@ void NetworkProcessProxy::networkProcessCrashed()
 {
     clearCallbackStates();
 
-    Ref<NetworkProcessProxy> protectedThis(*this);
-    for (auto* processPool : WebProcessPool::allProcessPools())
-        processPool->networkProcessCrashed(*this);
-    for (auto& websiteDataStore : m_websiteDataStores)
-        websiteDataStore.networkProcessCrashed(*this);
+    // Tell the network process manager to forget about this network process proxy. This will cause us to be deleted.
+    m_processPool.networkProcessCrashed(*this);
 }
 
 void NetworkProcessProxy::clearCallbackStates()
@@ -364,6 +258,9 @@ void NetworkProcessProxy::didReceiveMessage(IPC::Connection& connection, IPC::De
     if (dispatchMessage(connection, decoder))
         return;
 
+    if (m_processPool.dispatchMessage(connection, decoder))
+        return;
+
     didReceiveNetworkProcessProxyMessage(connection, decoder);
 }
 
@@ -377,6 +274,8 @@ void NetworkProcessProxy::didReceiveSyncMessage(IPC::Connection& connection, IPC
 
 void NetworkProcessProxy::didClose(IPC::Connection&)
 {
+    auto protectedProcessPool = makeRef(m_processPool);
+
     if (m_downloadProxyMap)
         m_downloadProxyMap->invalidate();
 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
@@ -432,6 +331,11 @@ void NetworkProcessProxy::didReceiveAuthenticationChallenge(PAL::SessionID sessi
         return;
     }
 
+    if (!topOrigin || !m_processPool.isServiceWorkerPageID(pageID)) {
+        processAuthenticationChallenge(sessionID, WTFMove(authenticationChallenge));
+        return;
+    }
+
     WebPageProxy::forMostVisibleWebPageIfAny(sessionID, *topOrigin, [this, weakThis = makeWeakPtr(this), sessionID, authenticationChallenge = WTFMove(authenticationChallenge), negotiatedLegacyTLS](auto* page) mutable {
         if (!weakThis)
             return;
@@ -488,6 +392,11 @@ void NetworkProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Con
         networkProcessCrashed();
         return;
     }
+
+#if PLATFORM(COCOA)
+    if (m_processPool.processSuppressionEnabled())
+        setProcessSuppressionEnabled(true);
+#endif
     
 #if PLATFORM(IOS_FAMILY)
     if (xpc_connection_t connection = this->connection()->xpcConnection())
@@ -1296,8 +1205,7 @@ void NetworkProcessProxy::setThirdPartyCNAMEDomainForTesting(PAL::SessionID sess
 }
 void NetworkProcessProxy::setDomainsWithUserInteraction(HashSet<WebCore::RegistrableDomain>&& domains)
 {
-    for (auto* processPool : WebProcessPool::allProcessPools())
-        processPool->setDomainsWithUserInteraction(HashSet<WebCore::RegistrableDomain> { domains });
+    processPool().setDomainsWithUserInteraction(WTFMove(domains));
 }
 #endif // ENABLE(RESOURCE_LOAD_STATISTICS)
 
@@ -1344,31 +1252,45 @@ void NetworkProcessProxy::flushCookies(const PAL::SessionID& sessionID, Completi
     sendWithAsyncReply(Messages::NetworkProcess::FlushCookies(sessionID), WTFMove(completionHandler));
 }
 
-void NetworkProcessProxy::addSession(WebsiteDataStore& store)
+void NetworkProcessProxy::addSession(Ref<WebsiteDataStore>&& store)
 {
-    m_websiteDataStores.add(store);
+    m_sessionIDs.add(store->sessionID());
 
     if (canSendMessage())
-        send(Messages::NetworkProcess::AddWebsiteDataStore { store.parameters() }, 0);
-    auto sessionID = store.sessionID();
+        send(Messages::NetworkProcess::AddWebsiteDataStore { store->parameters() }, 0);
+    auto sessionID = store->sessionID();
     if (!sessionID.isEphemeral()) {
 #if ENABLE(INDEXED_DATABASE)
-        createSymLinkForFileUpgrade(store.resolvedIndexedDatabaseDirectory());
+        createSymLinkForFileUpgrade(store->resolvedIndexedDatabaseDirectory());
 #endif
     }
 }
 
-void NetworkProcessProxy::removeSession(WebsiteDataStore& websiteDataStore)
+bool NetworkProcessProxy::hasSession(PAL::SessionID sessionID) const
+{
+    return m_sessionIDs.contains(sessionID);
+}
+
+void NetworkProcessProxy::removeSession(PAL::SessionID sessionID)
 {
-    m_websiteDataStores.remove(websiteDataStore);
+    m_sessionIDs.remove(sessionID);
 
     if (canSendMessage())
-        send(Messages::NetworkProcess::DestroySession { websiteDataStore.sessionID() }, 0);
+        send(Messages::NetworkProcess::DestroySession { sessionID }, 0);
 }
 
 WebsiteDataStore* NetworkProcessProxy::websiteDataStoreFromSessionID(PAL::SessionID sessionID)
 {
-    return WebsiteDataStore::existingDataStoreForSessionID(sessionID);
+    if (sessionID == PAL::SessionID::defaultSessionID()) {
+        if (!WebsiteDataStore::defaultDataStoreExists()) {
+            auto* websiteDataStore = m_processPool.websiteDataStore();
+            if (websiteDataStore && websiteDataStore->sessionID() == sessionID)
+                return websiteDataStore;
+        }
+
+        return WebsiteDataStore::defaultDataStore().ptr();
+    }
+    return WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID);
 }
 
 void NetworkProcessProxy::retrieveCacheStorageParameters(PAL::SessionID sessionID)
@@ -1415,7 +1337,7 @@ void NetworkProcessProxy::didDestroyWebUserContentControllerProxy(WebUserContent
 #if ENABLE(SERVICE_WORKER)
 void NetworkProcessProxy::establishWorkerContextConnectionToNetworkProcess(RegistrableDomain&& registrableDomain, PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
 {
-    WebProcessPool::establishWorkerContextConnectionToNetworkProcess(*this, RegistrableDomain {registrableDomain}, sessionID, WTFMove(completionHandler));
+    m_processPool.establishWorkerContextConnectionToNetworkProcess(*this, WTFMove(registrableDomain), sessionID, WTFMove(completionHandler));
 }
 
 void NetworkProcessProxy::workerContextConnectionNoLongerNeeded(WebCore::ProcessIdentifier identifier)
@@ -1578,34 +1500,16 @@ void NetworkProcessProxy::preconnectTo(PAL::SessionID sessionID, WebPageProxyIde
     send(Messages::NetworkProcess::PreconnectTo(sessionID, webPageProxyID, webPageID, url, userAgent, storedCredentialsPolicy, isNavigatingToAppBoundDomain), 0);
 }
 
-static bool anyProcessPoolHasForegroundWebProcesses()
-{
-    for (auto* processPool : WebProcessPool::allProcessPools()) {
-        if (processPool->hasForegroundWebProcesses())
-            return true;
-    }
-    return false;
-}
-
-static bool anyProcessPoolHasBackgroundWebProcesses()
-{
-    for (auto* processPool : WebProcessPool::allProcessPools()) {
-        if (processPool->hasBackgroundWebProcesses())
-            return true;
-    }
-    return false;
-}
-
 void NetworkProcessProxy::updateProcessAssertion()
 {
-    if (anyProcessPoolHasForegroundWebProcesses()) {
+    if (processPool().hasForegroundWebProcesses()) {
         if (!ProcessThrottler::isValidForegroundActivity(m_activityFromWebProcesses)) {
             m_activityFromWebProcesses = throttler().foregroundActivity("Networking for foreground view(s)"_s);
             send(Messages::NetworkProcess::ProcessDidTransitionToForeground(), 0);
         }
         return;
     }
-    if (anyProcessPoolHasBackgroundWebProcesses()) {
+    if (processPool().hasBackgroundWebProcesses()) {
         if (!ProcessThrottler::isValidBackgroundActivity(m_activityFromWebProcesses)) {
             m_activityFromWebProcesses = throttler().backgroundActivity("Networking for background view(s)"_s);
             send(Messages::NetworkProcess::ProcessDidTransitionToBackground(), 0);
index 0ad6187..a0b4c1d 100644 (file)
 
 #if PLATFORM(COCOA)
 #include "XPCEventHandler.h"
-#include <wtf/OSObjectPtr.h>
 #endif
 
 namespace IPC {
 class FormDataReference;
 }
 
-namespace API {
-class CustomProtocolManagerClient;
-}
-
 namespace PAL {
 class SessionID;
 }
@@ -78,8 +73,8 @@ namespace WebKit {
 
 class DownloadProxy;
 class DownloadProxyMap;
-class WebCookieManagerProxy;
 class WebPageProxy;
+class WebProcessPool;
 class WebUserContentControllerProxy;
 
 enum class ShouldGrandfatherStatistics : bool;
@@ -91,9 +86,8 @@ struct FrameInfoData;
 struct NetworkProcessCreationParameters;
 struct ResourceLoadInfo;
 struct WebsiteData;
-struct WebsiteDataStoreParameters;
 
-class NetworkProcessProxy final : public AuxiliaryProcessProxy, private ProcessThrottlerClient, public CanMakeWeakPtr<NetworkProcessProxy>, public RefCounted<NetworkProcessProxy> {
+class NetworkProcessProxy final : public AuxiliaryProcessProxy, private ProcessThrottlerClient, public CanMakeWeakPtr<NetworkProcessProxy> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     using RegistrableDomain = WebCore::RegistrableDomain;
@@ -108,18 +102,12 @@ public:
     using DomainInNeedOfStorageAccess = WebCore::RegistrableDomain;
     using OpenerDomain = WebCore::RegistrableDomain;
 
-    static Ref<NetworkProcessProxy> defaultNetworkProcess();
-    static Ref<NetworkProcessProxy> create() { return adoptRef(*new NetworkProcessProxy); }
+    explicit NetworkProcessProxy(WebProcessPool&);
     ~NetworkProcessProxy();
 
-    static Vector<Ref<NetworkProcessProxy>> allNetworkProcesses();
-    
-    void terminate() final;
-    void didTerminate();
-
     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnectionDelayedReply&&);
 
-    DownloadProxy& createDownloadProxy(WebsiteDataStore&, WebProcessPool&, const WebCore::ResourceRequest&, const FrameInfoData&, WebPageProxy* originatingPage);
+    DownloadProxy& createDownloadProxy(WebsiteDataStore&, const WebCore::ResourceRequest&, const FrameInfoData&, WebPageProxy* originatingPage);
 
     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, OptionSet<WebsiteDataFetchOption>, CompletionHandler<void(WebsiteData)>&&);
     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince, CompletionHandler<void()>&& completionHandler);
@@ -218,12 +206,15 @@ public:
     ProcessThrottler& throttler() final { return m_throttler; }
     void updateProcessAssertion();
 
+    WebProcessPool& processPool() { return m_processPool; }
+
 #if ENABLE(CONTENT_EXTENSIONS)
     void didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy&);
 #endif
 
-    void addSession(WebsiteDataStore&);
-    void removeSession(WebsiteDataStore&);
+    void addSession(Ref<WebsiteDataStore>&&);
+    bool hasSession(PAL::SessionID) const;
+    void removeSession(PAL::SessionID);
     
 #if ENABLE(INDEXED_DATABASE)
     void createSymLinkForFileUpgrade(const String& indexedDatabaseDirectory);
@@ -238,8 +229,6 @@ public:
     void registerSchemeForLegacyCustomProtocol(const String&);
     void unregisterSchemeForLegacyCustomProtocol(const String&);
 
-    void networkProcessCrashed();
-    
     void resetQuota(PAL::SessionID, CompletionHandler<void()>&&);
 
     void resourceLoadDidSendRequest(WebPageProxyIdentifier, ResourceLoadInfo&&, WebCore::ResourceRequest&&, Optional<IPC::FormDataReference>&&);
@@ -259,19 +248,7 @@ public:
     void updateBundleIdentifier(const String&, CompletionHandler<void()>&&);
     void clearBundleIdentifier(CompletionHandler<void()>&&);
 
-    WebCookieManagerProxy& cookieManager() { return m_cookieManager.get(); }
-
-    API::CustomProtocolManagerClient& customProtocolManagerClient() { return m_customProtocolManagerClient.get(); }
-
-#if PLATFORM(COCOA)
-    xpc_object_t xpcEndpointMessage() const { return m_endpointMessage.get(); }
-#endif
-
 private:
-    explicit NetworkProcessProxy();
-
-    void sendCreationParametersToNewProcess();
-
     // AuxiliaryProcessProxy
     ASCIILiteral processName() const final { return "Networking"_s; }
 
@@ -279,6 +256,7 @@ private:
     void connectionWillOpen(IPC::Connection&) override;
     void processWillShutDown(IPC::Connection&) override;
 
+    void networkProcessCrashed();
     void clearCallbackStates();
 
     // IPC::Connection::Client
@@ -334,17 +312,16 @@ private:
 
     void processAuthenticationChallenge(PAL::SessionID, Ref<AuthenticationChallengeProxy>&&);
 
+    WebProcessPool& m_processPool;
+
     HashMap<CallbackID, CompletionHandler<void(WebsiteData)>> m_pendingFetchWebsiteDataCallbacks;
     HashMap<CallbackID, CompletionHandler<void()>> m_pendingDeleteWebsiteDataCallbacks;
     HashMap<CallbackID, CompletionHandler<void()>> m_pendingDeleteWebsiteDataForOriginsCallbacks;
 
     std::unique_ptr<DownloadProxyMap> m_downloadProxyMap;
-
-    UniqueRef<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
     LegacyCustomProtocolManagerProxy m_customProtocolManagerProxy;
 #endif
-
     ProcessThrottler m_throttler;
     std::unique_ptr<ProcessThrottler::BackgroundActivity> m_activityForHoldingLockedFiles;
     ProcessThrottler::ActivityVariant m_activityFromWebProcesses;
@@ -370,11 +347,9 @@ private:
     private:
         WeakPtr<NetworkProcessProxy> m_networkProcess;
     };
-    OSObjectPtr<xpc_object_t> m_endpointMessage;
 #endif
 
-    WeakHashSet<WebsiteDataStore> m_websiteDataStores;
-    Ref<WebCookieManagerProxy> m_cookieManager;
+    HashSet<PAL::SessionID> m_sessionIDs;
 };
 
 } // namespace WebKit
index 0e5faec..b8daedf 100644 (file)
@@ -51,11 +51,8 @@ bool NetworkProcessProxy::XPCEventHandler::handleXPCEvent(xpc_object_t event) co
     if (messageName.isEmpty())
         return false;
 
-    if (messageName == LaunchServicesDatabaseXPCConstants::xpcLaunchServicesDatabaseXPCEndpointMessageName) {
-        m_networkProcess->m_endpointMessage = event;
-        for (auto& dataStore : m_networkProcess->m_websiteDataStores)
-            dataStore.sendNetworkProcessXPCEndpointToAllWebProcesses();
-    }
+    if (messageName == LaunchServicesDatabaseXPCConstants::xpcLaunchServicesDatabaseXPCEndpointMessageName)
+        m_networkProcess->processPool().sendNetworkProcessXPCEndpointToWebProcess(event);
 
     return true;
 }
index 085e7d2..cc526aa 100644 (file)
@@ -29,7 +29,6 @@
 #include "APIArray.h"
 #include "APISecurityOrigin.h"
 #include "NetworkProcessMessages.h"
-#include "NetworkProcessProxy.h"
 #include "OptionalCallbackID.h"
 #include "WebCookieManagerMessages.h"
 #include "WebCookieManagerProxyMessages.h"
 namespace WebKit {
 using namespace WebCore;
 
-WebCookieManagerProxy::WebCookieManagerProxy(NetworkProcessProxy& networkProcess)
-    : m_networkProcess(makeWeakPtr(networkProcess))
+const char* WebCookieManagerProxy::supplementName()
 {
-    networkProcess.addMessageReceiver(Messages::WebCookieManagerProxy::messageReceiverName(), *this);
+    return "WebCookieManagerProxy";
+}
+
+Ref<WebCookieManagerProxy> WebCookieManagerProxy::create(WebProcessPool* processPool)
+{
+    return adoptRef(*new WebCookieManagerProxy(processPool));
+}
+
+WebCookieManagerProxy::WebCookieManagerProxy(WebProcessPool* processPool)
+    : WebContextSupplement(processPool)
+{
+    WebContextSupplement::processPool()->addMessageReceiver(Messages::WebCookieManagerProxy::messageReceiverName(), *this);
 }
 
 WebCookieManagerProxy::~WebCookieManagerProxy()
 {
-    if (m_networkProcess)
-        m_networkProcess->removeMessageReceiver(Messages::WebCookieManagerProxy::messageReceiverName());
     ASSERT(m_cookieObservers.isEmpty());
 }
 
@@ -58,84 +65,102 @@ void WebCookieManagerProxy::initializeClient(const WKCookieManagerClientBase* cl
     m_client.initialize(client);
 }
 
+// WebContextSupplement
+
+void WebCookieManagerProxy::processPoolDestroyed()
+{
+    Vector<Observer*> observers;
+    for (auto& observerSet : m_cookieObservers.values()) {
+        for (auto* observer : observerSet)
+            observers.append(observer);
+    }
+
+    for (auto* observer : observers)
+        observer->managerDestroyed();
+
+    ASSERT(m_cookieObservers.isEmpty());
+}
+
+void WebCookieManagerProxy::processDidClose(WebProcessProxy*)
+{
+}
+
+void WebCookieManagerProxy::processDidClose(NetworkProcessProxy*)
+{
+}
+
+void WebCookieManagerProxy::refWebContextSupplement()
+{
+    API::Object::ref();
+}
+
+void WebCookieManagerProxy::derefWebContextSupplement()
+{
+    API::Object::deref();
+}
+
 void WebCookieManagerProxy::getHostnamesWithCookies(PAL::SessionID sessionID, CompletionHandler<void(Vector<String>&&)>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::GetHostnamesWithCookies(sessionID), WTFMove(callbackFunction));
-    else
-        callbackFunction({ });
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::GetHostnamesWithCookies(sessionID), WTFMove(callbackFunction));
 }
 
 void WebCookieManagerProxy::deleteCookiesForHostnames(PAL::SessionID sessionID, const Vector<String>& hostnames)
 {
-    if (m_networkProcess)
-        m_networkProcess->send(Messages::WebCookieManager::DeleteCookiesForHostnames(sessionID, hostnames), 0);
+    processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteCookiesForHostnames(sessionID, hostnames));
 }
 
 void WebCookieManagerProxy::deleteAllCookies(PAL::SessionID sessionID)
 {
-    if (m_networkProcess)
-        m_networkProcess->send(Messages::WebCookieManager::DeleteAllCookies(sessionID), 0);
+    processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::DeleteAllCookies(sessionID));
 }
 
 void WebCookieManagerProxy::deleteCookie(PAL::SessionID sessionID, const Cookie& cookie, CompletionHandler<void()>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::DeleteCookie(sessionID, cookie), WTFMove(callbackFunction));
-    else
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::DeleteCookie(sessionID, cookie), [callbackFunction = WTFMove(callbackFunction)]() mutable {
         callbackFunction();
+    });
 }
 
 void WebCookieManagerProxy::deleteAllCookiesModifiedSince(PAL::SessionID sessionID, WallTime time, CompletionHandler<void()>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::DeleteAllCookiesModifiedSince(sessionID, time), WTFMove(callbackFunction));
-    else
-        callbackFunction();
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::DeleteAllCookiesModifiedSince(sessionID, time), WTFMove(callbackFunction));
 }
 
 void WebCookieManagerProxy::setCookies(PAL::SessionID sessionID, const Vector<Cookie>& cookies, CompletionHandler<void()>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::SetCookie(sessionID, cookies), WTFMove(callbackFunction));
-    else
-        callbackFunction();
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::SetCookie(sessionID, cookies), WTFMove(callbackFunction));
 }
 
 void WebCookieManagerProxy::setCookies(PAL::SessionID sessionID, const Vector<Cookie>& cookies, const URL& url, const URL& mainDocumentURL, CompletionHandler<void()>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::SetCookies(sessionID, cookies, url, mainDocumentURL), WTFMove(callbackFunction));
-    else
-        callbackFunction();
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::SetCookies(sessionID, cookies, url, mainDocumentURL), WTFMove(callbackFunction));
 }
 
 void WebCookieManagerProxy::getAllCookies(PAL::SessionID sessionID, CompletionHandler<void(Vector<Cookie>&&)>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::GetAllCookies(sessionID), WTFMove(callbackFunction));
-    else
-        callbackFunction({ });
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::GetAllCookies(sessionID), WTFMove(callbackFunction));
 }
 
 void WebCookieManagerProxy::getCookies(PAL::SessionID sessionID, const URL& url, CompletionHandler<void(Vector<Cookie>&&)>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::GetCookies(sessionID, url), WTFMove(callbackFunction));
-    else
-        callbackFunction({ });
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::GetCookies(sessionID, url), WTFMove(callbackFunction));
 }
 
 void WebCookieManagerProxy::startObservingCookieChanges(PAL::SessionID sessionID)
 {
-    if (m_networkProcess)
-        m_networkProcess->send(Messages::WebCookieManager::StartObservingCookieChanges(sessionID), 0);
+    processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StartObservingCookieChanges(sessionID));
 }
 
 void WebCookieManagerProxy::stopObservingCookieChanges(PAL::SessionID sessionID)
 {
-    if (m_networkProcess)
-        m_networkProcess->send(Messages::WebCookieManager::StopObservingCookieChanges(sessionID), 0);
+    processPool()->sendToNetworkingProcessRelaunchingIfNecessary(Messages::WebCookieManager::StopObservingCookieChanges(sessionID));
 }
 
 void WebCookieManagerProxy::setCookieObserverCallback(PAL::SessionID sessionID, WTF::Function<void ()>&& callback)
@@ -186,18 +211,18 @@ void WebCookieManagerProxy::cookiesDidChange(PAL::SessionID sessionID)
 
 void WebCookieManagerProxy::setHTTPCookieAcceptPolicy(PAL::SessionID, HTTPCookieAcceptPolicy policy, CompletionHandler<void()>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::SetHTTPCookieAcceptPolicy(policy), WTFMove(callbackFunction));
-    else
-        callbackFunction();
+#if USE(SOUP)
+    processPool()->setInitialHTTPCookieAcceptPolicy(policy);
+#endif
+
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::SetHTTPCookieAcceptPolicy(policy), WTFMove(callbackFunction));
 }
 
-void WebCookieManagerProxy::getHTTPCookieAcceptPolicy(PAL::SessionID sessionID, CompletionHandler<void(HTTPCookieAcceptPolicy)>&& callbackFunction)
+void WebCookieManagerProxy::getHTTPCookieAcceptPolicy(PAL::SessionID, CompletionHandler<void(HTTPCookieAcceptPolicy)>&& callbackFunction)
 {
-    if (m_networkProcess)
-        m_networkProcess->sendWithAsyncReply(Messages::WebCookieManager::GetHTTPCookieAcceptPolicy(sessionID), WTFMove(callbackFunction));
-    else
-        callbackFunction(HTTPCookieAcceptPolicy::Never);
+    auto& networkProcess = processPool()->ensureNetworkProcess();
+    networkProcess.sendWithAsyncReply(Messages::WebCookieManager::GetHTTPCookieAcceptPolicy(), WTFMove(callbackFunction));
 }
 
 } // namespace WebKit
index 6f51f03..0bdfc0d 100644 (file)
@@ -56,9 +56,11 @@ typedef GenericCallback<API::Array*> ArrayCallback;
 typedef GenericCallback<WebCore::HTTPCookieAcceptPolicy> HTTPCookieAcceptPolicyCallback;
 typedef GenericCallback<const Vector<WebCore::Cookie>&> GetCookiesCallback;
 
-class WebCookieManagerProxy : public API::ObjectImpl<API::Object::Type::CookieManager>, private IPC::MessageReceiver {
+class WebCookieManagerProxy : public API::ObjectImpl<API::Object::Type::CookieManager>, public WebContextSupplement, private IPC::MessageReceiver {
 public:
-    static Ref<WebCookieManagerProxy> create(NetworkProcessProxy& networkProcess) { return adoptRef(*new WebCookieManagerProxy(networkProcess)); }
+    static const char* supplementName();
+
+    static Ref<WebCookieManagerProxy> create(WebProcessPool*);
     virtual ~WebCookieManagerProxy();
 
     void initializeClient(const WKCookieManagerClientBase*);
@@ -102,10 +104,17 @@ public:
     using API::Object::deref;
 
 private:
-    WebCookieManagerProxy(NetworkProcessProxy&);
+    WebCookieManagerProxy(WebProcessPool*);
 
     void cookiesDidChange(PAL::SessionID);
 
+    // WebContextSupplement
+    void processPoolDestroyed() override;
+    void processDidClose(WebProcessProxy*) override;
+    void processDidClose(NetworkProcessProxy*) override;
+    void refWebContextSupplement() override;
+    void derefWebContextSupplement() override;
+
     // IPC::MessageReceiver
     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
 
@@ -116,7 +125,6 @@ private:
     HashMap<PAL::SessionID, WTF::Function<void ()>> m_legacyCookieObservers;
     HashMap<PAL::SessionID, HashSet<Observer*>> m_cookieObservers;
 
-    WeakPtr<NetworkProcessProxy> m_networkProcess;
     WebCookieManagerProxyClient m_client;
 
 #if USE(SOUP)
index dd17f21..5289623 100644 (file)
@@ -1746,7 +1746,7 @@ void WebPageProxy::setControlledByAutomation(bool controlled)
         return;
 
     send(Messages::WebPage::SetControlledByAutomation(controlled));
-    websiteDataStore().networkProcess().send(Messages::NetworkProcess::SetSessionIsControlledByAutomation(m_websiteDataStore->sessionID(), m_controlledByAutomation), 0);
+    m_process->processPool().sendToNetworkingProcess(Messages::NetworkProcess::SetSessionIsControlledByAutomation(m_websiteDataStore->sessionID(), m_controlledByAutomation));
 }
 
 void WebPageProxy::createInspectorTarget(const String& targetId, Inspector::InspectorTargetType type)
@@ -3207,7 +3207,11 @@ void WebPageProxy::isForcedIntoAppBoundModeTesting(CompletionHandler<void(bool)>
 void WebPageProxy::disableServiceWorkerEntitlementInNetworkProcess()
 {
 #if ENABLE(APP_BOUND_DOMAINS) && !PLATFORM(MACCATALYST)
-    websiteDataStore().networkProcess().send(Messages::NetworkProcess::DisableServiceWorkerEntitlement(), 0);
+    if (auto* networkProcess = m_process->processPool().networkProcess()) {
+        if (!networkProcess->canSendMessage())
+            return;
+        networkProcess->send(Messages::NetworkProcess::DisableServiceWorkerEntitlement(), 0);
+    }
 #endif
 }
 
@@ -3216,7 +3220,13 @@ void WebPageProxy::clearServiceWorkerEntitlementOverride(CompletionHandler<void(
 #if ENABLE(APP_BOUND_DOMAINS) && !PLATFORM(MACCATALYST)
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     sendWithAsyncReply(Messages::WebPage::ClearServiceWorkerEntitlementOverride(), [callbackAggregator] { });
-    websiteDataStore().networkProcess().sendWithAsyncReply(Messages::NetworkProcess::ClearServiceWorkerEntitlementOverride(), [callbackAggregator] { });
+    if (auto* networkProcess = m_process->processPool().networkProcess()) {
+        if (!networkProcess->canSendMessage()) {
+            completionHandler();
+            return;
+        }
+        networkProcess->sendWithAsyncReply(Messages::NetworkProcess::ClearServiceWorkerEntitlementOverride(), [callbackAggregator] { });
+    }
 #else
     completionHandler();
 #endif
@@ -4410,7 +4420,7 @@ void WebPageProxy::preconnectTo(const URL& url)
         return;
 
     auto storedCredentialsPolicy = m_canUseCredentialStorage ? WebCore::StoredCredentialsPolicy::Use : WebCore::StoredCredentialsPolicy::DoNotUse;
-    websiteDataStore().networkProcess().preconnectTo(sessionID(), identifier(), webPageID(), url, userAgent(), storedCredentialsPolicy, isNavigatingToAppBoundDomain());
+    m_process->processPool().ensureNetworkProcess().preconnectTo(sessionID(), identifier(), webPageID(), url, userAgent(), storedCredentialsPolicy, isNavigatingToAppBoundDomain());
 }
 
 void WebPageProxy::setCanUseCredentialStorage(bool canUseCredentialStorage)
@@ -4706,7 +4716,7 @@ void WebPageProxy::didCommitLoadForFrame(FrameIdentifier frameID, FrameInfoData&
             RegistrableDomain currentDomain { currentRequest.url() };
             URL requesterURL { URL(), requesterOrigin.toString() };
             if (!currentDomain.matches(requesterURL))
-                m_websiteDataStore->networkProcess().didCommitCrossSiteLoadWithDataTransfer(m_websiteDataStore->sessionID(), RegistrableDomain { requesterURL }, currentDomain, navigationDataTransfer, m_identifier, m_webPageID);
+                m_process->processPool().didCommitCrossSiteLoadWithDataTransfer(m_websiteDataStore->sessionID(), RegistrableDomain { requesterURL }, currentDomain, navigationDataTransfer, m_identifier, m_webPageID);
         }
 #endif
     }
@@ -4744,7 +4754,7 @@ void WebPageProxy::didCommitLoadForFrame(FrameIdentifier frameID, FrameInfoData&
     if (navigation && frame->isMainFrame()) {
         if (auto& adClickAttribution = navigation->adClickAttribution()) {
             if (adClickAttribution->destination().matches(frame->url()))
-                websiteDataStore().networkProcess().send(Messages::NetworkProcess::StoreAdClickAttribution(m_websiteDataStore->sessionID(), *adClickAttribution), 0);
+                m_process->processPool().sendToNetworkingProcess(Messages::NetworkProcess::StoreAdClickAttribution(m_websiteDataStore->sessionID(), *adClickAttribution));
         }
     }
 
@@ -5358,7 +5368,7 @@ void WebPageProxy::logFrameNavigation(const WebFrameProxy& frame, const URL& pag
     if (targetHost.isEmpty() || mainFrameHost.isEmpty() || targetHost == sourceURL.host())
         return;
 
-    websiteDataStore().networkProcess().send(Messages::NetworkProcess::LogFrameNavigation(m_websiteDataStore->sessionID(), RegistrableDomain { targetURL }, RegistrableDomain { pageURL }, RegistrableDomain { sourceURL }, isRedirect, frame.isMainFrame(), MonotonicTime::now() - m_didFinishDocumentLoadForMainFrameTimestamp, wasPotentiallyInitiatedByUser), 0);
+    m_process->processPool().sendToNetworkingProcess(Messages::NetworkProcess::LogFrameNavigation(m_websiteDataStore->sessionID(), RegistrableDomain { targetURL }, RegistrableDomain { pageURL }, RegistrableDomain { sourceURL }, isRedirect, frame.isMainFrame(), MonotonicTime::now() - m_didFinishDocumentLoadForMainFrameTimestamp, wasPotentiallyInitiatedByUser));
 }
 #endif
 
@@ -9983,27 +9993,58 @@ void WebPageProxy::systemPreviewActionTriggered(const WebCore::SystemPreviewInfo
 
 void WebPageProxy::dumpAdClickAttribution(CompletionHandler<void(const String&)>&& completionHandler)
 {
-    websiteDataStore().networkProcess().sendWithAsyncReply(Messages::NetworkProcess::DumpAdClickAttribution(m_websiteDataStore->sessionID()), WTFMove(completionHandler));
+    if (auto* networkProcess = m_process->processPool().networkProcess()) {
+        if (!networkProcess->canSendMessage()) {
+            completionHandler(emptyString());
+            return;
+        }
+        networkProcess->sendWithAsyncReply(Messages::NetworkProcess::DumpAdClickAttribution(m_websiteDataStore->sessionID()), WTFMove(completionHandler));
+    }
 }
 
 void WebPageProxy::clearAdClickAttribution(CompletionHandler<void()>&& completionHandler)
 {
-    websiteDataStore().networkProcess().sendWithAsyncReply(Messages::NetworkProcess::ClearAdClickAttribution(m_websiteDataStore->sessionID()), WTFMove(completionHandler));
+    if (auto* networkProcess = m_process->processPool().networkProcess()) {
+        if (!networkProcess->canSendMessage()) {
+            completionHandler();
+            return;
+        }
+        networkProcess->sendWithAsyncReply(Messages::NetworkProcess::ClearAdClickAttribution(m_websiteDataStore->sessionID()), WTFMove(completionHandler));
+    } else
+        completionHandler();
 }
 
 void WebPageProxy::setAdClickAttributionOverrideTimerForTesting(bool value, CompletionHandler<void()>&& completionHandler)
 {
-    websiteDataStore().networkProcess().sendWithAsyncReply(Messages::NetworkProcess::SetAdClickAttributionOverrideTimerForTesting(m_websiteDataStore->sessionID(), value), WTFMove(completionHandler));
+    if (auto* networkProcess = m_process->processPool().networkProcess()) {
+        if (!networkProcess->canSendMessage()) {
+            completionHandler();
+            return;
+        }
+        networkProcess->sendWithAsyncReply(Messages::NetworkProcess::SetAdClickAttributionOverrideTimerForTesting(m_websiteDataStore->sessionID(), value), WTFMove(completionHandler));
+    }
 }
 
 void WebPageProxy::setAdClickAttributionConversionURLForTesting(const URL& url, CompletionHandler<void()>&& completionHandler)
 {
-    websiteDataStore().networkProcess().sendWithAsyncReply(Messages::NetworkProcess::SetAdClickAttributionConversionURLForTesting(m_websiteDataStore->sessionID(), url), WTFMove(completionHandler));
+    if (auto* networkProcess = m_process->processPool().networkProcess()) {
+        if (!networkProcess->canSendMessage()) {
+            completionHandler();
+            return;
+        }
+        networkProcess->sendWithAsyncReply(Messages::NetworkProcess::SetAdClickAttributionConversionURLForTesting(m_websiteDataStore->sessionID(), url), WTFMove(completionHandler));
+    }
 }
 
 void WebPageProxy::markAdClickAttributionsAsExpiredForTesting(CompletionHandler<void()>&& completionHandler)
 {
-    websiteDataStore().networkProcess().sendWithAsyncReply(Messages::NetworkProcess::MarkAdClickAttributionsAsExpiredForTesting(m_websiteDataStore->sessionID()), WTFMove(completionHandler));
+    if (auto* networkProcess = m_process->processPool().networkProcess()) {
+        if (!networkProcess->canSendMessage()) {
+            completionHandler();
+            return;
+        }
+        networkProcess->sendWithAsyncReply(Messages::NetworkProcess::MarkAdClickAttributionsAsExpiredForTesting(m_websiteDataStore->sessionID()), WTFMove(completionHandler));
+    }
 }
 
 #if ENABLE(SPEECH_SYNTHESIS)
index 71f1f63..d926b33 100644 (file)
@@ -45,6 +45,7 @@
 #include "LegacyGlobalSettings.h"
 #include "LogInitialization.h"
 #include "Logging.h"
+#include "NetworkProcessConnectionInfo.h"
 #include "NetworkProcessCreationParameters.h"
 #include "NetworkProcessMessages.h"
 #include "NetworkProcessProxy.h"
 #endif
 
 #define WEBPROCESSPOOL_RELEASE_LOG(channel, fmt, ...) RELEASE_LOG(channel, "%p - WebProcessPool::" fmt, this, ##__VA_ARGS__)
-#define WEBPROCESSPOOL_RELEASE_LOG_STATIC(channel, fmt, ...) RELEASE_LOG(channel, "WebProcessPool::" fmt, ##__VA_ARGS__)
 #define WEBPROCESSPOOL_RELEASE_LOG_ERROR(channel, fmt, ...) RELEASE_LOG_ERROR(channel, "%p - WebProcessPool::" fmt, this, ##__VA_ARGS__)
 #define WEBPROCESSPOOL_RELEASE_LOG_IF_ALLOWED(channel, fmt, ...) RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), channel, "%p - WebProcessPool::" fmt, this, ##__VA_ARGS__)
-#define WEBPROCESSPOOL_RELEASE_LOG_IF_ALLOWED_STATIC(channel, fmt, ...) RELEASE_LOG_IF(sessionID.isAlwaysOnLoggingAllowed(), channel, "WebProcessPool::" fmt, ##__VA_ARGS__)
 
 namespace WebKit {
 using namespace WebCore;
@@ -233,11 +232,6 @@ static HashSet<String, ASCIICaseInsensitiveHash>& globalURLSchemesWithCustomProt
     return set;
 }
 
-Vector<String> WebProcessPool::urlSchemesWithCustomProtocolHandlers()
-{
-    return copyToVector(globalURLSchemesWithCustomProtocolHandlers());
-}
-
 WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration)
     : m_configuration(configuration.copy())
     , m_defaultPageGroup(WebPageGroup::create())
@@ -245,6 +239,7 @@ WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration)
     , m_automationClient(makeUnique<API::AutomationClient>())
     , m_downloadClient(makeUniqueRef<API::DownloadClient>())
     , m_historyClient(makeUnique<API::LegacyContextHistoryClient>())
+    , m_customProtocolManagerClient(makeUnique<API::CustomProtocolManagerClient>())
     , m_visitedLinkStore(VisitedLinkStore::create())
 #if PLATFORM(MAC)
     , m_highPerformanceGraphicsUsageSampler(makeUnique<HighPerformanceGraphicsUsageSampler>(*this))
@@ -272,6 +267,9 @@ WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration)
 #endif
     });
 
+    if (!m_websiteDataStore && WebKit::WebsiteDataStore::defaultDataStoreExists())
+        m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore();
+
     for (auto& scheme : m_configuration->alwaysRevalidatedURLSchemes())
         m_schemesToRegisterAsAlwaysRevalidated.add(scheme);
 
@@ -287,6 +285,7 @@ WebProcessPool::WebProcessPool(API::ProcessPoolConfiguration& configuration)
     addMessageReceiver(Messages::WebProcessPool::messageReceiverName(), *this);
 
     // NOTE: These sub-objects must be initialized after m_messageReceiverMap..
+    addSupplement<WebCookieManagerProxy>();
     addSupplement<WebGeolocationManagerProxy>();
     addSupplement<WebNotificationManagerProxy>();
 #if ENABLE(MEDIA_SESSION)
@@ -343,6 +342,9 @@ WebProcessPool::~WebProcessPool()
     processPoolCounter.decrement();
 #endif
 
+    if (m_networkProcess)
+        m_networkProcess->shutDownProcess();
+
 #if ENABLE(GAMEPAD)
     if (!m_processesUsingGamepads.isEmpty())
         UIGamepadProvider::singleton().processPoolStoppedUsingGamepads(*this);
@@ -400,6 +402,16 @@ void WebProcessPool::setAutomationClient(std::unique_ptr<API::AutomationClient>&
         m_automationClient = WTFMove(automationClient);
 }
 
+void WebProcessPool::setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&& customProtocolManagerClient)
+{
+#if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
+    if (!customProtocolManagerClient)
+        m_customProtocolManagerClient = makeUnique<API::CustomProtocolManagerClient>();
+    else
+        m_customProtocolManagerClient = WTFMove(customProtocolManagerClient);
+#endif
+}
+
 void WebProcessPool::setCustomWebContentServiceBundleIdentifier(const String& customWebContentServiceBundleIdentifier)
 {
     // Guard against API misuse.
@@ -409,6 +421,11 @@ void WebProcessPool::setCustomWebContentServiceBundleIdentifier(const String& cu
     m_configuration->setCustomWebContentServiceBundleIdentifier(customWebContentServiceBundleIdentifier);
 }
 
+IPC::Connection* WebProcessPool::networkingProcessConnection()
+{
+    return m_networkProcess->connection();
+}
+
 void WebProcessPool::languageChanged(void* context)
 {
     static_cast<WebProcessPool*>(context)->languageChanged();
@@ -418,7 +435,8 @@ void WebProcessPool::languageChanged()
 {
     sendToAllProcesses(Messages::WebProcess::UserPreferredLanguagesChanged());
 #if USE(SOUP)
-    WebsiteDataStore::defaultDataStore()->networkProcess().send(Messages::NetworkProcess::UserPreferredLanguagesChanged(userPreferredLanguages()), 0);
+    if (m_networkProcess)
+        m_networkProcess->send(Messages::NetworkProcess::UserPreferredLanguagesChanged(userPreferredLanguages()), 0);
 #endif
 }
 
@@ -431,8 +449,7 @@ void WebProcessPool::fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnable
 void WebProcessPool::sendMemoryPressureEvent(bool isCritical)
 {
     sendToAllProcesses(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
-    for (auto networkProcess : NetworkProcessProxy::allNetworkProcesses())
-        networkProcess->send(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical), 0);
+    sendToNetworkingProcess(Messages::AuxiliaryProcess::DidReceiveMemoryPressureEvent(isCritical));
 #if ENABLE(NETSCAPE_PLUGIN_API)
     PluginProcessManager::singleton().sendMemoryPressureEvent(isCritical);
 #endif
@@ -457,8 +474,275 @@ void WebProcessPool::screenPropertiesStateChanged()
 #endif
 }
 
+NetworkProcessProxy& WebProcessPool::ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore)
+{
+    ASSERT(RunLoop::isMain());
+    
+    // FIXME: This is a temporary workaround for apps using WebKit API on non-main threads.
+    // We should remove this once we enforce threading violation check on our APIs.
+    // https://bugs.webkit.org/show_bug.cgi?id=200246.
+    if (!RunLoop::isMain()) {
+        callOnMainRunLoopAndWait([this, protectedThis = makeRef(*this)] {
+            ensureNetworkProcess();
+        });
+        return *m_networkProcess;
+    }
+
+    if (m_networkProcess) {
+        if (withWebsiteDataStore) {
+            m_networkProcess->addSession(makeRef(*withWebsiteDataStore));
+            withWebsiteDataStore->clearPendingCookies();
+        }
+        return *m_networkProcess;
+    }
+
+    auto networkProcess = makeUnique<NetworkProcessProxy>(*this);
+
+    NetworkProcessCreationParameters parameters;
+
+    if (m_websiteDataStore) {
+        parameters.defaultDataStoreParameters.pendingCookies = copyToVector(m_websiteDataStore->pendingCookies());
+        m_websiteDataStore->clearPendingCookies();
+#if PLATFORM(COCOA)
+        parameters.defaultDataStoreParameters.networkSessionParameters.sourceApplicationBundleIdentifier = m_websiteDataStore->configuration().sourceApplicationBundleIdentifier();
+        parameters.defaultDataStoreParameters.networkSessionParameters.sourceApplicationSecondaryIdentifier = m_websiteDataStore->configuration().sourceApplicationSecondaryIdentifier();
+#endif
+    }
+
+    parameters.cacheModel = LegacyGlobalSettings::singleton().cacheModel();
+
+    for (auto& scheme : globalURLSchemesWithCustomProtocolHandlers())
+        parameters.urlSchemesRegisteredForCustomProtocols.append(scheme);
+
+#if PLATFORM(IOS_FAMILY)
+    String cookieStorageDirectory = WebProcessPool::cookieStorageDirectory();
+    if (!cookieStorageDirectory.isEmpty())
+        SandboxExtension::createHandleForReadWriteDirectory(cookieStorageDirectory, parameters.cookieStorageDirectoryExtensionHandle);
+
+    String containerCachesDirectory = WebProcessPool::networkingCachesDirectory();
+    if (!containerCachesDirectory.isEmpty())
+        SandboxExtension::createHandleForReadWriteDirectory(containerCachesDirectory, parameters.containerCachesDirectoryExtensionHandle);
+
+    String parentBundleDirectory = WebProcessPool::parentBundleDirectory();
+    if (!parentBundleDirectory.isEmpty())
+        SandboxExtension::createHandle(parentBundleDirectory, SandboxExtension::Type::ReadOnly, parameters.parentBundleDirectoryExtensionHandle);
+
+#if ENABLE(INDEXED_DATABASE)
+    SandboxExtension::createHandleForTemporaryFile(emptyString(), SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.indexedDatabaseTempBlobDirectoryExtensionHandle);
+#endif
+#endif
+
+    parameters.urlSchemesRegisteredAsSecure = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsSecure());
+    parameters.urlSchemesRegisteredAsBypassingContentSecurityPolicy = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsBypassingContentSecurityPolicy());
+    parameters.urlSchemesRegisteredAsLocal = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsLocal());
+    parameters.urlSchemesRegisteredAsNoAccess = copyToVector(LegacyGlobalSettings::singleton().schemesToRegisterAsNoAccess());
+
+#if ENABLE(INDEXED_DATABASE)
+    // *********
+    // IMPORTANT: Do not change the directory structure for indexed databases on disk without first consulting a reviewer from Apple (<rdar://problem/17454712>)
+    // *********
+    if (m_websiteDataStore)
+        parameters.defaultDataStoreParameters.indexedDatabaseDirectory = m_websiteDataStore->resolvedIndexedDatabaseDirectory();
+    else if (WebKit::WebsiteDataStore::defaultDataStoreExists())
+        parameters.defaultDataStoreParameters.indexedDatabaseDirectory = WebKit::WebsiteDataStore::defaultDataStore()->parameters().indexedDatabaseDirectory;
+    
+    if (!parameters.defaultDataStoreParameters.indexedDatabaseDirectory.isEmpty()) {
+        SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.indexedDatabaseDirectory, parameters.defaultDataStoreParameters.indexedDatabaseDirectoryExtensionHandle);
+        networkProcess->createSymLinkForFileUpgrade(parameters.defaultDataStoreParameters.indexedDatabaseDirectory);
+    }
+#endif
+
+#if ENABLE(SERVICE_WORKER)
+    if (m_websiteDataStore)
+        parameters.serviceWorkerRegistrationDirectory = m_websiteDataStore->resolvedServiceWorkerRegistrationDirectory();
+    if (!parameters.serviceWorkerRegistrationDirectory)
+        parameters.serviceWorkerRegistrationDirectory =  WebKit::WebsiteDataStore::defaultServiceWorkerRegistrationDirectory();
+    SandboxExtension::createHandleForReadWriteDirectory(parameters.serviceWorkerRegistrationDirectory, parameters.serviceWorkerRegistrationDirectoryExtensionHandle);
+#endif
+
+    auto localStorageDirectory = m_websiteDataStore ? m_websiteDataStore->resolvedLocalStorageDirectory() : nullString();
+    if (!localStorageDirectory)
+        localStorageDirectory = WebKit::WebsiteDataStore::defaultLocalStorageDirectory();
+    parameters.defaultDataStoreParameters.localStorageDirectory = localStorageDirectory;
+    SandboxExtension::createHandleForReadWriteDirectory(localStorageDirectory, parameters.defaultDataStoreParameters.localStorageDirectoryExtensionHandle);
+
+    auto cacheStorageDirectory = m_websiteDataStore ? m_websiteDataStore->cacheStorageDirectory() : nullString();
+    if (!cacheStorageDirectory.isEmpty()) {
+        SandboxExtension::createHandleForReadWriteDirectory(cacheStorageDirectory, parameters.defaultDataStoreParameters.cacheStorageDirectoryExtensionHandle);
+        parameters.defaultDataStoreParameters.cacheStorageDirectory = WTFMove(cacheStorageDirectory);
+    }
+
+    String resourceLoadStatisticsDirectory;
+    SandboxExtension::Handle resourceLoadStatisticsDirectoryExtensionHandle;
+    if (m_websiteDataStore)
+        resourceLoadStatisticsDirectory = m_websiteDataStore->resolvedResourceLoadStatisticsDirectory();
+    else if (WebKit::WebsiteDataStore::defaultDataStoreExists())
+        resourceLoadStatisticsDirectory = WebKit::WebsiteDataStore::defaultDataStore()->parameters().networkSessionParameters.resourceLoadStatisticsParameters.directory;
+    
+    if (!resourceLoadStatisticsDirectory.isEmpty())
+        SandboxExtension::createHandleForReadWriteDirectory(resourceLoadStatisticsDirectory, resourceLoadStatisticsDirectoryExtensionHandle);
+
+    bool enableResourceLoadStatistics = false;
+    bool enableResourceLoadStatisticsLogTestingEvent = false;
+    bool shouldIncludeLocalhost = true;
+    bool enableResourceLoadStatisticsDebugMode = false;
+#if ENABLE(RESOURCE_LOAD_STATISTICS)
+    WebCore::ThirdPartyCookieBlockingMode thirdPartyCookieBlockingMode = WebCore::ThirdPartyCookieBlockingMode::All;
+    WebCore::SameSiteStrictEnforcementEnabled sameSiteStrictEnforcementEnabled = WebCore::SameSiteStrictEnforcementEnabled::No;
+#endif
+    WebCore::FirstPartyWebsiteDataRemovalMode firstPartyWebsiteDataRemovalMode = WebCore::FirstPartyWebsiteDataRemovalMode::AllButCookies;
+    WebCore::RegistrableDomain standaloneApplicationDomain;
+    HashSet<WebCore::RegistrableDomain> appBoundDomains;
+    WebCore::RegistrableDomain manualPrevalentResource;
+
+#if PLATFORM(COCOA)
+    m_tccPreferenceEnabled = doesAppHaveITPEnabled();
+    if (withWebsiteDataStore && !withWebsiteDataStore->isItpStateExplicitlySet()) {
+        enableResourceLoadStatistics = m_tccPreferenceEnabled;
+        withWebsiteDataStore->setResourceLoadStatisticsEnabled(enableResourceLoadStatistics);
+    } else if (m_websiteDataStore && !m_websiteDataStore->isItpStateExplicitlySet()) {
+        enableResourceLoadStatistics = m_tccPreferenceEnabled;
+        m_websiteDataStore->setResourceLoadStatisticsEnabled(enableResourceLoadStatistics);
+    } else if (WebsiteDataStore::defaultDataStoreExists() && !WebsiteDataStore::defaultDataStore()->isItpStateExplicitlySet()) {
+        enableResourceLoadStatistics = m_tccPreferenceEnabled;
+        WebsiteDataStore::defaultDataStore()->setResourceLoadStatisticsEnabled(enableResourceLoadStatistics);
+    } else
+        enableResourceLoadStatistics = m_tccPreferenceEnabled;
+#endif
+
+    if (withWebsiteDataStore) {
+        enableResourceLoadStatistics = withWebsiteDataStore->resourceLoadStatisticsEnabled();
+#if ENABLE(RESOURCE_LOAD_STATISTICS)
+        enableResourceLoadStatisticsLogTestingEvent = withWebsiteDataStore->hasStatisticsTestingCallback();
+#endif
+        if (enableResourceLoadStatistics) {
+            auto networkSessionParameters = withWebsiteDataStore->parameters().networkSessionParameters;
+            shouldIncludeLocalhost = networkSessionParameters.resourceLoadStatisticsParameters.shouldIncludeLocalhost;
+            enableResourceLoadStatisticsDebugMode = networkSessionParameters.resourceLoadStatisticsParameters.enableDebugMode;
+#if ENABLE(RESOURCE_LOAD_STATISTICS)
+            thirdPartyCookieBlockingMode = networkSessionParameters.resourceLoadStatisticsParameters.thirdPartyCookieBlockingMode;
+            sameSiteStrictEnforcementEnabled = networkSessionParameters.resourceLoadStatisticsParameters.sameSiteStrictEnforcementEnabled;
+#endif
+            firstPartyWebsiteDataRemovalMode = networkSessionParameters.resourceLoadStatisticsParameters.firstPartyWebsiteDataRemovalMode;
+            standaloneApplicationDomain = networkSessionParameters.resourceLoadStatisticsParameters.standaloneApplicationDomain;
+            appBoundDomains = networkSessionParameters.resourceLoadStatisticsParameters.appBoundDomains;
+            manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsParameters.manualPrevalentResource;
+        }
+
+        parameters.defaultDataStoreParameters.perOriginStorageQuota = withWebsiteDataStore->perOriginStorageQuota();
+        parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = withWebsiteDataStore->perThirdPartyOriginStorageQuota();
+        
+        const auto& networkCacheDirectory = withWebsiteDataStore->resolvedNetworkCacheDirectory();
+        if (!networkCacheDirectory.isNull()) {
+            parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
+            SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
+        }
+
+        const auto& hstsStorageDirectory = withWebsiteDataStore->resolvedHSTSStorageDirectory();
+        if (!hstsStorageDirectory.isNull()) {
+            parameters.defaultDataStoreParameters.networkSessionParameters.hstsStorageDirectory = hstsStorageDirectory;
+            SandboxExtension::createHandle(hstsStorageDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.hstsStorageDirectoryExtensionHandle);
+        }
+    } else if (m_websiteDataStore) {
+        enableResourceLoadStatistics = m_websiteDataStore->resourceLoadStatisticsEnabled();
+#if ENABLE(RESOURCE_LOAD_STATISTICS)
+        enableResourceLoadStatisticsLogTestingEvent = m_websiteDataStore->hasStatisticsTestingCallback();
+#endif
+        if (enableResourceLoadStatistics) {
+            auto networkSessionParameters = m_websiteDataStore->parameters().networkSessionParameters;
+            shouldIncludeLocalhost = networkSessionParameters.resourceLoadStatisticsParameters.shouldIncludeLocalhost;
+            enableResourceLoadStatisticsDebugMode = networkSessionParameters.resourceLoadStatisticsParameters.enableDebugMode;
+#if ENABLE(RESOURCE_LOAD_STATISTICS)
+            thirdPartyCookieBlockingMode = networkSessionParameters.resourceLoadStatisticsParameters.thirdPartyCookieBlockingMode;
+            sameSiteStrictEnforcementEnabled = networkSessionParameters.resourceLoadStatisticsParameters.sameSiteStrictEnforcementEnabled;
+#endif
+            firstPartyWebsiteDataRemovalMode = networkSessionParameters.resourceLoadStatisticsParameters.firstPartyWebsiteDataRemovalMode;
+            standaloneApplicationDomain = networkSessionParameters.resourceLoadStatisticsParameters.standaloneApplicationDomain;
+            appBoundDomains = networkSessionParameters.resourceLoadStatisticsParameters.appBoundDomains;
+            manualPrevalentResource = networkSessionParameters.resourceLoadStatisticsParameters.manualPrevalentResource;
+        }
+
+        parameters.defaultDataStoreParameters.perOriginStorageQuota = m_websiteDataStore->perOriginStorageQuota();
+        parameters.defaultDataStoreParameters.perThirdPartyOriginStorageQuota = m_websiteDataStore->perThirdPartyOriginStorageQuota();
+
+        const auto& networkCacheDirectory = m_websiteDataStore->resolvedNetworkCacheDirectory();
+        if (!networkCacheDirectory.isNull()) {
+            parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
+            SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
+        }
+
+        const auto& hstsStorageDirectory = m_websiteDataStore->resolvedHSTSStorageDirectory();
+        if (!hstsStorageDirectory.isNull()) {
+            parameters.defaultDataStoreParameters.networkSessionParameters.hstsStorageDirectory = hstsStorageDirectory;
+            SandboxExtension::createHandle(hstsStorageDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.hstsStorageDirectoryExtensionHandle);
+        }
+    } else {
+        if (WebsiteDataStore::defaultDataStoreExists())
+            enableResourceLoadStatistics = WebsiteDataStore::defaultDataStore()->resourceLoadStatisticsEnabled();
+        auto networkCacheDirectory = WebsiteDataStore::defaultNetworkCacheDirectory();
+        parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectory = networkCacheDirectory;
+        SandboxExtension::createHandle(networkCacheDirectory, SandboxExtension::Type::ReadWrite, parameters.defaultDataStoreParameters.networkSessionParameters.networkCacheDirectoryExtensionHandle);
+    }
+
+#if HAVE(CFNETWORK_ALTERNATIVE_SERVICE)
+    if (WebsiteDataStore::http3Enabled()) {
+        parameters.defaultDataStoreParameters.networkSessionParameters.alternativeServiceDirectory = WebsiteDataStore::defaultAlternativeServicesDirectory();
+        if (!parameters.defaultDataStoreParameters.networkSessionParameters.alternativeServiceDirectory.isEmpty())
+            SandboxExtension::createHandleForReadWriteDirectory(parameters.defaultDataStoreParameters.networkSessionParameters.alternativeServiceDirectory, parameters.defaultDataStoreParameters.networkSessionParameters.alternativeServiceDirectoryExtensionHandle);
+        parameters.defaultDataStoreParameters.networkSessionParameters.http3Enabled = true;
+    }
+#endif
+    bool isItpStateExplicitlySet = false;
+    parameters.defaultDataStoreParameters.networkSessionParameters.resourceLoadStatisticsParameters = ResourceLoadStatisticsParameters {
+        WTFMove(resourceLoadStatisticsDirectory),
+        WTFMove(resourceLoadStatisticsDirectoryExtensionHandle),
+        enableResourceLoadStatistics,
+        isItpStateExplicitlySet,
+        enableResourceLoadStatisticsLogTestingEvent,
+        shouldIncludeLocalhost,
+        enableResourceLoadStatisticsDebugMode,
+#if ENABLE(RESOURCE_LOAD_STATISTICS)
+        thirdPartyCookieBlockingMode,
+        sameSiteStrictEnforcementEnabled,
+#endif
+        firstPartyWebsiteDataRemovalMode,
+        standaloneApplicationDomain,
+        appBoundDomains,
+        manualPrevalentResource,
+    };
+
+    // Add any platform specific parameters
+    platformInitializeNetworkProcess(parameters);
+
+    // Initialize the network process.
+    networkProcess->send(Messages::NetworkProcess::InitializeNetworkProcess(parameters), 0);
+
+#if PLATFORM(COCOA)
+    networkProcess->send(Messages::NetworkProcess::SetQOS(networkProcessLatencyQOS(), networkProcessThroughputQOS()), 0);
+#endif
+
+    networkProcess->updateProcessAssertion();
+
+    if (withWebsiteDataStore) {
+        networkProcess->addSession(makeRef(*withWebsiteDataStore));
+        withWebsiteDataStore->clearPendingCookies();
+    }
+
+    // Make sure the network process knows about all the sessions that have been registered before it started.
+    for (auto& sessionID : m_sessionToPageIDsMap.keys()) {
+        if (auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID))
+            networkProcess->addSession(*websiteDataStore);
+    }
+
+    m_networkProcess = WTFMove(networkProcess);
+    return *m_networkProcess;
+}
+
 void WebProcessPool::networkProcessCrashed(NetworkProcessProxy& networkProcessProxy)
 {
+    ASSERT(m_networkProcess);
+    ASSERT(&networkProcessProxy == m_networkProcess.get());
+
     for (auto& supplement : m_supplements.values())
         supplement->processDidClose(&networkProcessProxy);
 
@@ -467,6 +751,9 @@ void WebProcessPool::networkProcessCrashed(NetworkProcessProxy& networkProcessPr
     if (m_automationSession)
         m_automationSession->terminate();
 
+    // Leave the process proxy around during client call, so that the client could query the process identifier.
+    m_networkProcess = nullptr;
+
     terminateServiceWorkers();
 }
 
@@ -477,6 +764,20 @@ void WebProcessPool::serviceWorkerProcessCrashed(WebProcessProxy& proxy)
 #endif
 }
 
+void WebProcessPool::getNetworkProcessConnection(WebProcessProxy& webProcessProxy, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
+{
+    ensureNetworkProcess();
+    m_networkProcess->getNetworkProcessConnection(webProcessProxy, [this, weakThis = makeWeakPtr(*this), webProcessProxy = makeWeakPtr(webProcessProxy), reply = WTFMove(reply)] (auto& connectionInfo) mutable {
+        if (UNLIKELY(!IPC::Connection::identifierIsValid(connectionInfo.identifier()) && webProcessProxy && weakThis)) {
+            WEBPROCESSPOOL_RELEASE_LOG_ERROR(Process, "getNetworkProcessConnection: Failed first attempt, retrying");
+            ensureNetworkProcess();
+            m_networkProcess->getNetworkProcessConnection(*webProcessProxy, WTFMove(reply));
+            return;
+        }
+        reply(connectionInfo);
+    });
+}
+
 #if ENABLE(GPU_PROCESS)
 void WebProcessPool::gpuProcessCrashed(ProcessID identifier)
 {
@@ -500,26 +801,23 @@ void WebProcessPool::getGPUProcessConnection(WebProcessProxy& webProcessProxy, M
 }
 #endif
 
-bool WebProcessPool::s_useSeparateServiceWorkerProcess = false;
-
 #if ENABLE(SERVICE_WORKER)
 void WebProcessPool::establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy& proxy, RegistrableDomain&& registrableDomain, PAL::SessionID sessionID, CompletionHandler<void()>&& completionHandler)
 {
-    auto* websiteDataStore = WebsiteDataStore::existingDataStoreForSessionID(sessionID);
-    if (!websiteDataStore)
-        websiteDataStore = WebsiteDataStore::defaultDataStore().ptr();
-    if (!processPools().size())
-        static NeverDestroyed<Ref<WebProcessPool>> serviceWorkerProcessPool(WebProcessPool::create(API::ProcessPoolConfiguration::create().get()));
+    ASSERT_UNUSED(proxy, &proxy == m_networkProcess.get());
 
-    // Arbitrarily choose the first process pool to host the service worker process.
-    auto* processPool = processPools()[0];
-    ASSERT(processPool);
+    auto* websiteDataStore = WebsiteDataStore::existingNonDefaultDataStoreForSessionID(sessionID);
 
-    WebProcessProxy* serviceWorkerProcessProxy { nullptr };
+    if (!websiteDataStore) {
+        if (!m_websiteDataStore)
+            m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore().ptr();
+        websiteDataStore = m_websiteDataStore.get();
+    }
 
-    if (!s_useSeparateServiceWorkerProcess) {
-        for (auto& process : processPool->m_processes) {
-            if (process == processPool->m_prewarmedProcess || process->isDummyProcessProxy())
+    WebProcessProxy* serviceWorkerProcessProxy { nullptr };
+    if (!m_useSeparateServiceWorkerProcess) {
+        for (auto& process : m_processes) {
+            if (process == m_prewarmedProcess || process->isDummyProcessProxy())
                 continue;
             if (&process->websiteDataStore() != websiteDataStore)
                 continue;
@@ -527,35 +825,35 @@ void WebProcessPool::establishWorkerContextConnectionToNetworkProcess(NetworkPro
                 continue;
 
             serviceWorkerProcessProxy = process.get();
-            serviceWorkerProcessProxy->enableServiceWorkers(processPool->userContentControllerIdentifierForServiceWorkers());
+            serviceWorkerProcessProxy->enableServiceWorkers(userContentControllerIdentifierForServiceWorkers());
 
-            WEBPROCESSPOOL_RELEASE_LOG_IF_ALLOWED_STATIC(ServiceWorker, "establishWorkerContextConnectionToNetworkProcess reusing an existing web process (process=%p, PID=%d)", serviceWorkerProcessProxy, serviceWorkerProcessProxy->processIdentifier());
+            WEBPROCESSPOOL_RELEASE_LOG_IF_ALLOWED(ServiceWorker, "establishWorkerContextConnectionToNetworkProcess reusing an existing web process (process=%p, PID=%d)", serviceWorkerProcessProxy, serviceWorkerProcessProxy->processIdentifier());
             break;
         }
     }
 
     if (!serviceWorkerProcessProxy) {
-        auto newProcessProxy = WebProcessProxy::createForServiceWorkers(*processPool, WTFMove(registrableDomain), *websiteDataStore);
+        auto newProcessProxy = WebProcessProxy::createForServiceWorkers(*this, WTFMove(registrableDomain), *websiteDataStore);
         serviceWorkerProcessProxy = newProcessProxy.ptr();
 
-        WEBPROCESSPOOL_RELEASE_LOG_IF_ALLOWED_STATIC(ServiceWorker, "establishWorkerContextConnectionToNetworkProcess creating a new service worker process (proces=%p, PID=%d)", serviceWorkerProcessProxy, serviceWorkerProcessProxy->processIdentifier());
+        WEBPROCESSPOOL_RELEASE_LOG_IF_ALLOWED(ServiceWorker, "establishWorkerContextConnectionToNetworkProcess creating a new service worker process (proces=%p, PID=%d)", serviceWorkerProcessProxy, serviceWorkerProcessProxy->processIdentifier());
 
-        processPool->initializeNewWebProcess(newProcessProxy, websiteDataStore);
-        processPool->m_processes.append(WTFMove(newProcessProxy));
+        initializeNewWebProcess(newProcessProxy, websiteDataStore);
+        m_processes.append(WTFMove(newProcessProxy));
     }
 
-    ASSERT(!serviceWorkerProcesses().contains(*serviceWorkerProcessProxy));
-    serviceWorkerProcesses().add(*serviceWorkerProcessProxy);
+    ASSERT(!m_serviceWorkerProcesses.contains(*serviceWorkerProcessProxy));
+    m_serviceWorkerProcesses.add(*serviceWorkerProcessProxy);
 
-    serviceWorkerProcessProxy->establishServiceWorkerContext(processPool->m_serviceWorkerPreferences ? processPool->m_serviceWorkerPreferences.value() : processPool->m_defaultPageGroup->preferences().store(), WTFMove(completionHandler));
-    if (!processPool->m_serviceWorkerUserAgent.isNull())
-        serviceWorkerProcessProxy->setServiceWorkerUserAgent(processPool->m_serviceWorkerUserAgent);
+    serviceWorkerProcessProxy->establishServiceWorkerContext(m_serviceWorkerPreferences ? m_serviceWorkerPreferences.value() : m_defaultPageGroup->preferences().store(), WTFMove(completionHandler));
+    if (!m_serviceWorkerUserAgent.isNull())
+        serviceWorkerProcessProxy->setServiceWorkerUserAgent(m_serviceWorkerUserAgent);
 }
 
 void WebProcessPool::removeFromServiceWorkerProcesses(WebProcessProxy& process)
 {
-    ASSERT(serviceWorkerProcesses().contains(process));
-    serviceWorkerProcesses().remove(process);
+    ASSERT(m_serviceWorkerProcesses.contains(process));
+    m_serviceWorkerProcesses.remove(process);
 }
 #endif
 
@@ -624,7 +922,7 @@ RefPtr<WebProcessProxy> WebProcessPool::tryTakePrewarmedProcess(WebsiteDataStore
 #if PLATFORM(GTK) || PLATFORM(WPE)
     // In platforms using Bubblewrap for sandboxing, prewarmed process is launched using the WebProcessPool primary WebsiteDataStore,
     // so we don't use it in case of using a different WebsiteDataStore.
-    if (m_sandboxEnabled)
+    if (m_sandboxEnabled && m_websiteDataStore && m_websiteDataStore.get() != &websiteDataStore)
         return nullptr;
 #endif
 
@@ -734,6 +1032,8 @@ void WebProcessPool::initializeNewWebProcess(WebProcessProxy& process, WebsiteDa
         process.isResponsive([initializationActivity = WTFMove(initializationActivity)] (bool) { });
     });
 
+    ensureNetworkProcess();
+
     WebProcessCreationParameters parameters;
 
     parameters.injectedBundlePath = m_resolvedPaths.injectedBundlePath;
@@ -898,6 +1198,9 @@ void WebProcessPool::processDidFinishLaunching(WebProcessProxy* process)
         process->connection()->ignoreTimeoutsForTesting();
 
     m_connectionClient.didCreateConnection(this, process->webConnection());
+
+    if (m_websiteDataStore)
+        m_websiteDataStore->didCreateNetworkProcess();
 }
 
 void WebProcessPool::disconnectProcess(WebProcessProxy* process)
@@ -992,7 +1295,10 @@ Ref<WebPageProxy> WebProcessPool::createWebPage(PageClient& pageClient, Ref<API:
     if (!pageConfiguration->websiteDataStore()) {
         // We try to avoid creating the default data store as long as possible.
         // But if there is an attempt to create a web page without any specified data store, then we have to create it.
-        pageConfiguration->setWebsiteDataStore(WebKit::WebsiteDataStore::defaultDataStore().ptr());
+        if (!m_websiteDataStore)
+            m_websiteDataStore = WebKit::WebsiteDataStore::defaultDataStore().ptr();
+
+        pageConfiguration->setWebsiteDataStore(m_websiteDataStore.get());
     }
 
     RefPtr<WebProcessProxy> process;
@@ -1023,7 +1329,7 @@ Ref<WebPageProxy> WebProcessPool::createWebPage(PageClient& pageClient, Ref<API:
 #if ENABLE(SERVICE_WORKER)
     if (!m_serviceWorkerPreferences) {
         m_serviceWorkerPreferences = page->preferencesStore();
-        for (auto& serviceWorkerProcess : serviceWorkerProcesses())
+        for (auto& serviceWorkerProcess : m_serviceWorkerProcesses)
             serviceWorkerProcess.updateServiceWorkerPreferencesStore(*m_serviceWorkerPreferences);
     }
     if (userContentController)
@@ -1050,7 +1356,7 @@ void WebProcessPool::updateServiceWorkerUserAgent(const String& userAgent)
     if (m_serviceWorkerUserAgent == userAgent)
         return;
     m_serviceWorkerUserAgent = userAgent;
-    for (auto& serviceWorkerProcess : serviceWorkerProcesses())
+    for (auto& serviceWorkerProcess : m_serviceWorkerProcesses)
         serviceWorkerProcess.setServiceWorkerUserAgent(m_serviceWorkerUserAgent);
 }
 #endif
@@ -1059,6 +1365,15 @@ void WebProcessPool::pageBeginUsingWebsiteDataStore(WebPageProxyIdentifier pageI
 {
     auto result = m_sessionToPageIDsMap.add(dataStore.sessionID(), HashSet<WebPageProxyIdentifier>()).iterator->value.add(pageID);
     ASSERT_UNUSED(result, result.isNewEntry);
+
+    auto sessionID = dataStore.sessionID();
+    if (sessionID != PAL::SessionID::defaultSessionID()) {
+        ASSERT(!sessionID.isEphemeral() || dataStore.parameters().networkSessionParameters.sessionID == sessionID);
+        if (m_networkProcess) {
+            m_networkProcess->addSession(makeRef(dataStore));
+            dataStore.clearPendingCookies();
+        }
+    }
 }
 
 void WebProcessPool::pageEndUsingWebsiteDataStore(WebPageProxyIdentifier pageID, WebsiteDataStore& dataStore)
@@ -1086,6 +1401,7 @@ bool WebProcessPool::hasPagesUsingWebsiteDataStore(WebsiteDataStore& dataStore)
 DownloadProxy& WebProcessPool::download(WebsiteDataStore& dataStore, WebPageProxy* initiatingPage, const ResourceRequest& request, const String& suggestedFilename)
 {
     auto& downloadProxy = createDownloadProxy(dataStore, request, initiatingPage, { });
+    PAL::SessionID sessionID = dataStore.sessionID();
 
     Optional<NavigatingToAppBoundDomain> isAppBound = NavigatingToAppBoundDomain::No;
     if (initiatingPage) {
@@ -1095,23 +1411,26 @@ DownloadProxy& WebProcessPool::download(WebsiteDataStore& dataStore, WebPageProx
 #endif
     }
 
-    ResourceRequest updatedRequest(request);
-    // Request's firstPartyForCookies will be used as Original URL of the download request.
-    // We set the value to top level document's URL.
-    if (initiatingPage) {
-        URL initiatingPageURL = URL { URL { }, initiatingPage->pageLoadState().url() };
-        updatedRequest.setFirstPartyForCookies(initiatingPageURL);
-        updatedRequest.setIsSameSite(areRegistrableDomainsEqual(initiatingPageURL, request.url()));
-        if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
-            updatedRequest.setHTTPUserAgent(initiatingPage->userAgentForURL(request.url()));
-    } else {
-        updatedRequest.setFirstPartyForCookies(URL());
-        updatedRequest.setIsSameSite(false);
-        if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
-            updatedRequest.setHTTPUserAgent(WebPageProxy::standardUserAgent());
+    if (networkProcess()) {
+        ResourceRequest updatedRequest(request);
+        // Request's firstPartyForCookies will be used as Original URL of the download request.
+        // We set the value to top level document's URL.
+        if (initiatingPage) {
+            URL initiatingPageURL = URL { URL { }, initiatingPage->pageLoadState().url() };
+            updatedRequest.setFirstPartyForCookies(initiatingPageURL);
+            updatedRequest.setIsSameSite(areRegistrableDomainsEqual(initiatingPageURL, request.url()));
+            if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
+                updatedRequest.setHTTPUserAgent(initiatingPage->userAgentForURL(request.url()));
+        } else {
+            updatedRequest.setFirstPartyForCookies(URL());
+            updatedRequest.setIsSameSite(false);
+            if (!updatedRequest.hasHTTPHeaderField(HTTPHeaderName::UserAgent))
+                updatedRequest.setHTTPUserAgent(WebPageProxy::standardUserAgent());
+        }
+        updatedRequest.setIsTopSite(false);
+        networkProcess()->send(Messages::NetworkProcess::DownloadRequest(sessionID, downloadProxy.downloadID(), updatedRequest, isAppBound, suggestedFilename), 0);
+        return downloadProxy;
     }
-    updatedRequest.setIsTopSite(false);
-    dataStore.networkProcess().send(Messages::NetworkProcess::DownloadRequest(dataStore.sessionID(), downloadProxy.downloadID(), updatedRequest, isAppBound, suggestedFilename), 0);
 
     return downloadProxy;
 }
@@ -1119,12 +1438,17 @@ DownloadProxy& WebProcessPool::download(WebsiteDataStore& dataStore, WebPageProx
 DownloadProxy& WebProcessPool::resumeDownload(WebsiteDataStore& dataStore, WebPageProxy* initiatingPage, const API::Data& resumeData, const String& path)
 {
     auto& downloadProxy = createDownloadProxy(dataStore, ResourceRequest(), initiatingPage, { });
+    PAL::SessionID sessionID = dataStore.sessionID();
 
     SandboxExtension::Handle sandboxExtensionHandle;
     if (!path.isEmpty())
         SandboxExtension::createHandle(path, SandboxExtension::Type::ReadWrite, sandboxExtensionHandle);
 
-    dataStore.networkProcess().send(Messages::NetworkProcess::ResumeDownload(dataStore.sessionID(), downloadProxy.downloadID(), resumeData.dataReference(), path, sandboxExtensionHandle), 0);
+    if (networkProcess()) {
+        networkProcess()->send(Messages::NetworkProcess::ResumeDownload(sessionID, downloadProxy.downloadID(), resumeData.dataReference(), path, sandboxExtensionHandle), 0);
+        return downloadProxy;
+    }
+
     return downloadProxy;
 }
 
@@ -1193,6 +1517,11 @@ void WebProcessPool::refreshPlugins()
 
 #endif // ENABLE(NETSCAPE_PLUGIN_API)
 
+ProcessID WebProcessPool::networkProcessIdentifier()
+{
+    return m_networkProcess ? m_networkProcess->processIdentifier() : 0;
+}
+
 ProcessID WebProcessPool::prewarmedProcessIdentifier()
 {
     return m_prewarmedProcess ? m_prewarmedProcess->processIdentifier() : 0;
@@ -1229,18 +1558,14 @@ void WebProcessPool::registerURLSchemeAsSecure(const String& urlScheme)
 {
     LegacyGlobalSettings::singleton().registerURLSchemeAsSecure(urlScheme);
     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsSecure(urlScheme));
-    WebsiteDataStore::forEachWebsiteDataStore([urlScheme] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().send(Messages::NetworkProcess::RegisterURLSchemeAsSecure(urlScheme), 0);
-    });
+    sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsSecure(urlScheme));
 }
 
 void WebProcessPool::registerURLSchemeAsBypassingContentSecurityPolicy(const String& urlScheme)
 {
     LegacyGlobalSettings::singleton().registerURLSchemeAsBypassingContentSecurityPolicy(urlScheme);
     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
-    WebsiteDataStore::forEachWebsiteDataStore([urlScheme] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().send(Messages::NetworkProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme), 0);
-    });
+    sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsBypassingContentSecurityPolicy(urlScheme));
 }
 
 void WebProcessPool::setDomainRelaxationForbiddenForURLScheme(const String& urlScheme)
@@ -1253,18 +1578,14 @@ void WebProcessPool::registerURLSchemeAsLocal(const String& urlScheme)
 {
     LegacyGlobalSettings::singleton().registerURLSchemeAsLocal(urlScheme);
     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsLocal(urlScheme));
-    WebsiteDataStore::forEachWebsiteDataStore([urlScheme] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().send(Messages::NetworkProcess::RegisterURLSchemeAsLocal(urlScheme), 0);
-    });
+    sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsLocal(urlScheme));
 }
 
 void WebProcessPool::registerURLSchemeAsNoAccess(const String& urlScheme)
 {
     LegacyGlobalSettings::singleton().registerURLSchemeAsNoAccess(urlScheme);
     sendToAllProcesses(Messages::WebProcess::RegisterURLSchemeAsNoAccess(urlScheme));
-    WebsiteDataStore::forEachWebsiteDataStore([urlScheme] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().send(Messages::NetworkProcess::RegisterURLSchemeAsNoAccess(urlScheme), 0);
-    });
+    sendToNetworkingProcess(Messages::NetworkProcess::RegisterURLSchemeAsNoAccess(urlScheme));
 }
 
 void WebProcessPool::registerURLSchemeAsDisplayIsolated(const String& urlScheme)
@@ -1285,8 +1606,10 @@ void WebProcessPool::registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const
         return;
 
     globalURLSchemesWithCustomProtocolHandlers().add(urlScheme);
-    for (auto networkProcess : NetworkProcessProxy::allNetworkProcesses())
-        networkProcess->registerSchemeForLegacyCustomProtocol(urlScheme);
+    for (auto* processPool : allProcessPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->registerSchemeForLegacyCustomProtocol(urlScheme);
+    }
 }
 
 void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String& urlScheme)
@@ -1295,8 +1618,10 @@ void WebProcessPool::unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(con
         return;
 
     globalURLSchemesWithCustomProtocolHandlers().remove(urlScheme);
-    for (auto networkProcess : NetworkProcessProxy::allNetworkProcesses())
-        networkProcess->unregisterSchemeForLegacyCustomProtocol(urlScheme);
+    for (auto* processPool : allProcessPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->unregisterSchemeForLegacyCustomProtocol(urlScheme);
+    }
 }
 
 void WebProcessPool::registerURLSchemeAsCachePartitioned(const String& urlScheme)
@@ -1330,18 +1655,16 @@ void WebProcessPool::setCacheModel(CacheModel cacheModel)
 
     sendToAllProcesses(Messages::WebProcess::SetCacheModel(cacheModel));
 
-    WebsiteDataStore::forEachWebsiteDataStore([cacheModel] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().send(Messages::NetworkProcess::SetCacheModel(cacheModel), 0);
-    });
+    if (m_networkProcess)
+        m_networkProcess->send(Messages::NetworkProcess::SetCacheModel(cacheModel), 0);
 }
 
 void WebProcessPool::setCacheModelSynchronouslyForTesting(CacheModel cacheModel)
 {
     updateBackForwardCacheCapacity();
 
-    WebsiteDataStore::forEachWebsiteDataStore([cacheModel] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().sendSync(Messages::NetworkProcess::SetCacheModelSynchronouslyForTesting(cacheModel), { }, 0);
-    });
+    if (m_networkProcess)
+        m_networkProcess->sendSync(Messages::NetworkProcess::SetCacheModelSynchronouslyForTesting(cacheModel), { }, { });
 }
 
 void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval)
@@ -1351,7 +1674,12 @@ void WebProcessPool::setDefaultRequestTimeoutInterval(double timeoutInterval)
 
 DownloadProxy& WebProcessPool::createDownloadProxy(WebsiteDataStore& dataStore, const ResourceRequest& request, WebPageProxy* originatingPage, const FrameInfoData& frameInfo)
 {
-    return dataStore.networkProcess().createDownloadProxy(dataStore, *this, request, frameInfo, originatingPage);
+    return ensureNetworkProcess(&dataStore).createDownloadProxy(dataStore, request, frameInfo, originatingPage);
+}
+
+void WebProcessPool::synthesizeAppIsBackground(bool background)
+{
+    ensureNetworkProcess().synthesizeAppIsBackground(background);
 }
 
 void WebProcessPool::addMessageReceiver(IPC::ReceiverName messageReceiverName, IPC::MessageReceiver& messageReceiver)
@@ -1422,6 +1750,30 @@ void WebProcessPool::stopMemorySampler()
     sendToAllProcesses(Messages::WebProcess::StopMemorySampler());
 }
 
+template<typename T, typename U>
+void WebProcessPool::sendSyncToNetworkingProcess(T&& message, U&& reply)
+{
+    if (m_networkProcess && m_networkProcess->canSendMessage())
+        m_networkProcess->sendSync(std::forward<T>(message), std::forward<U>(reply), 0);
+}
+
+void WebProcessPool::clearCachedCredentials(const PAL::SessionID& sessionID)
+{
+    if (m_networkProcess)
+        m_networkProcess->send(Messages::NetworkProcess::ClearCachedCredentials(sessionID), 0);
+}
+
+void WebProcessPool::terminateNetworkProcess()
+{
+    terminateServiceWorkers();
+
+    if (!m_networkProcess)
+        return;
+    
+    m_networkProcess->terminate();
+    m_networkProcess = nullptr;
+}
+
 void WebProcessPool::terminateAllWebContentProcesses()
 {
     Vector<RefPtr<WebProcessProxy>> processes = m_processes;
@@ -1429,15 +1781,40 @@ void WebProcessPool::terminateAllWebContentProcesses()
         process->terminate();
 }
 
+void WebProcessPool::sendNetworkProcessPrepareToSuspendForTesting(CompletionHandler<void()>&& completionHandler)
+{
+    if (!m_networkProcess)
+        return completionHandler();
+
+    m_networkProcess->sendPrepareToSuspend(IsSuspensionImminent::No, WTFMove(completionHandler));
+}
+
+void WebProcessPool::sendNetworkProcessWillSuspendImminentlyForTesting()
+{
+    if (m_networkProcess)
+        m_networkProcess->sendProcessWillSuspendImminentlyForTesting();
+}
+
+void WebProcessPool::sendNetworkProcessDidResume()
+{
+    if (m_networkProcess)
+        m_networkProcess->sendProcessDidResume();
+}
+
 void WebProcessPool::terminateServiceWorkers()
 {
 #if ENABLE(SERVICE_WORKER)
     auto protectedThis = makeRef(*this);
-    while (serviceWorkerProcesses().computeSize())
-        serviceWorkerProcesses().begin()->disableServiceWorkers();
+    while (m_serviceWorkerProcesses.computeSize())
+        m_serviceWorkerProcesses.begin()->disableServiceWorkers();
 #endif
 }
 
+void WebProcessPool::flushCookies(const PAL::SessionID& sessionID, CompletionHandler<void()>&& completionHandler)
+{
+    ensureNetworkProcess().flushCookies(sessionID, WTFMove(completionHandler));
+}
+
 void WebProcessPool::updateAutomationCapabilities() const
 {
 #if ENABLE(REMOTE_INSPECTOR)
@@ -1712,21 +2089,15 @@ void WebProcessPool::reportWebContentCPUTime(Seconds cpuTime, uint64_t activityS
 #endif
 }
 
-WeakHashSet<WebProcessProxy>& WebProcessPool::serviceWorkerProcesses()
-{
-    static NeverDestroyed<WeakHashSet<WebProcessProxy>> processes;
-    return processes;
-}
-
 void WebProcessPool::updateProcessAssertions()
 {
-    WebsiteDataStore::forEachWebsiteDataStore([] (WebsiteDataStore& dataStore) {
-        dataStore.networkProcess().updateProcessAssertion();
-    });
+    ensureNetworkProcess().updateProcessAssertion();
 #if ENABLE(SERVICE_WORKER)
     // Check on next run loop since the web process proxy tokens are probably being updated.
-    callOnMainRunLoop([] {
-        for (auto& serviceWorkerProcess : serviceWorkerProcesses())
+    callOnMainRunLoop([this, weakThis = makeWeakPtr(this)] {
+        if (!weakThis)
+            return;
+        for (auto& serviceWorkerProcess : m_serviceWorkerProcesses)
             serviceWorkerProcess.updateServiceWorkerProcessAssertion();
     });
 #endif
@@ -1736,7 +2107,7 @@ bool WebProcessPool::isServiceWorkerPageID(WebPageProxyIdentifier pageID) const
 {
 #if ENABLE(SERVICE_WORKER)
     // FIXME: This is inefficient.
-    return WTF::anyOf(serviceWorkerProcesses(), [pageID](auto& process) {
+    return WTF::anyOf(m_serviceWorkerProcesses, [pageID](auto& process) {
         return process.hasServiceWorkerPageProxy(pageID);
     });
 #endif
@@ -1958,6 +2329,14 @@ void WebProcessPool::clearCurrentModifierStateForTesting()
 }
 
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
+void WebProcessPool::didCommitCrossSiteLoadWithDataTransfer(PAL::SessionID sessionID, const RegistrableDomain& fromDomain, const RegistrableDomain& toDomain, OptionSet<CrossSiteNavigationDataTransfer::Flag> navigationDataTransfer, WebPageProxyIdentifier webPageProxyID, PageIdentifier webPageID)
+{
+    if (!m_networkProcess)
+        return;
+
+    m_networkProcess->didCommitCrossSiteLoadWithDataTransfer(sessionID, fromDomain, toDomain, navigationDataTransfer, webPageProxyID, webPageID);
+}
+
 void WebProcessPool::setDomainsWithUserInteraction(HashSet<WebCore::RegistrableDomain>&& domains)
 {
     sendToAllProcesses(Messages::WebProcess::SetDomainsWithUserInteraction(domains));
@@ -2008,27 +2387,27 @@ void WebProcessPool::updateAudibleMediaAssertions()
 
 void WebProcessPool::setUseSeparateServiceWorkerProcess(bool useSeparateServiceWorkerProcess)
 {
-    if (s_useSeparateServiceWorkerProcess == useSeparateServiceWorkerProcess)
+    if (m_useSeparateServiceWorkerProcess == useSeparateServiceWorkerProcess)
         return;
 
-    WEBPROCESSPOOL_RELEASE_LOG_STATIC(ServiceWorker, "setUseSeparateServiceWorkerProcess: (useSeparateServiceWorkerProcess=%d)", useSeparateServiceWorkerProcess);
+    WEBPROCESSPOOL_RELEASE_LOG(ServiceWorker, "setUseSeparateServiceWorkerProcess: (useSeparateServiceWorkerProcess=%d)", useSeparateServiceWorkerProcess);
 
-    s_useSeparateServiceWorkerProcess = useSeparateServiceWorkerProcess;
-    for (auto* processPool : WebProcessPool::allProcessPools())
-        processPool->terminateServiceWorkers();
+    m_useSeparateServiceWorkerProcess = useSeparateServiceWorkerProcess;
+    terminateServiceWorkers();
+    terminateNetworkProcess();
 }
 
 #if ENABLE(SERVICE_WORKER)
 bool WebProcessPool::hasServiceWorkerForegroundActivityForTesting() const
 {
-    return WTF::anyOf(serviceWorkerProcesses(), [](auto& process) {
+    return WTF::anyOf(m_serviceWorkerProcesses, [](auto& process) {
         return process.hasServiceWorkerForegroundActivityForTesting();
     });
 }
 
 bool WebProcessPool::hasServiceWorkerBackgroundActivityForTesting() const
 {
-    return WTF::anyOf(serviceWorkerProcesses(), [](auto& process) {
+    return WTF::anyOf(m_serviceWorkerProcesses, [](auto& process) {
         return process.hasServiceWorkerBackgroundActivityForTesting();
     });
 }
index 668c1e6..9906b7d 100644 (file)
@@ -77,6 +77,7 @@ OBJC_CLASS WKPreferenceObserver;
 
 namespace API {
 class AutomationClient;
+class CustomProtocolManagerClient;
 class DownloadClient;
 class HTTPCookieStore;
 class InjectedBundleClient;
@@ -175,6 +176,7 @@ public:
     void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&&);
     void setDownloadClient(UniqueRef<API::DownloadClient>&&);
     void setAutomationClient(std::unique_ptr<API::AutomationClient>&&);
+    void setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&&);
 
     void setCustomWebContentServiceBundleIdentifier(const String&);
     const String& customWebContentServiceBundleIdentifier() { return m_configuration->customWebContentServiceBundleIdentifier(); }
@@ -185,9 +187,17 @@ public:
     // null checks in WebPageProxy.
     WebProcessProxy* dummyProcessProxy(PAL::SessionID sessionID) const { return m_dummyProcessProxies.get(sessionID).get(); }
 
+    // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null.
+    IPC::Connection* networkingProcessConnection();
+
     template<typename T> void sendToAllProcesses(const T& message);
     template<typename T> void sendToAllProcessesForSession(const T& message, PAL::SessionID);
 
+    // Sends the message to WebProcess or NetworkProcess as approporiate for current process model.
+    template<typename T> void sendToNetworkingProcess(T&& message);
+    template<typename T, typename U> void sendSyncToNetworkingProcess(T&& message, U&& reply);
+    template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message);
+
     void processDidFinishLaunching(WebProcessProxy*);
 
     WebProcessCache& webProcessCache() { return m_webProcessCache.get(); }
@@ -195,6 +205,9 @@ public:
     // Disconnect the process from the context.
     void disconnectProcess(WebProcessProxy*);
 
+    WebKit::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); }
+    void setPrimaryDataStore(WebKit::WebsiteDataStore& dataStore) { m_websiteDataStore = &dataStore; }
+
     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
 
     void pageBeginUsingWebsiteDataStore(WebPageProxyIdentifier, WebsiteDataStore&);
@@ -245,8 +258,10 @@ public:
     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
     void clearSupportedPlugins();
 
+    ProcessID networkProcessIdentifier();
     ProcessID prewarmedProcessIdentifier();
     void activePagesOriginsInWebProcessForTesting(ProcessID, CompletionHandler<void(Vector<String>&&)>&&);
+    bool networkProcessHasEntitlementForTesting(const String&);
 
     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
 
@@ -287,6 +302,8 @@ public:
     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
     WebContextClient& client() { return m_client; }
 
+    API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
+
     struct Statistics {
         unsigned wkViewCount;
         unsigned wkPageCount;
@@ -302,8 +319,12 @@ public:
     void sendNetworkProcessDidResume();
     void terminateServiceWorkers();
 
+    void flushCookies(const PAL::SessionID&, CompletionHandler<void()>&&);
+
     void setShouldMakeNextWebProcessLaunchFailForTesting(bool value) { m_shouldMakeNextWebProcessLaunchFailForTesting = value; }
     bool shouldMakeNextWebProcessLaunchFailForTesting() const { return m_shouldMakeNextWebProcessLaunchFailForTesting; }
+    void setShouldMakeNextNetworkProcessLaunchFailForTesting(bool value) { m_shouldMakeNextNetworkProcessLaunchFailForTesting = value; }
+    bool shouldMakeNextNetworkProcessLaunchFailForTesting() const { return m_shouldMakeNextNetworkProcessLaunchFailForTesting; }
 
     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
 
@@ -362,13 +383,19 @@ public:
 #endif
 
     // Network Process Management
+    NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
+    NetworkProcessProxy* networkProcess() const { return m_networkProcess.get(); }
     void networkProcessCrashed(NetworkProcessProxy&);
 
+    void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnectionDelayedReply&&);
+
     bool isServiceWorkerPageID(WebPageProxyIdentifier) const;
 #if ENABLE(SERVICE_WORKER)
-    static void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::RegistrableDomain&&, PAL::SessionID, CompletionHandler<void()>&&);
+    void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::RegistrableDomain&&, PAL::SessionID, CompletionHandler<void()>&&);
     void removeFromServiceWorkerProcesses(WebProcessProxy&);
-    size_t serviceWorkerProxiesCount() const { return serviceWorkerProcesses().computeSize(); }
+    size_t serviceWorkerProxiesCount() const { return m_serviceWorkerProcesses.computeSize(); }
+    void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
+    bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
     void updateServiceWorkerUserAgent(const String& userAgent);
     const Optional<UserContentControllerIdentifier>& userContentControllerIdentifierForServiceWorkers() const { return m_userContentControllerIDForServiceWorker; }
     bool hasServiceWorkerForegroundActivityForTesting() const;
@@ -422,6 +449,8 @@ public:
     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
 
+    void synthesizeAppIsBackground(bool background);
+    
 #if ENABLE(GAMEPAD)
     void gamepadConnected(const UIGamepad&, WebCore::EventMakesGamepadsVisible);
     void gamepadDisconnected(const UIGamepad&);
@@ -459,6 +488,7 @@ public:
     void clearCurrentModifierStateForTesting();
 
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
+    void didCommitCrossSiteLoadWithDataTransfer(PAL::SessionID, const WebCore::RegistrableDomain& fromDomain, const WebCore::RegistrableDomain& toDomain, OptionSet<WebCore::CrossSiteNavigationDataTransfer::Flag>, WebPageProxyIdentifier, WebCore::PageIdentifier);
     void setDomainsWithUserInteraction(HashSet<WebCore::RegistrableDomain>&&);
     void seedResourceLoadStatisticsForTesting(const WebCore::RegistrableDomain& firstPartyDomain, const WebCore::RegistrableDomain& thirdPartyDomain, bool shouldScheduleNotification, CompletionHandler<void()>&&);
     void sendResourceLoadStatisticsDataImmediately(CompletionHandler<void()>&&);
@@ -485,8 +515,8 @@ public:
     
     PlugInAutoStartProvider& plugInAutoStartProvider() { return m_plugInAutoStartProvider; }
 
-    static void setUseSeparateServiceWorkerProcess(bool);
-    static bool useSeparateServiceWorkerProcess() { return s_useSeparateServiceWorkerProcess; }
+    void setUseSeparateServiceWorkerProcess(bool);
+    bool useSeparateServiceWorkerProcess() const { return m_useSeparateServiceWorkerProcess; }
 
 #if ENABLE(CFPREFS_DIRECT_MODE)
     void notifyPreferencesChanged(const String& domain, const String& key, const Optional<String>& encodedValue);
@@ -498,15 +528,9 @@ public:
     int32_t userId() const { return m_userId; }
 #endif
 
-    static void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
-    static Vector<String> urlSchemesWithCustomProtocolHandlers();
-
-#if PLATFORM(IOS_FAMILY)
-    static String cookieStorageDirectory();
-    static String parentBundleDirectory();
-    static String networkingCachesDirectory();
-    static String webContentCachesDirectory();
-    static String containerTemporaryDirectory();
+#if PLATFORM(COCOA)
+    OSObjectPtr<xpc_object_t> xpcEndpointMessage() const;
+    void sendNetworkProcessXPCEndpointToWebProcess(OSObjectPtr<xpc_object_t> endpointMessage);
 #endif
 
 private:
@@ -522,6 +546,8 @@ private:
     WebProcessProxy& createNewWebProcess(WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
 
+    void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
+
     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&&);
 
@@ -545,6 +571,14 @@ private:
 
     bool usesSingleWebProcess() const { return m_configuration->usesSingleWebProcess(); }
 
+#if PLATFORM(IOS_FAMILY)
+    static String cookieStorageDirectory();
+    static String parentBundleDirectory();
+    static String networkingCachesDirectory();
+    static String webContentCachesDirectory();
+    static String containerTemporaryDirectory();
+#endif
+
 #if PLATFORM(COCOA)
     void registerNotificationObservers();
     void unregisterNotificationObservers();
@@ -586,8 +620,9 @@ private:
     HashMap<PAL::SessionID, WeakPtr<WebProcessProxy>> m_dummyProcessProxies; // Lightweight WebProcessProxy objects without backing process.
 
 #if ENABLE(SERVICE_WORKER)
-    static WeakHashSet<WebProcessProxy>& serviceWorkerProcesses();
+    WeakHashSet<WebProcessProxy> m_serviceWorkerProcesses;
     bool m_waitingForWorkerContextProcessConnection { false };
+    bool m_allowsAnySSLCertificateForServiceWorker { false };
     String m_serviceWorkerUserAgent;
     Optional<WebPreferencesStore> m_serviceWorkerPreferences;
     Optional<UserContentControllerIdentifier> m_userContentControllerIDForServiceWorker;
@@ -603,6 +638,7 @@ private:
     std::unique_ptr<API::AutomationClient> m_automationClient;
     UniqueRef<API::DownloadClient> m_downloadClient;
     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
+    std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
 
     RefPtr<WebAutomationSession> m_automationSession;
 
@@ -634,6 +670,8 @@ private:
     bool m_memorySamplerEnabled { false };
     double m_memorySamplerInterval { 1400.0 };
 
+    RefPtr<WebKit::WebsiteDataStore> m_websiteDataStore;
+
     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
     WebContextSupplementMap m_supplements;
 
@@ -665,6 +703,8 @@ private:
 
     bool m_processTerminationEnabled { true };
 
+    std::unique_ptr<NetworkProcessProxy> m_networkProcess;
+
     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
 
     bool m_memoryCacheDisabled { false };
@@ -673,6 +713,7 @@ private:
     bool m_alwaysRunsAtBackgroundPriority;
     bool m_shouldTakeUIBackgroundAssertion;
     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
+    bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
     bool m_tccPreferenceEnabled { false };
 
     UserObservablePageCounter m_userObservablePageCounter;
@@ -764,14 +805,32 @@ private:
 #else
     bool m_isDelayedWebProcessLaunchDisabled { false };
 #endif
-    static bool s_useSeparateServiceWorkerProcess;
+    bool m_useSeparateServiceWorkerProcess { false };
 
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
     HashSet<WebCore::RegistrableDomain> m_domainsWithUserInteraction;
 #endif
+
+#if PLATFORM(COCOA)
+    OSObjectPtr<xpc_object_t> m_endpointMessage;
+#endif
 };
 
 template<typename T>
+void WebProcessPool::sendToNetworkingProcess(T&& message)
+{
+    if (m_networkProcess && m_networkProcess->canSendMessage())
+        m_networkProcess->send(std::forward<T>(message), 0);
+}
+
+template<typename T>
+void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
+{
+    ensureNetworkProcess();
+    m_networkProcess->send(std::forward<T>(message), 0);
+}
+
+template<typename T>
 void WebProcessPool::sendToAllProcesses(const T& message)
 {
     size_t processCount = m_processes.size();
index 5e2c708..d661033 100644 (file)
@@ -268,9 +268,6 @@ void WebProcessProxy::setWebsiteDataStore(WebsiteDataStore& dataStore)
 {
     ASSERT(!m_websiteDataStore);
     m_websiteDataStore = &dataStore;
-#if PLATFORM(COCOA)
-    dataStore.sendNetworkProcessXPCEndpointToWebProcess(*this);
-#endif
     updateRegistrationWithDataStore();
     send(Messages::WebProcess::SetWebsiteDataStoreParameters(processPool().webProcessDataStoreParameters(*this, dataStore)), 0);
 }
@@ -741,7 +738,7 @@ void WebProcessProxy::getPluginProcessConnection(uint64_t pluginProcessToken, Me
 
 void WebProcessProxy::getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&& reply)
 {
-    websiteDataStore().getNetworkProcessConnection(*this, WTFMove(reply));
+    m_processPool->getNetworkProcessConnection(*this, WTFMove(reply));
 }
 
 #if ENABLE(GPU_PROCESS)
@@ -958,8 +955,9 @@ void WebProcessProxy::didFinishLaunching(ProcessLauncher* launcher, IPC::Connect
     }
 
 #if PLATFORM(COCOA)
-    if (m_websiteDataStore)
-        m_websiteDataStore->sendNetworkProcessXPCEndpointToWebProcess(*this);
+    auto endpointMessage = processPool().xpcEndpointMessage();
+    if (endpointMessage)
+        xpc_connection_send_message(connection()->xpcConnection(), endpointMessage.get());
 #endif
 
     RELEASE_ASSERT(!m_webConnection);
index cb8b3ba..7c44085 100644 (file)
 
 #import "CookieStorageUtilsCF.h"
 #import "DefaultWebBrowserChecks.h"
-#import "NetworkProcessProxy.h"
 #import "SandboxUtilities.h"
 #import "StorageManager.h"
 #import "WebFramePolicyListenerProxy.h"
 #import "WebPreferencesKeys.h"
-#import "WebProcessProxy.h"
 #import "WebResourceLoadStatisticsStore.h"
 #import "WebsiteDataStoreParameters.h"
 #import <WebCore/NetworkStorageSession.h>
@@ -46,7 +44,6 @@
 #import <wtf/NeverDestroyed.h>
 #import <wtf/ProcessPrivilege.h>
 #import <wtf/URL.h>
-#import <wtf/cocoa/Entitlements.h>
 #import <wtf/text/StringBuilder.h>
 
 #if PLATFORM(IOS_FAMILY)
@@ -565,28 +562,4 @@ void WebsiteDataStore::reinitializeAppBoundDomains()
 }
 #endif
 
-bool WebsiteDataStore::networkProcessHasEntitlementForTesting(const String& entitlement)
-{
-    return WTF::hasEntitlement(networkProcess().connection()->xpcConnection(), entitlement.utf8().data());
-}
-
-void WebsiteDataStore::sendNetworkProcessXPCEndpointToWebProcess(WebProcessProxy& process)
-{
-    if (process.state() != AuxiliaryProcessProxy::State::Running)
-        return;
-    auto* connection = process.connection();
-    if (!connection)
-        return;
-    auto message = networkProcess().xpcEndpointMessage();
-    if (!message)
-        return;
-    xpc_connection_send_message(connection->xpcConnection(), message);
-}
-
-void WebsiteDataStore::sendNetworkProcessXPCEndpointToAllWebProcesses()
-{
-    for (auto& process : m_processes)
-        sendNetworkProcessXPCEndpointToWebProcess(process);
-}
-
 }
index 8070f57..0830ca7 100644 (file)
 #include "AuthenticatorManager.h"
 #include "DeviceIdHashSaltStorage.h"
 #include "GPUProcessProxy.h"
-#include "Logging.h"
 #include "MockAuthenticatorManager.h"
-#include "NetworkProcessConnectionInfo.h"
 #include "NetworkProcessMessages.h"
 #include "ShouldGrandfatherStatistics.h"
 #include "StorageAccessStatus.h"
 #include "WebBackForwardCache.h"
-#include "WebCookieManagerProxy.h"
 #include "WebKit2Initialize.h"
 #include "WebPageProxy.h"
 #include "WebProcessCache.h"
 #include "SOAuthorizationCoordinator.h"
 #endif
 
-#if PLATFORM(COCOA)
-#include "DefaultWebBrowserChecks.h"
-#endif
-
 namespace WebKit {
 
 static bool allowsWebsiteDataRecordsForAllOrigins;
@@ -90,19 +83,13 @@ void WebsiteDataStore::allowWebsiteDataRecordsForAllOrigins()
     allowsWebsiteDataRecordsForAllOrigins = true;
 }
 
-static HashMap<PAL::SessionID, WebsiteDataStore*>& allDataStores()
+static HashMap<PAL::SessionID, WebsiteDataStore*>& nonDefaultDataStores()
 {
     RELEASE_ASSERT(isUIThread());
     static NeverDestroyed<HashMap<PAL::SessionID, WebsiteDataStore*>> map;
     return map;
 }
 
-void WebsiteDataStore::forEachWebsiteDataStore(Function<void(WebsiteDataStore&)>&& function)
-{
-    for (auto* dataStore : allDataStores().values())
-        function(*dataStore);
-}
-
 Ref<WebsiteDataStore> WebsiteDataStore::createNonPersistent()
 {
     return adoptRef(*new WebsiteDataStore(WebsiteDataStoreConfiguration::create(IsPersistent::No), PAL::SessionID::generateEphemeralSessionID()));
@@ -128,7 +115,7 @@ WebsiteDataStore::WebsiteDataStore(Ref<WebsiteDataStoreConfiguration>&& configur
 #endif
 {
     WTF::setProcessPrivileges(allPrivileges());
-    registerWithSessionIDMap();
+    maybeRegisterWithSessionIDMap();
     platformInitialize();
 
     ASSERT(RunLoop::isMain());
@@ -141,12 +128,17 @@ WebsiteDataStore::~WebsiteDataStore()
 
     platformDestroy();
 
-    ASSERT(allDataStores().get(m_sessionID) == this);
-    allDataStores().remove(m_sessionID);
-    networkProcess().removeSession(*this);
+    if (m_sessionID != PAL::SessionID::defaultSessionID()) {
+        ASSERT(nonDefaultDataStores().get(m_sessionID) == this);
+        nonDefaultDataStores().remove(m_sessionID);
+        for (auto& processPool : WebProcessPool::allProcessPools()) {
+            if (auto* networkProcess = processPool->networkProcess())
+                networkProcess->removeSession(m_sessionID);
+        }
+    }
 #if ENABLE(GPU_PROCESS)
-    if (auto* gpuProcessProxy = GPUProcessProxy::singletonIfCreated())
-        gpuProcessProxy->removeSession(m_sessionID);
+        if (auto* gpuProcessProxy = GPUProcessProxy::singletonIfCreated())
+            gpuProcessProxy->removeSession(m_sessionID);
 #endif
 }
 
@@ -159,6 +151,7 @@ static RefPtr<WebsiteDataStore>& globalDefaultDataStore()
 Ref<WebsiteDataStore> WebsiteDataStore::defaultDataStore()
 {
     InitializeWebKit2();
+
     auto& store = globalDefaultDataStore();
     if (!store)
         store = adoptRef(new WebsiteDataStore(WebsiteDataStoreConfiguration::create(IsPersistent::Yes), PAL::SessionID::defaultSessionID()));
@@ -176,47 +169,17 @@ bool WebsiteDataStore::defaultDataStoreExists()
     return !!globalDefaultDataStore();
 }
 
-void WebsiteDataStore::registerWithSessionIDMap()
+void WebsiteDataStore::maybeRegisterWithSessionIDMap()
 {
-    auto result = allDataStores().add(m_sessionID, this);
-    ASSERT_UNUSED(result, result.isNewEntry);
-}
-
-WebsiteDataStore* WebsiteDataStore::existingDataStoreForSessionID(PAL::SessionID sessionID)
-{
-    return allDataStores().get(sessionID);
-}
-
-static Ref<NetworkProcessProxy> networkProcessForSession(PAL::SessionID sessionID)
-{
-#if PLATFORM(GTK) || PLATFORM(WPE)
-    if (sessionID.isEphemeral()) {
-        // Reuse a previous persistent session network process for ephemeral sessions.
-        for (auto* dataStore : allDataStores().values()) {
-            if (dataStore->isPersistent())
-                return makeRef(dataStore->networkProcess());
-        }
+    if (m_sessionID != PAL::SessionID::defaultSessionID()) {
+        auto result = nonDefaultDataStores().add(m_sessionID, this);
+        ASSERT_UNUSED(result, result.isNewEntry);
     }
-    return NetworkProcessProxy::create();
-#else
-    UNUSED_PARAM(sessionID);
-    return NetworkProcessProxy::defaultNetworkProcess();
-#endif
 }
 
-NetworkProcessProxy& WebsiteDataStore::networkProcess()
+WebsiteDataStore* WebsiteDataStore::existingNonDefaultDataStoreForSessionID(PAL::SessionID sessionID)
 {
-    if (!m_networkProcess) {
-        m_networkProcess = networkProcessForSession(m_sessionID);
-        m_networkProcess->addSession(*this);
-    }
-
-    return *m_networkProcess;
-}
-
-NetworkProcessProxy& WebsiteDataStore::networkProcess() const
-{
-    return const_cast<WebsiteDataStore&>(*this).networkProcess();
+    return sessionID != PAL::SessionID::defaultSessionID() ? nonDefaultDataStores().get(sessionID) : nullptr;
 }
 
 void WebsiteDataStore::registerProcess(WebProcessProxy& process)
@@ -232,6 +195,12 @@ void WebsiteDataStore::unregisterProcess(WebProcessProxy& process)
     m_processes.remove(process);
 }
 
+WebProcessPool* WebsiteDataStore::processPoolForCookieStorageOperations()
+{
+    auto pools = processPools(1);
+    return pools.isEmpty() ? nullptr : pools.begin()->get();
+}
+
 void WebsiteDataStore::resolveDirectoriesIfNecessary()
 {
     if (m_hasResolvedDirectories)
@@ -471,21 +440,28 @@ void WebsiteDataStore::fetchDataAndApply(OptionSet<WebsiteDataType> dataTypes, O
 #endif
 
     auto networkProcessAccessType = computeNetworkProcessAccessTypeForDataFetch(dataTypes, !isPersistent());
-    switch (networkProcessAccessType) {
-    case ProcessAccessType::Launch:
-        networkProcess();
-        ASSERT(m_networkProcess);
-        FALLTHROUGH;
-    case ProcessAccessType::OnlyIfLaunched:
-        if (m_networkProcess) {
+    if (networkProcessAccessType != ProcessAccessType::None) {
+        auto pools = networkProcessAccessType == ProcessAccessType::Launch ? ensureProcessPools() : processPools();
+        for (auto& processPool : pools) {
+            switch (networkProcessAccessType) {
+            case ProcessAccessType::OnlyIfLaunched:
+                if (!processPool->networkProcess())
+                    continue;
+                break;
+
+            case ProcessAccessType::Launch:
+                processPool->ensureNetworkProcess(this);
+                break;
+
+            case ProcessAccessType::None:
+                ASSERT_NOT_REACHED();
+            }
+
             callbackAggregator->addPendingCallback();
-            m_networkProcess->fetchWebsiteData(m_sessionID, dataTypes, fetchOptions, [callbackAggregator](WebsiteData websiteData) {
+            processPool->networkProcess()->fetchWebsiteData(m_sessionID, dataTypes, fetchOptions, [callbackAggregator, processPool](WebsiteData websiteData) {
                 callbackAggregator->removePendingCallback(WTFMove(websiteData));
             });
         }
-        break;
-    case ProcessAccessType::None:
-        break;
     }
 
     auto webProcessAccessType = computeWebProcessAccessTypeForDataFetch(dataTypes, !isPersistent());
@@ -748,24 +724,31 @@ void WebsiteDataStore::removeData(OptionSet<WebsiteDataType> dataTypes, WallTime
     bool didNotifyNetworkProcessToDeleteWebsiteData = false;
 #endif
     auto networkProcessAccessType = computeNetworkProcessAccessTypeForDataRemoval(dataTypes, !isPersistent());
-    switch (networkProcessAccessType) {
-    case ProcessAccessType::Launch:
-        networkProcess();
-        ASSERT(m_networkProcess);
-        FALLTHROUGH;
-    case ProcessAccessType::OnlyIfLaunched:
-        if (m_networkProcess) {
+    if (networkProcessAccessType != ProcessAccessType::None) {
+        auto pools = networkProcessAccessType == ProcessAccessType::Launch ? ensureProcessPools() : processPools();
+        for (auto& processPool : pools) {
+            switch (networkProcessAccessType) {
+            case ProcessAccessType::OnlyIfLaunched:
+                if (!processPool->networkProcess())
+                    continue;
+                break;
+
+            case ProcessAccessType::Launch:
+                processPool->ensureNetworkProcess(this);
+                break;
+
+            case ProcessAccessType::None:
+                ASSERT_NOT_REACHED();
+            }
+
             callbackAggregator->addPendingCallback();
-            m_networkProcess->deleteWebsiteData(m_sessionID, dataTypes, modifiedSince, [callbackAggregator] {
+            processPool->networkProcess()->deleteWebsiteData(m_sessionID, dataTypes, modifiedSince, [callbackAggregator, processPool] {
                 callbackAggregator->removePendingCallback();
             });
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
             didNotifyNetworkProcessToDeleteWebsiteData = true;
 #endif
         }
-        break;
-    case ProcessAccessType::None:
-        break;
     }
 
     auto webProcessAccessType = computeWebProcessAccessTypeForDataRemoval(dataTypes, !isPersistent());
@@ -910,9 +893,14 @@ void WebsiteDataStore::removeData(OptionSet<WebsiteDataType> dataTypes, WallTime
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
     if (dataTypes.contains(WebsiteDataType::ResourceLoadStatistics)) {
         if (!didNotifyNetworkProcessToDeleteWebsiteData) {
-            networkProcess().deleteWebsiteData(m_sessionID, dataTypes, modifiedSince, [callbackAggregator] {
-                callbackAggregator->removePendingCallback();
-            });
+            for (auto& processPool : processPools()) {
+                if (auto* process = processPool->networkProcess()) {
+                    callbackAggregator->addPendingCallback();
+                    process->deleteWebsiteData(m_sessionID, dataTypes, modifiedSince, [callbackAggregator] {
+                        callbackAggregator->removePendingCallback();
+                    });
+                }
+            }
         }
 
         callbackAggregator->addPendingCallback();
@@ -1006,10 +994,12 @@ void WebsiteDataStore::removeData(OptionSet<WebsiteDataType> dataTypes, const Ve
         for (auto& processPool : pools) {
             switch (networkProcessAccessType) {
             case ProcessAccessType::OnlyIfLaunched:
+                if (!processPool->networkProcess())
+                    continue;
                 break;
 
             case ProcessAccessType::Launch:
-                networkProcess();
+                processPool->ensureNetworkProcess(this);
                 break;
 
             case ProcessAccessType::None:
@@ -1031,7 +1021,7 @@ void WebsiteDataStore::removeData(OptionSet<WebsiteDataType> dataTypes, const Ve
             }
 
             callbackAggregator->addPendingCallback();
-            networkProcess().deleteWebsiteDataForOrigins(m_sessionID, dataTypes, origins, cookieHostNames, HSTSCacheHostNames, registrableDomains, [callbackAggregator, processPool] {
+            processPool->networkProcess()->deleteWebsiteDataForOrigins(m_sessionID, dataTypes, origins, cookieHostNames, HSTSCacheHostNames, registrableDomains, [callbackAggregator, processPool] {
                 callbackAggregator->removePendingCallback();
             });
         }
@@ -1190,12 +1180,18 @@ void WebsiteDataStore::removeData(OptionSet<WebsiteDataType> dataTypes, const Ve
 
 void WebsiteDataStore::setServiceWorkerTimeoutForTesting(Seconds seconds)
 {
-    networkProcess().sendSync(Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting(seconds), Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting::Reply(), 0);
+    for (auto& processPool : WebProcessPool::allProcessPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->sendSync(Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting(seconds), Messages::NetworkProcess::SetServiceWorkerFetchTimeoutForTesting::Reply(), 0);
+    }
 }
 
 void WebsiteDataStore::resetServiceWorkerTimeoutForTesting()
 {
-    networkProcess().sendSync(Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting(), Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting::Reply(), 0);
+    for (auto& processPool : WebProcessPool::allProcessPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->sendSync(Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting(), Messages::NetworkProcess::ResetServiceWorkerFetchTimeoutForTesting::Reply(), 0);
+    }
 }
 
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
@@ -1205,7 +1201,8 @@ void WebsiteDataStore::setMaxStatisticsEntries(size_t maximumEntryCount, Complet
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setMaxStatisticsEntries(m_sessionID, maximumEntryCount, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setMaxStatisticsEntries(m_sessionID, maximumEntryCount, [processPool, callbackAggregator] { });
 }
 
 void WebsiteDataStore::setPruneEntriesDownTo(size_t pruneTargetCount, CompletionHandler<void()>&& completionHandler)
@@ -1214,7 +1211,8 @@ void WebsiteDataStore::setPruneEntriesDownTo(size_t pruneTargetCount, Completion
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setPruneEntriesDownTo(m_sessionID, pruneTargetCount, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setPruneEntriesDownTo(m_sessionID, pruneTargetCount, [processPool, callbackAggregator] { });
 }
 
 void WebsiteDataStore::setGrandfatheringTime(Seconds seconds, CompletionHandler<void()>&& completionHandler)
@@ -1223,7 +1221,8 @@ void WebsiteDataStore::setGrandfatheringTime(Seconds seconds, CompletionHandler<
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setGrandfatheringTime(m_sessionID, seconds, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setGrandfatheringTime(m_sessionID, seconds, [processPool, callbackAggregator] { });
 }
 
 void WebsiteDataStore::setMinimumTimeBetweenDataRecordsRemoval(Seconds seconds, CompletionHandler<void()>&& completionHandler)
@@ -1232,13 +1231,20 @@ void WebsiteDataStore::setMinimumTimeBetweenDataRecordsRemoval(Seconds seconds,
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setMinimumTimeBetweenDataRecordsRemoval(m_sessionID, seconds, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setMinimumTimeBetweenDataRecordsRemoval(m_sessionID, seconds, [processPool, callbackAggregator] { });
 }
     
 void WebsiteDataStore::dumpResourceLoadStatistics(CompletionHandler<void(const String&)>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
-    networkProcess().dumpResourceLoadStatistics(m_sessionID, WTFMove(completionHandler));
+
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->dumpResourceLoadStatistics(m_sessionID, WTFMove(completionHandler));
+            break;
+        }
+    }
 }
 
 void WebsiteDataStore::isPrevalentResource(const URL& url, CompletionHandler<void(bool isPrevalent)>&& completionHandler)
@@ -1250,7 +1256,12 @@ void WebsiteDataStore::isPrevalentResource(const URL& url, CompletionHandler<voi
         return;
     }
 
-    networkProcess().isPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->isPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+            break;
+        }
+    }
 }
 
 void WebsiteDataStore::isGrandfathered(const URL& url, CompletionHandler<void(bool isPrevalent)>&& completionHandler)
@@ -1262,7 +1273,12 @@ void WebsiteDataStore::isGrandfathered(const URL& url, CompletionHandler<void(bo
         return;
     }
 
-    networkProcess().isGrandfathered(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->isGrandfathered(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+            break;
+        }
+    }
 }
 
 void WebsiteDataStore::setPrevalentResource(const URL& url, CompletionHandler<void()>&& completionHandler)
@@ -1276,7 +1292,8 @@ void WebsiteDataStore::setPrevalentResource(const URL& url, CompletionHandler<vo
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    for (auto& processPool : ensureProcessPools())
+        processPool->ensureNetworkProcess().setPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, [processPool, callbackAggregator] { });
 }
 
 void WebsiteDataStore::setPrevalentResourceForDebugMode(const URL& url, CompletionHandler<void()>&& completionHandler)
@@ -1290,7 +1307,10 @@ void WebsiteDataStore::setPrevalentResourceForDebugMode(const URL& url, Completi
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setPrevalentResourceForDebugMode(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setPrevalentResourceForDebugMode(m_sessionID, WebCore::RegistrableDomain { url }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::isVeryPrevalentResource(const URL& url, CompletionHandler<void(bool isVeryPrevalent)>&& completionHandler)
@@ -1302,7 +1322,12 @@ void WebsiteDataStore::isVeryPrevalentResource(const URL& url, CompletionHandler
         return;
     }
     
-    networkProcess().isVeryPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->isVeryPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+            break;
+        }
+    }
 }
 
 void WebsiteDataStore::setVeryPrevalentResource(const URL& url, CompletionHandler<void()>&& completionHandler)
@@ -1316,7 +1341,10 @@ void WebsiteDataStore::setVeryPrevalentResource(const URL& url, CompletionHandle
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setVeryPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->setVeryPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setShouldClassifyResourcesBeforeDataRecordsRemoval(bool value, CompletionHandler<void()>&& completionHandler)
@@ -1325,7 +1353,8 @@ void WebsiteDataStore::setShouldClassifyResourcesBeforeDataRecordsRemoval(bool v
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setShouldClassifyResourcesBeforeDataRecordsRemoval(m_sessionID, value, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setShouldClassifyResourcesBeforeDataRecordsRemoval(m_sessionID, value, [processPool, callbackAggregator] { });
 }
 
 void WebsiteDataStore::setSubframeUnderTopFrameDomain(const URL& subFrameURL, const URL& topFrameURL, CompletionHandler<void()>&& completionHandler)
@@ -1339,14 +1368,22 @@ void WebsiteDataStore::setSubframeUnderTopFrameDomain(const URL& subFrameURL, co
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setSubframeUnderTopFrameDomain(m_sessionID, WebCore::RegistrableDomain { subFrameURL }, WebCore::RegistrableDomain { topFrameURL }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setSubframeUnderTopFrameDomain(m_sessionID, WebCore::RegistrableDomain { subFrameURL }, WebCore::RegistrableDomain { topFrameURL }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::isRegisteredAsSubFrameUnder(const URL& subFrameURL, const URL& topFrameURL, CompletionHandler<void(bool)>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
 
-    networkProcess().isRegisteredAsSubFrameUnder(m_sessionID, WebCore::RegistrableDomain { subFrameURL }, WebCore::RegistrableDomain { topFrameURL }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->isRegisteredAsSubFrameUnder(m_sessionID, WebCore::RegistrableDomain { subFrameURL }, WebCore::RegistrableDomain { topFrameURL }, WTFMove(completionHandler));
+            break;
+        }
+    }
 }
 
 void WebsiteDataStore::setSubresourceUnderTopFrameDomain(const URL& subresourceURL, const URL& topFrameURL, CompletionHandler<void()>&& completionHandler)
@@ -1360,14 +1397,23 @@ void WebsiteDataStore::setSubresourceUnderTopFrameDomain(const URL& subresourceU
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setSubresourceUnderTopFrameDomain(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { topFrameURL }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setSubresourceUnderTopFrameDomain(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { topFrameURL }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::isRegisteredAsSubresourceUnder(const URL& subresourceURL, const URL& topFrameURL, CompletionHandler<void(bool)>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
     
-    networkProcess().isRegisteredAsSubresourceUnder(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { topFrameURL }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->isRegisteredAsSubresourceUnder(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { topFrameURL }, WTFMove(completionHandler));
+            return;
+        }
+    }
+    completionHandler(false);
 }
 
 void WebsiteDataStore::setSubresourceUniqueRedirectTo(const URL& subresourceURL, const URL& urlRedirectedTo, CompletionHandler<void()>&& completionHandler)
@@ -1381,7 +1427,10 @@ void WebsiteDataStore::setSubresourceUniqueRedirectTo(const URL& subresourceURL,
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setSubresourceUniqueRedirectTo(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { urlRedirectedTo }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setSubresourceUniqueRedirectTo(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { urlRedirectedTo }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setSubresourceUniqueRedirectFrom(const URL& subresourceURL, const URL& urlRedirectedFrom, CompletionHandler<void()>&& completionHandler)
@@ -1393,7 +1442,12 @@ void WebsiteDataStore::setSubresourceUniqueRedirectFrom(const URL& subresourceUR
         return;
     }
 
-    networkProcess().setSubresourceUniqueRedirectFrom(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { urlRedirectedFrom }, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setSubresourceUniqueRedirectFrom(m_sessionID, WebCore::RegistrableDomain { subresourceURL }, WebCore::RegistrableDomain { urlRedirectedFrom }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setTopFrameUniqueRedirectTo(const URL& topFrameURL, const URL& urlRedirectedTo, CompletionHandler<void()>&& completionHandler)
@@ -1405,7 +1459,12 @@ void WebsiteDataStore::setTopFrameUniqueRedirectTo(const URL& topFrameURL, const
         return;
     }
 
-    networkProcess().setTopFrameUniqueRedirectTo(m_sessionID, WebCore::RegistrableDomain { topFrameURL }, WebCore::RegistrableDomain { urlRedirectedTo }, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setTopFrameUniqueRedirectTo(m_sessionID, WebCore::RegistrableDomain { topFrameURL }, WebCore::RegistrableDomain { urlRedirectedTo }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setTopFrameUniqueRedirectFrom(const URL& topFrameURL, const URL& urlRedirectedFrom, CompletionHandler<void()>&& completionHandler)
@@ -1417,14 +1476,25 @@ void WebsiteDataStore::setTopFrameUniqueRedirectFrom(const URL& topFrameURL, con
         return;
     }
 
-    networkProcess().setTopFrameUniqueRedirectFrom(m_sessionID, WebCore::RegistrableDomain { topFrameURL }, WebCore::RegistrableDomain { urlRedirectedFrom }, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setTopFrameUniqueRedirectFrom(m_sessionID, WebCore::RegistrableDomain { topFrameURL }, WebCore::RegistrableDomain { urlRedirectedFrom }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::isRegisteredAsRedirectingTo(const URL& urlRedirectedFrom, const URL& urlRedirectedTo, CompletionHandler<void(bool)>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
     
-    networkProcess().isRegisteredAsRedirectingTo(m_sessionID, WebCore::RegistrableDomain { urlRedirectedFrom }, WebCore::RegistrableDomain { urlRedirectedTo }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->isRegisteredAsRedirectingTo(m_sessionID, WebCore::RegistrableDomain { urlRedirectedFrom }, WebCore::RegistrableDomain { urlRedirectedTo }, WTFMove(completionHandler));
+            return;
+        }
+    }
+    completionHandler(false);
 }
 
 void WebsiteDataStore::clearPrevalentResource(const URL& url, CompletionHandler<void()>&& completionHandler)
@@ -1436,41 +1506,60 @@ void WebsiteDataStore::clearPrevalentResource(const URL& url, CompletionHandler<
         return;
     }
 
-    networkProcess().clearPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->clearPrevalentResource(m_sessionID, WebCore::RegistrableDomain { url }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::resetParametersToDefaultValues(CompletionHandler<void()>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
-    networkProcess().resetParametersToDefaultValues(m_sessionID, WTFMove(completionHandler));
+
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->resetParametersToDefaultValues(m_sessionID, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::submitTelemetry()
 {
     ASSERT(RunLoop::isMain());
     
-    networkProcess().submitTelemetry(m_sessionID, [] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->submitTelemetry(m_sessionID, [] { });
+    }
 }
 
 void WebsiteDataStore::scheduleClearInMemoryAndPersistent(WallTime modifiedSince, ShouldGrandfatherStatistics shouldGrandfather, CompletionHandler<void()>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
     
-    networkProcess().scheduleClearInMemoryAndPersistent(m_sessionID, modifiedSince, shouldGrandfather, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->scheduleClearInMemoryAndPersistent(m_sessionID, modifiedSince, shouldGrandfather, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::getResourceLoadStatisticsDataSummary(CompletionHandler<void(Vector<WebResourceLoadStatisticsStore::ThirdPartyData>&&)>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
 
-    struct LocalCallbackAggregator : RefCounted<LocalCallbackAggregator> {
-        LocalCallbackAggregator(CompletionHandler<void(Vector<WebResourceLoadStatisticsStore::ThirdPartyData>&&)>&& completionHandler)
+    struct CallbackAggregator : RefCounted<CallbackAggregator> {
+        CallbackAggregator(CompletionHandler<void(Vector<WebResourceLoadStatisticsStore::ThirdPartyData>&&)>&& completionHandler)
             : m_completionHandler(WTFMove(completionHandler))
         {
             ASSERT(RunLoop::isMain());
         };
 
-        ~LocalCallbackAggregator()
+        ~CallbackAggregator()
         {
             ASSERT(RunLoop::isMain());
 
@@ -1485,31 +1574,38 @@ void WebsiteDataStore::getResourceLoadStatisticsDataSummary(CompletionHandler<vo
         CompletionHandler<void(Vector<WebResourceLoadStatisticsStore::ThirdPartyData>&&)> m_completionHandler;
         Vector<WebResourceLoadStatisticsStore::ThirdPartyData> m_results;
     };
-    
-    auto localCallbackAggregator = adoptRef(new LocalCallbackAggregator(WTFMove(completionHandler)));
-    
-    auto wtfCallbackAggregator = WTF::CallbackAggregator::create([this, protectedThis = makeRef(*this), localCallbackAggregator] {
-        networkProcess().getResourceLoadStatisticsDataSummary(m_sessionID, [localCallbackAggregator](Vector<WebResourceLoadStatisticsStore::ThirdPartyData>&& data) {
-            localCallbackAggregator->addResult(WTFMove(data));
+
+    RefPtr<CallbackAggregator> callbackAggregator = adoptRef(new CallbackAggregator(WTFMove(completionHandler)));
+
+    for (auto& processPool : ensureProcessPools()) {
+        processPool->sendResourceLoadStatisticsDataImmediately([this, protectedThis = makeRef(*this), processPool, callbackAggregator] {
+            processPool->ensureNetworkProcess(this).getResourceLoadStatisticsDataSummary(m_sessionID, [callbackAggregator, processPool](Vector<WebResourceLoadStatisticsStore::ThirdPartyData>&& data) {
+                callbackAggregator->addResult(WTFMove(data));
+            });
         });
-    });
-    
-    for (auto* processPool : WebProcessPool::allProcessPools())
-        processPool->sendResourceLoadStatisticsDataImmediately([wtfCallbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::scheduleClearInMemoryAndPersistent(ShouldGrandfatherStatistics shouldGrandfather, CompletionHandler<void()>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
     
-    networkProcess().scheduleClearInMemoryAndPersistent(m_sessionID, { }, shouldGrandfather, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->scheduleClearInMemoryAndPersistent(m_sessionID, { }, shouldGrandfather, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::scheduleCookieBlockingUpdate(CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().scheduleCookieBlockingUpdate(m_sessionID, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->scheduleCookieBlockingUpdate(m_sessionID, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::scheduleStatisticsAndDataRecordsProcessing(CompletionHandler<void()>&& completionHandler)
@@ -1518,13 +1614,24 @@ void WebsiteDataStore::scheduleStatisticsAndDataRecordsProcessing(CompletionHand
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().scheduleStatisticsAndDataRecordsProcessing(m_sessionID, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->scheduleStatisticsAndDataRecordsProcessing(m_sessionID, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::statisticsDatabaseHasAllTables(CompletionHandler<void(bool)>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
-    networkProcess().statisticsDatabaseHasAllTables(m_sessionID, WTFMove(completionHandler));
+
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->statisticsDatabaseHasAllTables(m_sessionID, WTFMove(completionHandler));
+            return;
+        }
+    }
+
+    completionHandler(false);
 }
 
 void WebsiteDataStore::setLastSeen(const URL& url, Seconds seconds, CompletionHandler<void()>&& completionHandler)
@@ -1536,14 +1643,22 @@ void WebsiteDataStore::setLastSeen(const URL& url, Seconds seconds, CompletionHa
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setLastSeen(m_sessionID, WebCore::RegistrableDomain { url }, seconds, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setLastSeen(m_sessionID, WebCore::RegistrableDomain { url }, seconds, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::domainIDExistsInDatabase(int domainID, CompletionHandler<void(bool)>&& completionHandler)
 {
     ASSERT(RunLoop::isMain());
 
-    networkProcess().domainIDExistsInDatabase(m_sessionID, domainID, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->domainIDExistsInDatabase(m_sessionID, domainID, WTFMove(completionHandler));
+            break;
+        }
+    }
 }
 
 void WebsiteDataStore::mergeStatisticForTesting(const URL& url, const URL& topFrameUrl1, const URL& topFrameUrl2, Seconds lastSeen, bool hadUserInteraction, Seconds mostRecentUserInteraction, bool isGrandfathered, bool isPrevalent, bool isVeryPrevalent, unsigned dataRecordsRemoved, CompletionHandler<void()>&& completionHandler)
@@ -1555,7 +1670,10 @@ void WebsiteDataStore::mergeStatisticForTesting(const URL& url, const URL& topFr
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().mergeStatisticForTesting(m_sessionID, WebCore::RegistrableDomain { url }, WebCore::RegistrableDomain { topFrameUrl1 }, WebCore::RegistrableDomain { topFrameUrl2 }, lastSeen, hadUserInteraction, mostRecentUserInteraction, isGrandfathered, isPrevalent, isVeryPrevalent, dataRecordsRemoved, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->mergeStatisticForTesting(m_sessionID, WebCore::RegistrableDomain { url }, WebCore::RegistrableDomain { topFrameUrl1 }, WebCore::RegistrableDomain { topFrameUrl2 }, lastSeen, hadUserInteraction, mostRecentUserInteraction, isGrandfathered, isPrevalent, isVeryPrevalent, dataRecordsRemoved, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::insertExpiredStatisticForTesting(const URL& url, bool hadUserInteraction, bool isScheduledForAllButCookieDataRemoval, bool isPrevalent, CompletionHandler<void()>&& completionHandler)
@@ -1567,14 +1685,18 @@ void WebsiteDataStore::insertExpiredStatisticForTesting(const URL& url, bool had
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().insertExpiredStatisticForTesting(m_sessionID, WebCore::RegistrableDomain { url }, hadUserInteraction, isScheduledForAllButCookieDataRemoval, isPrevalent, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->insertExpiredStatisticForTesting(m_sessionID, WebCore::RegistrableDomain { url }, hadUserInteraction, isScheduledForAllButCookieDataRemoval, isPrevalent, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setNotifyPagesWhenDataRecordsWereScanned(bool value, CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setNotifyPagesWhenDataRecordsWereScanned(m_sessionID, value, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setNotifyPagesWhenDataRecordsWereScanned(m_sessionID, value, [processPool, callbackAggregator] { });
 }
 
 void WebsiteDataStore::setIsRunningResourceLoadStatisticsTest(bool value, CompletionHandler<void()>&& completionHandler)
@@ -1582,7 +1704,8 @@ void WebsiteDataStore::setIsRunningResourceLoadStatisticsTest(bool value, Comple
     useExplicitITPState();
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setIsRunningResourceLoadStatisticsTest(m_sessionID, value, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setIsRunningResourceLoadStatisticsTest(m_sessionID, value, [processPool, callbackAggregator] { });
 }
 
 void WebsiteDataStore::getAllStorageAccessEntries(WebPageProxyIdentifier pageID, CompletionHandler<void(Vector<String>&& domains)>&& completionHandler)
@@ -1593,7 +1716,7 @@ void WebsiteDataStore::getAllStorageAccessEntries(WebPageProxyIdentifier pageID,
         return;
     }
 
-    networkProcess().getAllStorageAccessEntries(m_sessionID, WTFMove(completionHandler));
+    webPage->process().processPool().ensureNetworkProcess().getAllStorageAccessEntries(m_sessionID, WTFMove(completionHandler));
 }
 
 
@@ -1601,7 +1724,8 @@ void WebsiteDataStore::setTimeToLiveUserInteraction(Seconds seconds, CompletionH
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setTimeToLiveUserInteraction(m_sessionID, seconds, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setTimeToLiveUserInteraction(m_sessionID, seconds, [callbackAggregator] { });
 }
 
 void WebsiteDataStore::logUserInteraction(const URL& url, CompletionHandler<void()>&& completionHandler)
@@ -1615,7 +1739,10 @@ void WebsiteDataStore::logUserInteraction(const URL& url, CompletionHandler<void
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().logUserInteraction(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->logUserInteraction(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::hasHadUserInteraction(const URL& url, CompletionHandler<void(bool)>&& completionHandler)
@@ -1627,7 +1754,13 @@ void WebsiteDataStore::hasHadUserInteraction(const URL& url, CompletionHandler<v
         return;
     }
     
-    networkProcess().hasHadUserInteraction(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->hasHadUserInteraction(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+            return;
+        }
+    }
+    completionHandler(false);
 }
 
 void WebsiteDataStore::isRelationshipOnlyInDatabaseOnce(const URL& subUrl, const URL& topUrl, CompletionHandler<void(bool)>&& completionHandler)
@@ -1639,7 +1772,13 @@ void WebsiteDataStore::isRelationshipOnlyInDatabaseOnce(const URL& subUrl, const
         return;
     }
     
-    networkProcess().isRelationshipOnlyInDatabaseOnce(m_sessionID, WebCore::RegistrableDomain { subUrl }, WebCore::RegistrableDomain { topUrl }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess()) {
+            process->isRelationshipOnlyInDatabaseOnce(m_sessionID, WebCore::RegistrableDomain { subUrl }, WebCore::RegistrableDomain { topUrl }, WTFMove(completionHandler));
+            return;
+        }
+    }
+    completionHandler(false);
 }
 
 void WebsiteDataStore::clearUserInteraction(const URL& url, CompletionHandler<void()>&& completionHandler)
@@ -1653,7 +1792,10 @@ void WebsiteDataStore::clearUserInteraction(const URL& url, CompletionHandler<vo
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().clearUserInteraction(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->clearUserInteraction(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setGrandfathered(const URL& url, bool isGrandfathered, CompletionHandler<void()>&& completionHandler)
@@ -1667,7 +1809,10 @@ void WebsiteDataStore::setGrandfathered(const URL& url, bool isGrandfathered, Co
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setGrandfathered(m_sessionID, WebCore::RegistrableDomain { url }, isGrandfathered, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setGrandfathered(m_sessionID, WebCore::RegistrableDomain { url }, isGrandfathered, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setUseITPDatabase(bool value, CompletionHandler<void()>&& completionHandler)
@@ -1676,7 +1821,10 @@ void WebsiteDataStore::setUseITPDatabase(bool value, CompletionHandler<void()>&&
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setUseITPDatabase(m_sessionID, value, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setUseITPDatabase(m_sessionID, value, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setCrossSiteLoadWithLinkDecorationForTesting(const URL& fromURL, const URL& toURL, CompletionHandler<void()>&& completionHandler)
@@ -1685,38 +1833,62 @@ void WebsiteDataStore::setCrossSiteLoadWithLinkDecorationForTesting(const URL& f
     
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setCrossSiteLoadWithLinkDecorationForTesting(m_sessionID, WebCore::RegistrableDomain { fromURL }, WebCore::RegistrableDomain { toURL }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->setCrossSiteLoadWithLinkDecorationForTesting(m_sessionID, WebCore::RegistrableDomain { fromURL }, WebCore::RegistrableDomain { toURL }, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::resetCrossSiteLoadsWithLinkDecorationForTesting(CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().resetCrossSiteLoadsWithLinkDecorationForTesting(m_sessionID, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->resetCrossSiteLoadsWithLinkDecorationForTesting(m_sessionID, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::deleteCookiesForTesting(const URL& url, bool includeHttpOnlyCookies, CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().deleteCookiesForTesting(m_sessionID, WebCore::RegistrableDomain { url }, includeHttpOnlyCookies, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->deleteCookiesForTesting(m_sessionID, WebCore::RegistrableDomain { url }, includeHttpOnlyCookies, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::hasLocalStorageForTesting(const URL& url, CompletionHandler<void(bool)>&& completionHandler) const
 {
-    networkProcess().hasLocalStorage(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess()) {
+            networkProcess->hasLocalStorage(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+            return;
+        }
+    }
+    completionHandler(false);
 }
 
 void WebsiteDataStore::hasIsolatedSessionForTesting(const URL& url, CompletionHandler<void(bool)>&& completionHandler) const
 {
-    networkProcess().hasIsolatedSession(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess()) {
+            networkProcess->hasIsolatedSession(m_sessionID, WebCore::RegistrableDomain { url }, WTFMove(completionHandler));
+            return;
+        }
+    }
+    completionHandler(false);
 }
 
 void WebsiteDataStore::setResourceLoadStatisticsShouldDowngradeReferrerForTesting(bool enabled, CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setShouldDowngradeReferrerForTesting(enabled, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->setShouldDowngradeReferrerForTesting(enabled, [callbackAggregator] { });
+    }
 }
 
 #if !PLATFORM(COCOA)
@@ -1747,7 +1919,10 @@ void WebsiteDataStore::setThirdPartyCookieBlockingMode(WebCore::ThirdPartyCookie
             webProcess.setThirdPartyCookieBlockingMode(blockingMode, [callbackAggregator] { });
     }
 
-    networkProcess().setThirdPartyCookieBlockingMode(m_sessionID, blockingMode, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->setThirdPartyCookieBlockingMode(m_sessionID, blockingMode, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setResourceLoadStatisticsShouldEnbleSameSiteStrictEnforcementForTesting(bool enabled, CompletionHandler<void()>&& completionHandler)
@@ -1755,7 +1930,10 @@ void WebsiteDataStore::setResourceLoadStatisticsShouldEnbleSameSiteStrictEnforce
     auto flag = enabled ? WebCore::SameSiteStrictEnforcementEnabled::Yes : WebCore::SameSiteStrictEnforcementEnabled::No;
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
-    networkProcess().setShouldEnbleSameSiteStrictEnforcementForTesting(m_sessionID, flag, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->setShouldEnbleSameSiteStrictEnforcementForTesting(m_sessionID, flag, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setResourceLoadStatisticsFirstPartyWebsiteDataRemovalModeForTesting(bool enabled, CompletionHandler<void()>&& completionHandler)
@@ -1763,14 +1941,20 @@ void WebsiteDataStore::setResourceLoadStatisticsFirstPartyWebsiteDataRemovalMode
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     auto mode = enabled ? WebCore::FirstPartyWebsiteDataRemovalMode::AllButCookies : WebCore::FirstPartyWebsiteDataRemovalMode::None;
 
-    networkProcess().setFirstPartyWebsiteDataRemovalModeForTesting(m_sessionID, mode, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->setFirstPartyWebsiteDataRemovalModeForTesting(m_sessionID, mode, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setResourceLoadStatisticsToSameSiteStrictCookiesForTesting(const URL& url, CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setToSameSiteStrictCookiesForTesting(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->setToSameSiteStrictCookiesForTesting(m_sessionID, WebCore::RegistrableDomain { url }, [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setResourceLoadStatisticsFirstPartyHostCNAMEDomainForTesting(const URL& firstPartyURL, const URL& cnameURL, CompletionHandler<void()>&& completionHandler)
@@ -1782,7 +1966,8 @@ void WebsiteDataStore::setResourceLoadStatisticsFirstPartyHostCNAMEDomainForTest
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setFirstPartyHostCNAMEDomainForTesting(m_sessionID, firstPartyURL.host().toString(), WebCore::RegistrableDomain { cnameURL }, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setFirstPartyHostCNAMEDomainForTesting(m_sessionID, firstPartyURL.host().toString(), WebCore::RegistrableDomain { cnameURL }, [callbackAggregator] { });
 }
 
 void WebsiteDataStore::setResourceLoadStatisticsThirdPartyCNAMEDomainForTesting(const URL& cnameURL, CompletionHandler<void()>&& completionHandler)
@@ -1794,13 +1979,18 @@ void WebsiteDataStore::setResourceLoadStatisticsThirdPartyCNAMEDomainForTesting(
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setThirdPartyCNAMEDomainForTesting(m_sessionID, WebCore::RegistrableDomain { cnameURL }, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setThirdPartyCNAMEDomainForTesting(m_sessionID, WebCore::RegistrableDomain { cnameURL }, [callbackAggregator] { });
 }
 #endif // ENABLE(RESOURCE_LOAD_STATISTICS)
 
 void WebsiteDataStore::syncLocalStorage(CompletionHandler<void()>&& completionHandler)
 {
-    networkProcess().sendWithAsyncReply(Messages::NetworkProcess::SyncLocalStorage(), WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->sendWithAsyncReply(Messages::NetworkProcess::SyncLocalStorage(), [callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::setCacheMaxAgeCapForPrevalentResources(Seconds seconds, CompletionHandler<void()>&& completionHandler)
@@ -1808,7 +1998,8 @@ void WebsiteDataStore::setCacheMaxAgeCapForPrevalentResources(Seconds seconds, C
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setCacheMaxAgeCapForPrevalentResources(m_sessionID, seconds, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setCacheMaxAgeCapForPrevalentResources(m_sessionID, seconds, [callbackAggregator] { });
 #else
     UNUSED_PARAM(seconds);
     completionHandler();
@@ -1818,12 +2009,26 @@ void WebsiteDataStore::setCacheMaxAgeCapForPrevalentResources(Seconds seconds, C
 void WebsiteDataStore::resetCacheMaxAgeCapForPrevalentResources(CompletionHandler<void()>&& completionHandler)
 {
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
-    networkProcess().resetCacheMaxAgeCapForPrevalentResources(m_sessionID, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->resetCacheMaxAgeCapForPrevalentResources(m_sessionID, [callbackAggregator] { });
+    }
 #else
     completionHandler();
 #endif
 }
 
+bool WebsiteDataStore::isAssociatedProcessPool(WebProcessPool& processPool) const
+{
+    if (auto* processPoolDataStore = processPool.websiteDataStore())
+        return processPoolDataStore == this;
+    if (auto* networkProcessProxy = processPool.networkProcess())
+        return networkProcessProxy->hasSession(m_sessionID);
+    return false;
+}
+
 HashSet<RefPtr<WebProcessPool>> WebsiteDataStore::processPools(size_t limit) const
 {
     HashSet<RefPtr<WebProcessPool>> processPools;
@@ -1838,6 +2043,9 @@ HashSet<RefPtr<WebProcessPool>> WebsiteDataStore::processPools(size_t limit) con
     if (processPools.isEmpty()) {
         // Check if we're one of the legacy data stores.
         for (auto& processPool : WebProcessPool::allProcessPools()) {
+            if (!isAssociatedProcessPool(*processPool))
+                continue;
+
             processPools.add(processPool);
             if (processPools.size() == limit)
                 break;
@@ -1876,7 +2084,8 @@ static String computeMediaKeyFile(const String& mediaKeyDirectory)
 
 void WebsiteDataStore::allowSpecificHTTPSCertificateForHost(const WebCertificateInfo* certificate, const String& host)
 {
-    networkProcess().send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().send(Messages::NetworkProcess::AllowSpecificHTTPSCertificateForHost(certificate->certificateInfo(), host), 0);
 }
 
 Vector<WebCore::SecurityOriginData> WebsiteDataStore::mediaKeyOrigins(const String& mediaKeysStorageDirectory)
@@ -1931,52 +2140,6 @@ void WebsiteDataStore::removeMediaKeys(const String& mediaKeysStorageDirectory,
     }
 }
 
-void WebsiteDataStore::getNetworkProcessConnection(WebProcessProxy& webProcessProxy, CompletionHandler<void(const NetworkProcessConnectionInfo&)>&& reply)
-{
-    networkProcess().getNetworkProcessConnection(webProcessProxy, [this, weakThis = makeWeakPtr(*this), webProcessProxy = makeWeakPtr(webProcessProxy), reply = WTFMove(reply)] (auto& connectionInfo) mutable {
-        if (UNLIKELY(!IPC::Connection::identifierIsValid(connectionInfo.identifier()) && webProcessProxy && weakThis)) {
-            terminateNetworkProcess();
-            RELEASE_LOG_IF(isPersistent(), Process, "getNetworkProcessConnection: Failed first attempt, retrying");
-            networkProcess().getNetworkProcessConnection(*webProcessProxy, WTFMove(reply));
-            return;
-        }
-        reply(connectionInfo);
-    });
-}
-
-void WebsiteDataStore::networkProcessCrashed(NetworkProcessProxy&)
-{
-    if (m_networkProcess)
-        m_networkProcess->didTerminate();
-    m_networkProcess = nullptr;
-}
-
-void WebsiteDataStore::terminateNetworkProcess()
-{
-    for (auto* processPool : WebProcessPool::allProcessPools())
-        processPool->terminateServiceWorkers();
-
-    if (!m_networkProcess)
-        return;
-    m_networkProcess->terminate();
-    m_networkProcess = nullptr;
-}
-
-void WebsiteDataStore::sendNetworkProcessPrepareToSuspendForTesting(CompletionHandler<void()>&& completionHandler)
-{
-    networkProcess().sendPrepareToSuspend(IsSuspensionImminent::No, WTFMove(completionHandler));
-}
-
-void WebsiteDataStore::sendNetworkProcessWillSuspendImminentlyForTesting()
-{
-    networkProcess().sendProcessWillSuspendImminentlyForTesting();
-}
-
-void WebsiteDataStore::sendNetworkProcessDidResume()
-{
-    networkProcess().sendProcessDidResume();
-}
-
 bool WebsiteDataStore::resourceLoadStatisticsEnabled() const
 {
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
@@ -2006,15 +2169,17 @@ void WebsiteDataStore::setResourceLoadStatisticsEnabled(bool enabled)
         
         resolveDirectoriesIfNecessary();
         
-        networkProcess().send(Messages::NetworkProcess::SetResourceLoadStatisticsEnabled(m_sessionID, true), 0);
-        for (auto& processPool : processPools())
+        for (auto& processPool : processPools()) {
+            processPool->sendToNetworkingProcess(Messages::NetworkProcess::SetResourceLoadStatisticsEnabled(m_sessionID, true));
             processPool->sendToAllProcessesForSession(Messages::WebProcess::SetResourceLoadStatisticsEnabled(true), m_sessionID);
+        }
         return;
     }
 
-    networkProcess().send(Messages::NetworkProcess::SetResourceLoadStatisticsEnabled(m_sessionID, false), 0);
-    for (auto& processPool : processPools())
+    for (auto& processPool : processPools()) {
+        processPool->sendToNetworkingProcess(Messages::NetworkProcess::SetResourceLoadStatisticsEnabled(m_sessionID, false));
         processPool->sendToAllProcessesForSession(Messages::WebProcess::SetResourceLoadStatisticsEnabled(false), m_sessionID);
+    }
 
     m_resourceLoadStatisticsEnabled = false;
 #else
@@ -2026,7 +2191,8 @@ void WebsiteDataStore::setResourceLoadStatisticsEnabled(bool enabled)
 void WebsiteDataStore::setStatisticsTestingCallback(Function<void(const String&)>&& callback)
 {
     if (callback) {
-        networkProcess().send(Messages::NetworkProcess::SetResourceLoadStatisticsLogTestingEvent(true), 0);
+        for (auto& processPool : processPools())
+            processPool->sendToNetworkingProcess(Messages::NetworkProcess::SetResourceLoadStatisticsLogTestingEvent(true));
     }
     
     m_statisticsTestingCallback = WTFMove(callback);
@@ -2045,7 +2211,8 @@ void WebsiteDataStore::setResourceLoadStatisticsDebugMode(bool enabled, Completi
 
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
     
-    networkProcess().setResourceLoadStatisticsDebugMode(m_sessionID, enabled, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setResourceLoadStatisticsDebugMode(m_sessionID, enabled, [callbackAggregator] { });
 #else
     UNUSED_PARAM(enabled);
     UNUSED_PARAM(completionHandler);
@@ -2060,15 +2227,20 @@ void WebsiteDataStore::isResourceLoadStatisticsEphemeral(CompletionHandler<void(
         return;
     }
 
-    networkProcess().isResourceLoadStatisticsEphemeral(m_sessionID, WTFMove(completionHandler));
-#else
-    completionHandler(false);
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess()) {
+            networkProcess->isResourceLoadStatisticsEphemeral(m_sessionID, WTFMove(completionHandler));
+            return;
+        }
+    }
 #endif
+    completionHandler(false);
 }
 
 void WebsiteDataStore::setAdClickAttributionDebugMode(bool enabled)
 {
-    networkProcess().setAdClickAttributionDebugMode(enabled);
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().setAdClickAttributionDebugMode(enabled);
 }
 
 #if ENABLE(RESOURCE_LOAD_STATISTICS)
@@ -2090,19 +2262,48 @@ void WebsiteDataStore::clearResourceLoadStatisticsInWebProcesses(CompletionHandl
 }
 #endif
 
+Vector<WebCore::Cookie> WebsiteDataStore::pendingCookies() const
+{
+    return copyToVector(m_pendingCookies);
+}
+
+void WebsiteDataStore::addPendingCookie(const WebCore::Cookie& cookie)
+{
+    m_pendingCookies.removeIf([&cookie](auto& pendingCookie) {
+        return pendingCookie.isKeyEqual(cookie);
+    });
+    m_pendingCookies.add(cookie);
+}
+
+void WebsiteDataStore::removePendingCookie(const WebCore::Cookie& cookie)
+{
+    m_pendingCookies.remove(cookie);
+}
+    
+void WebsiteDataStore::clearPendingCookies()
+{
+    m_pendingCookies.clear();
+}
+
 void WebsiteDataStore::flushCookies(CompletionHandler<void()>&& completionHandler)
 {
-    networkProcess().flushCookies(sessionID(), WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    for (auto processPool : WebProcessPool::allProcessPools())
+        processPool->flushCookies(sessionID(), [callbackAggregator] { });
 }
 
 void WebsiteDataStore::setAllowsAnySSLCertificateForWebSocket(bool allows)
 {
-    networkProcess().sendSync(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply(), 0);
+    for (auto processPool : WebProcessPool::allProcessPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->sendSync(Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket(allows), Messages::NetworkProcess::SetAllowsAnySSLCertificateForWebSocket::Reply(), 0);
+    }
 }
 
 void WebsiteDataStore::clearCachedCredentials()
 {
-    networkProcess().send(Messages::NetworkProcess::ClearCachedCredentials(sessionID()), 0);
+    for (auto processPool : WebProcessPool::allProcessPools())
+        processPool->clearCachedCredentials(sessionID());
 }
 
 void WebsiteDataStore::dispatchOnQueue(Function<void()>&& function)
@@ -2128,6 +2329,8 @@ WebsiteDataStoreParameters WebsiteDataStore::parameters()
 
     resolveDirectoriesIfNecessary();
 
+    parameters.pendingCookies = pendingCookies();
+
     auto resourceLoadStatisticsDirectory = m_configuration->resourceLoadStatisticsDirectory();
     SandboxExtension::Handle resourceLoadStatisticsDirectoryHandle;
     if (!resourceLoadStatisticsDirectory.isEmpty())
@@ -2232,10 +2435,7 @@ WebsiteDataStoreParameters WebsiteDataStore::parameters()
     parameters.networkSessionParameters.resourceLoadStatisticsParameters.enabled = m_resourceLoadStatisticsEnabled;
 #endif
     platformSetNetworkParameters(parameters);
-#if PLATFORM(COCOA)
-    parameters.networkSessionParameters.appHasRequestedCrossWebsiteTrackingPermission = hasRequestedCrossWebsiteTrackingPermission();
-#endif
-    
+
     return parameters;
 }
 
@@ -2265,6 +2465,10 @@ API::HTTPCookieStore& WebsiteDataStore::cookieStore()
     return *m_cookieStore;
 }
 
+void WebsiteDataStore::didCreateNetworkProcess()
+{
+}
+
 void WebsiteDataStore::getLocalStorageDetails(Function<void(Vector<LocalStorageDatabaseTracker::OriginDetails>&&)>&& completionHandler)
 {
     if (!isPersistent()) {
@@ -2272,15 +2476,23 @@ void WebsiteDataStore::getLocalStorageDetails(Function<void(Vector<LocalStorageD
         return;
     }
 
-    networkProcess().getLocalStorageDetails(m_sessionID, [completionHandler = WTFMove(completionHandler)](auto&& details) {
-        completionHandler(WTFMove(details));
-    });
+    for (auto& processPool : ensureProcessPools()) {
+        processPool->ensureNetworkProcess(this).getLocalStorageDetails(m_sessionID, [completionHandler = WTFMove(completionHandler)](auto&& details) {
+            completionHandler(WTFMove(details));
+        });
+        // FIXME: Support fetching from multiple pools.
+        break;
+    }
+    ASSERT(!completionHandler);
 }
 
 void WebsiteDataStore::resetQuota(CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
-    networkProcess().resetQuota(m_sessionID, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* process = processPool->networkProcess())
+            process->resetQuota(m_sessionID, [callbackAggregator] { });
+    }
 }
 
 #if !PLATFORM(COCOA)
@@ -2306,12 +2518,7 @@ bool WebsiteDataStore::http3Enabled()
 {
     return false;
 }
-
-bool WebsiteDataStore::networkProcessHasEntitlementForTesting(const String&)
-{
-    return false;
-}
-#endif // !PLATFORM(COCOA)
+#endif
 
 #if !USE(GLIB)
 WTF::String WebsiteDataStore::defaultDeviceIdHashSaltsStorageDirectory()
@@ -2323,18 +2530,35 @@ WTF::String WebsiteDataStore::defaultDeviceIdHashSaltsStorageDirectory()
 
 void WebsiteDataStore::renameOriginInWebsiteData(URL&& oldName, URL&& newName, OptionSet<WebsiteDataType> dataTypes, CompletionHandler<void()>&& completionHandler)
 {
-    networkProcess().renameOriginInWebsiteData(m_sessionID, oldName, newName, dataTypes, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+    for (auto& processPool : WebProcessPool::allProcessPools()) {
+        if (auto* networkProcess = processPool->networkProcess()) {
+            networkProcess->addSession(*this);
+            networkProcess->renameOriginInWebsiteData(m_sessionID, oldName, newName, dataTypes, [callbackAggregator] { });
+        }
+    }
 }
 
 #if ENABLE(APP_BOUND_DOMAINS)
 void WebsiteDataStore::hasAppBoundSession(CompletionHandler<void(bool)>&& completionHandler) const
 {
-    networkProcess().hasAppBoundSession(m_sessionID, WTFMove(completionHandler));
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess()) {
+            networkProcess->hasAppBoundSession(m_sessionID, WTFMove(completionHandler));
+            return;
+        }
+    }
+    completionHandler(false);
 }
 
 void WebsiteDataStore::clearAppBoundSession(CompletionHandler<void()>&& completionHandler)
 {
-    networkProcess().clearAppBoundSession(m_sessionID, WTFMove(completionHandler));
+    auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
+
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->clearAppBoundSession(m_sessionID, [processPool, callbackAggregator] { });
+    }
 }
 
 void WebsiteDataStore::forwardAppBoundDomainsToITPIfInitialized(CompletionHandler<void()>&& completionHandler)
@@ -2356,7 +2580,7 @@ void WebsiteDataStore::forwardAppBoundDomainsToITPIfInitialized(CompletionHandle
 
     propagateAppBoundDomains(globalDefaultDataStore().get(), *appBoundDomains);
 
-    for (auto* store : allDataStores().values())
+    for (auto* store : nonDefaultDataStores().values())
         propagateAppBoundDomains(store, *appBoundDomains);
 }
 
@@ -2364,7 +2588,10 @@ void WebsiteDataStore::setAppBoundDomainsForITP(const HashSet<WebCore::Registrab
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().setAppBoundDomainsForResourceLoadStatistics(m_sessionID, domains, [callbackAggregator] { });
+    for (auto& processPool : processPools()) {
+        if (auto* networkProcess = processPool->networkProcess())
+            networkProcess->setAppBoundDomainsForResourceLoadStatistics(m_sessionID, domains, [callbackAggregator] { });
+    }
 }
 #endif
 
@@ -2372,26 +2599,16 @@ void WebsiteDataStore::updateBundleIdentifierInNetworkProcess(const String& bund
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().updateBundleIdentifier(bundleIdentifier, [callbackAggregator] { });
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().updateBundleIdentifier(bundleIdentifier, [callbackAggregator] { });
 }
 
 void WebsiteDataStore::clearBundleIdentifierInNetworkProcess(CompletionHandler<void()>&& completionHandler)
 {
     auto callbackAggregator = CallbackAggregator::create(WTFMove(completionHandler));
 
-    networkProcess().clearBundleIdentifier([callbackAggregator] { });
-}
-
-static bool nextNetworkProcessLaunchShouldFailForTesting { false };
-
-void WebsiteDataStore::makeNextNetworkProcessLaunchFailForTesting()
-{
-    nextNetworkProcessLaunchShouldFailForTesting = true;
-}
-
-bool WebsiteDataStore::shouldMakeNextNetworkProcessLaunchFailForTesting()
-{
-    return std::exchange(nextNetworkProcessLaunchShouldFailForTesting, false);
+    for (auto& processPool : processPools())
+        processPool->ensureNetworkProcess().clearBundleIdentifier([callbackAggregator] { });
 }
 
 }
index b8361ac..e9deba4 100644 (file)
@@ -53,8 +53,6 @@
 
 #if PLATFORM(COCOA)
 #include <pal/spi/cf/CFNetworkSPI.h>
-#include <wtf/OSObjectPtr.h>
-#include <wtf/spi/darwin/XPCSPI.h>
 #endif
 
 #if USE(CURL)
@@ -81,7 +79,6 @@ namespace WebKit {
 class AuthenticatorManager;
 class SecKeyProxyStore;
 class DeviceIdHashSaltStorage;
-class NetworkProcessProxy;
 class SOAuthorizationCoordinator;
 class WebCertificateInfo;
 class WebPageProxy;
@@ -91,8 +88,6 @@ class WebResourceLoadStatisticsStore;
 enum class CacheModel : uint8_t;
 enum class WebsiteDataFetchOption : uint8_t;
 enum class WebsiteDataType : uint32_t;
-
-struct NetworkProcessConnectionInfo;
 struct WebsiteDataRecord;
 struct WebsiteDataStoreParameters;
 
@@ -118,12 +113,7 @@ public:
     WebsiteDataStore(Ref<WebsiteDataStoreConfiguration>&&, PAL::SessionID);
     ~WebsiteDataStore();
 
-    static void forEachWebsiteDataStore(Function<void(WebsiteDataStore&)>&&);
-    
-    NetworkProcessProxy& networkProcess() const;
-    NetworkProcessProxy& networkProcess();
-
-    static WebsiteDataStore* existingDataStoreForSessionID(PAL::SessionID);
+    static WebsiteDataStore* existingNonDefaultDataStoreForSessionID(PAL::SessionID);
 
     bool isPersistent() const { return !m_sessionID.isEphemeral(); }
     PAL::SessionID sessionID() const { return m_sessionID; }
@@ -133,15 +123,6 @@ public:
     
     const WeakHashSet<WebProcessProxy>& processes() const { return m_processes; }
 
-    void getNetworkProcessConnection(WebProcessProxy&, CompletionHandler<void(const NetworkProcessConnectionInfo&)>&&);
-    void terminateNetworkProcess();
-    void sendNetworkProcessPrepareToSuspendForTesting(CompletionHandler<void()>&&);
-    void sendNetworkProcessWillSuspendImminentlyForTesting();
-    void sendNetworkProcessDidResume();
-    void networkProcessCrashed(NetworkProcessProxy&);
-    static void makeNextNetworkProcessLaunchFailForTesting();
-    static bool shouldMakeNextNetworkProcessLaunchFailForTesting();
-
     bool resourceLoadStatisticsEnabled() const;
     void setResourceLoadStatisticsEnabled(bool);
     bool resourceLoadStatisticsDebugMode() const;
@@ -258,8 +239,15 @@ public:
 
     DeviceIdHashSaltStorage& deviceIdHashSaltStorage() { return m_deviceIdHashSaltStorage.get(); }
 
+    WebProcessPool* processPoolForCookieStorageOperations();
+    bool isAssociatedProcessPool(WebProcessPool&) const;
+
     WebsiteDataStoreParameters parameters();
 
+    Vector<WebCore::Cookie> pendingCookies() const;
+    void addPendingCookie(const WebCore::Cookie&);
+    void removePendingCookie(const WebCore::Cookie&);
+    void clearPendingCookies();
     void flushCookies(CompletionHandler<void()>&&);
     void clearCachedCredentials();
 
@@ -267,11 +255,6 @@ public:
 
     void dispatchOnQueue(Function<void()>&&);
 
-#if PLATFORM(COCOA)
-    void sendNetworkProcessXPCEndpointToWebProcess(WebProcessProxy&);
-    void sendNetworkProcessXPCEndpointToAllWebProcesses();
-#endif
-
 #if USE(CURL)
     void setNetworkProxySettings(WebCore::CurlProxySettings&&);
     const WebCore::CurlProxySettings& networkProxySettings() const { return m_proxySettings; }
@@ -297,6 +280,8 @@ public:
     void setMockWebAuthenticationConfiguration(WebCore::MockWebAuthenticationConfiguration&&);
 #endif
 
+    void didCreateNetworkProcess();
+
     const WebsiteDataStoreConfiguration& configuration() { return m_configuration.get(); }
 
     WebsiteDataStoreClient& client() { return m_client.get(); }
@@ -306,8 +291,6 @@ public:
 
     void renameOriginInWebsiteData(URL&&, URL&&, OptionSet<WebsiteDataType>, CompletionHandler<void()>&&);
 
-    bool networkProcessHasEntitlementForTesting(const String&);
-
 #if ENABLE(DEVICE_ORIENTATION)
     WebDeviceOrientationAndMotionAccessController& deviceOrientationAndMotionAccessController() { return m_deviceOrientationAndMotionAccessController; }
 #endif
@@ -384,7 +367,7 @@ private:
     static void removeMediaKeys(const String& mediaKeysStorageDirectory, WallTime modifiedSince);
     static void removeMediaKeys(const String& mediaKeysStorageDirectory, const HashSet<WebCore::SecurityOriginData>&);
 
-    void registerWithSessionIDMap();
+    void maybeRegisterWithSessionIDMap();
 
 #if ENABLE(APP_BOUND_DOMAINS)
     static Optional<HashSet<WebCore::RegistrableDomain>> appBoundDomainsIfInitialized();
@@ -424,6 +407,8 @@ private:
     WebCore::SoupNetworkProxySettings m_networkProxySettings;
 #endif
 
+    HashSet<WebCore::Cookie> m_pendingCookies;
+    
     WeakHashSet<WebProcessProxy> m_processes;
 
     bool m_isItpStateExplicitlySet { false };
@@ -444,7 +429,6 @@ private:
     UniqueRef<WebsiteDataStoreClient> m_client;
 
     RefPtr<API::HTTPCookieStore> m_cookieStore;
-    RefPtr<NetworkProcessProxy> m_networkProcess;
 
 #if HAVE(APP_SSO)
     UniqueRef<SOAuthorizationCoordinator> m_soAuthorizationCoordinator;
index 64b6c74..0e0c06e 100644 (file)
@@ -42,7 +42,8 @@ void WebsiteDataStore::setNetworkProxySettings(WebCore::CurlProxySettings&& prox
 {
     m_proxySettings = WTFMove(proxySettings);
 
-    networkProcess().send(Messages::NetworkProcess::SetNetworkProxySettings(m_sessionID, m_proxySettings), 0);
+    for (auto& processPool : processPools())
+        processPool->sendToNetworkingProcess(Messages::NetworkProcess::SetNetworkProxySettings(m_sessionID, m_proxySettings));
 }
 
 }
index 704a9b6..14d7ff4 100644 (file)
@@ -42,7 +42,8 @@ void WebsiteDataStore::platformSetNetworkParameters(WebsiteDataStoreParameters&
     networkSessionParameters.ignoreTLSErrors = m_ignoreTLSErrors;
     networkSessionParameters.proxySettings = m_networkProxySettings;
 
-    networkProcess().cookieManager().getCookiePersistentStorage(m_sessionID, networkSessionParameters.cookiePersistentStoragePath, networkSessionParameters.cookiePersistentStorageType);
+    if (auto* processPool = processPoolForCookieStorageOperations())
+        processPool->supplement<WebCookieManagerProxy>()->getCookiePersistentStorage(m_sessionID, networkSessionParameters.cookiePersistentStoragePath, networkSessionParameters.cookiePersistentStorageType);
 }
 
 void WebsiteDataStore::setPersistentCredentialStorageEnabled(bool enabled)
@@ -54,7 +55,8 @@ void WebsiteDataStore::setPersistentCredentialStorageEnabled(bool enabled)
         return;
 
     m_persistentCredentialStorageEnabled = enabled;
-    networkProcess().send(Messages::NetworkProcess::SetPersistentCredentialStorageEnabled(m_sessionID, m_persistentCredentialStorageEnabled), 0);
+    for (auto& processPool : processPools())
+        processPool->sendToNetworkingProcess(Messages::NetworkProcess::SetPersistentCredentialStorageEnabled(m_sessionID, m_persistentCredentialStorageEnabled));
 }
 
 void WebsiteDataStore::setIgnoreTLSErrors(bool ignoreTLSErrors)
@@ -63,13 +65,15 @@ void WebsiteDataStore::setIgnoreTLSErrors(bool ignoreTLSErrors)
         return;
 
     m_ignoreTLSErrors = ignoreTLSErrors;
-    networkProcess().send(Messages::NetworkProcess::SetIgnoreTLSErrors(m_sessionID, m_ignoreTLSErrors), 0);
+    for (auto& processPool : processPools())
+        processPool->sendToNetworkingProcess(Messages::NetworkProcess::SetIgnoreTLSErrors(m_sessionID, m_ignoreTLSErrors));
 }
 
 void WebsiteDataStore::setNetworkProxySettings(WebCore::SoupNetworkProxySettings&& settings)
 {
     m_networkProxySettings = WTFMove(settings);
-    networkProcess().send(Messages::NetworkProcess::SetNetworkProxySettings(m_sessionID, m_networkProxySettings), 0);
+    for (auto& processPool : processPools())
+        processPool->sendToNetworkingProcess(Messages::NetworkProcess::SetNetworkProxySettings(m_sessionID, m_networkProxySettings));
 }
 
 } // namespace WebKit
index 27f23ea..0a84a75 100644 (file)
@@ -44,7 +44,7 @@ void WebProcessProxy::platformGetLaunchOptions(ProcessLauncher::LaunchOptions& l
         if (!dataStore) {
             // Prewarmed processes don't have a WebsiteDataStore yet, so use the primary WebsiteDataStore from the WebProcessPool.
             // The process won't be used if current WebsiteDataStore is different than the WebProcessPool primary one.
-            dataStore = WebsiteDataStore::defaultDataStore().ptr();
+            dataStore = m_processPool->websiteDataStore();
         }
 
         ASSERT(dataStore);
index ac04e38..9f7be3c 100644 (file)
@@ -26,7 +26,6 @@
 #include "config.h"
 #include "WebCookieManagerProxy.h"
 
-#include "NetworkProcessProxy.h"
 #include "WebCookieManagerMessages.h"
 #include "WebProcessPool.h"
 
@@ -34,8 +33,8 @@ namespace WebKit {
 
 void WebCookieManagerProxy::setCookiePersistentStorage(PAL::SessionID sessionID, const String& storagePath, SoupCookiePersistentStorageType storageType)
 {
-    if (m_networkProcess)
-        m_networkProcess->send(Messages::WebCookieManager::SetCookiePersistentStorage(sessionID, storagePath, storageType), 0);
+    m_cookiePersistentStorageMap.set(sessionID, std::make_pair(storagePath, storageType));
+    processPool()->sendToNetworkingProcess(Messages::WebCookieManager::SetCookiePersistentStorage(sessionID, storagePath, storageType));
 }
 
 void WebCookieManagerProxy::getCookiePersistentStorage(PAL::SessionID sessionID, String& storagePath, SoupCookiePersistentStorageType& storageType) const
index 081f5be..6b7c5b4 100644 (file)
@@ -37,6 +37,15 @@ namespace WebKit {
 
 void WebProcessPool::platformInitializeNetworkProcess(NetworkProcessCreationParameters& parameters)
 {
+    NetworkSessionCreationParameters& defaultSessionParameters = parameters.defaultDataStoreParameters.networkSessionParameters;
+    supplement<WebCookieManagerProxy>()->getCookiePersistentStorage(defaultSessionParameters.sessionID, defaultSessionParameters.cookiePersistentStoragePath, defaultSessionParameters.cookiePersistentStorageType);
+    if (m_websiteDataStore) {
+        defaultSessionParameters.persistentCredentialStorageEnabled = m_websiteDataStore->persistentCredentialStorageEnabled();
+        defaultSessionParameters.ignoreTLSErrors = m_websiteDataStore->ignoreTLSErrors();
+        defaultSessionParameters.proxySettings = m_websiteDataStore->networkProxySettings();
+    }
+
+    parameters.cookieAcceptPolicy = m_initialHTTPCookieAcceptPolicy;
     parameters.languages = userPreferredLanguages();
     parameters.shouldEnableITPDatabase = true;
 }
index bad74c4..1c93dec 100644 (file)
@@ -1,5 +1,18 @@
 2020-09-25  Alex Christensen  <achristensen@webkit.org>
 
+        Unreviewed, reverting r267608.
+
+        Caused API test failures
+
+        Reverted changeset:
+
+        "Move NetworkProcessProxy ownership from WebProcessPool to
+        WebsiteDataStore"
+        https://bugs.webkit.org/show_bug.cgi?id=216041
+        https://trac.webkit.org/changeset/267608
+
+2020-09-25  Alex Christensen  <achristensen@webkit.org>
+
         Move NetworkProcessProxy ownership from WebProcessPool to WebsiteDataStore
         https://bugs.webkit.org/show_bug.cgi?id=216041
 
index 97b72e0..97389f0 100644 (file)
@@ -32,7 +32,6 @@
 #import <WebKit/WKProcessGroupPrivate.h>
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKWebViewPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <wtf/RetainPtr.h>
 
@@ -88,7 +87,7 @@ TEST(WebKit, NetworkProcessCrashWithPendingConnection)
     pid_t webView2PID = [webView2.get() _webProcessIdentifier];
     EXPECT_NE(webView1PID, webView2PID);
 
-    pid_t initialNetworkProcessIdentififer = [configuration.get().websiteDataStore _networkProcessIdentifier];
+    pid_t initialNetworkProcessIdentififer = [processPool.get() _networkProcessIdentifier];
     EXPECT_NE(initialNetworkProcessIdentififer, 0);
     kill(initialNetworkProcessIdentififer, SIGKILL);
     Util::run(&networkProcessCrashed);
@@ -97,7 +96,7 @@ TEST(WebKit, NetworkProcessCrashWithPendingConnection)
     [webView1.get() loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"simple" withExtension:@"html" subdirectory:@"TestWebKitAPI.resources"]]];
     [webView1.get() _test_waitForDidFinishNavigation];
 
-    pid_t relaunchedNetworkProcessIdentifier = [configuration.get().websiteDataStore _networkProcessIdentifier];
+    pid_t relaunchedNetworkProcessIdentifier = [processPool.get() _networkProcessIdentifier];
     EXPECT_NE(initialNetworkProcessIdentififer, relaunchedNetworkProcessIdentifier);
     EXPECT_FALSE(networkProcessCrashed);
 
@@ -147,8 +146,8 @@ TEST(WebKit, NetworkProcessRelaunchOnLaunchFailure)
 
     // Constucting a WebView starts a network process so terminate this one. The page load below will then request a network process and we
     // make this new network process launch crash on startup.
-    [WKWebsiteDataStore _makeNextNetworkProcessLaunchFailForTesting];
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [processPool _terminateNetworkProcess];
+    [processPool _makeNextNetworkProcessLaunchFailForTesting];
 
     auto delegate = adoptNS([[MonitorWebContentCrashNavigationDelegate alloc] init]);
     [webView setNavigationDelegate:delegate.get()];
@@ -159,7 +158,7 @@ TEST(WebKit, NetworkProcessRelaunchOnLaunchFailure)
     EXPECT_TRUE(networkProcessCrashed);
     EXPECT_FALSE(webProcessCrashed);
     EXPECT_GT([webView _webProcessIdentifier], 0);
-    EXPECT_GT([configuration.get().websiteDataStore _networkProcessIdentifier], 0);
+    EXPECT_GT([processPool.get() _networkProcessIdentifier], 0);
 }
 
 } // namespace TestWebKitAPI
index 1819131..b7ed999 100644 (file)
@@ -889,9 +889,9 @@ void downloadAtRate(double desiredKbps, unsigned speedMultiplier, AppReturnsToFo
     receivedData = false;
     Util::run(&receivedData);
     // Start the DownloadMonitor's timer.
-    [[webView configuration].websiteDataStore _synthesizeAppIsBackground:YES];
+    [[webView configuration].processPool _synthesizeAppIsBackground:YES];
     if (returnToForeground == AppReturnsToForeground::Yes)
-        [[webView configuration].websiteDataStore _synthesizeAppIsBackground:NO];
+        [[webView configuration].processPool _synthesizeAppIsBackground:NO];
     didCancel = false;
     Util::run(&didCancel);
     terminateServer = true;
index d77a6fd..5cd7abd 100644 (file)
@@ -31,7 +31,6 @@
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <WebKit/_WKUserStyleSheet.h>
@@ -87,7 +86,7 @@ TEST(IndexedDB, CheckpointsWALAutomatically)
     RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
     [[configuration userContentController] addScriptMessageHandler:handler.get() name:@"testHandler"];
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     RetainPtr<WKWebView> webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
 
index bbf1a15..c8af1d2 100644 (file)
@@ -30,7 +30,6 @@
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <WebKit/_WKUserStyleSheet.h>
@@ -58,7 +57,7 @@ TEST(IndexedDB, DeleteRecovery)
     RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
     [[configuration userContentController] addScriptMessageHandler:handler.get() name:@"testHandler"];
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     // Copy the inconsistent database files to the database directory
     NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"IDBDeleteRecovery" withExtension:@"sqlite3" subdirectory:@"TestWebKitAPI.resources"];
index 88a53f6..95cca0c 100644 (file)
@@ -31,7 +31,6 @@
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <WebKit/_WKUserStyleSheet.h>
@@ -59,7 +58,7 @@ TEST(IndexedDB, IndexUpgradeToV2)
     RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
     [[configuration userContentController] addScriptMessageHandler:handler.get() name:@"testHandler"];
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     // Copy the inconsistent database files to the database directory
     NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"IndexUpgrade" withExtension:@"sqlite3" subdirectory:@"TestWebKitAPI.resources"];
index 403e0ff..ffa5a78 100644 (file)
@@ -31,7 +31,6 @@
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <WebKit/_WKUserStyleSheet.h>
@@ -58,7 +57,7 @@ TEST(IndexedDB, IDBObjectStoreInfoUpgradeToV2)
     RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
     [[configuration userContentController] addScriptMessageHandler:handler.get() name:@"testHandler"];
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     // Copy database files with old ObjectStoreInfo schema to the database directory.
     NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"IDBObjectStoreInfoUpgrade" withExtension:@"sqlite3" subdirectory:@"TestWebKitAPI.resources"];
index 73077ec..6874529 100644 (file)
@@ -31,7 +31,6 @@
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <wtf/RetainPtr.h>
@@ -93,7 +92,7 @@ TEST(IndexedDB, DatabaseProcessKill)
         TestWebKitAPI::Util::run(&receivedScriptMessage);
         if (!killedDBProcess && openRequestUpgradeNeeded) {
             killedDBProcess = true;
-            [configuration.get().websiteDataStore _terminateNetworkProcess];
+            [configuration.get().processPool _terminateNetworkProcess];
         }
     }
 
index 6f67dc2..7f62645 100644 (file)
@@ -32,7 +32,6 @@
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
 #import <WebKit/WKWebViewPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <WebKit/_WKUserStyleSheet.h>
 #import <wtf/Deque.h>
@@ -70,7 +69,7 @@ TEST(IndexedDB, IndexedDBMultiProcess)
     RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
     [[configuration userContentController] addScriptMessageHandler:handler.get() name:@"testHandler"];
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     RetainPtr<WKWebView> webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
 
index d622032..b32ce4a 100644 (file)
@@ -78,7 +78,7 @@ TEST(IndexedDB, IndexedDBPersistence)
     webView = nil;
 
     // Terminate the network process
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     // Make a new web view to finish the test
     webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
@@ -268,7 +268,7 @@ TEST(IndexedDB, IndexedDBThirdPartyFrameHasAccess)
 
     webView = nil;
     secondWebView = nil;
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     // Third-party IDB storage is stored in the memory of network process.
     auto thirdWebView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
@@ -385,7 +385,7 @@ TEST(IndexedDB, IndexedDBThirdPartyWorkerHasAccess)
 
     webView = nil;
     secondWebView = nil;
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     auto thirdWebView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
     loadTestPageInWebView(thirdWebView.get(), @"database is created");
index 510b24f..8ec65f0 100644 (file)
@@ -32,7 +32,6 @@
 #import <WebKit/WKProcessPoolPrivate.h>
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <wtf/RetainPtr.h>
@@ -89,8 +88,8 @@ TEST(IndexedDB, IndexedDBSuspendImminently)
 
     runTestAndCheckResult(@"Continue");
 
-    [configuration.get().websiteDataStore _sendNetworkProcessWillSuspendImminently];
-    [configuration.get().websiteDataStore _sendNetworkProcessDidResume];
+    [configuration.get().processPool _sendNetworkProcessWillSuspendImminently];
+    [configuration.get().processPool _sendNetworkProcessDidResume];
 
     runTestAndCheckResult(@"Expected Abort For Suspension");
     runTestAndCheckResult(@"Expected Success After Resume");
@@ -159,8 +158,8 @@ TEST(IndexedDB, SuspendImminentlyForThirdPartyDatabases)
     [webView loadHTMLString:mainFrameString baseURL:[NSURL URLWithString:@"http://webkit.org"]];
     runTestAndCheckResult(@"database is created");
 
-    [configuration.get().websiteDataStore _sendNetworkProcessWillSuspendImminently];
-    [configuration.get().websiteDataStore _sendNetworkProcessDidResume];
+    [configuration.get().processPool _sendNetworkProcessWillSuspendImminently];
+    [configuration.get().processPool _sendNetworkProcessDidResume];
 
     runTestAndCheckResult(@"transaction is completed");
 }
index e7b9922..536541e 100644 (file)
@@ -95,7 +95,7 @@ TEST(IndexedDB, IndexedDBTempFileSize)
 
     // Terminate network process to keep WAL on disk.
     webView = nil;
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     EXPECT_TRUE([[NSFileManager defaultManager] fileExistsAtPath:walFilePath.get().path]);
     RetainPtr<NSDictionary> fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:walFilePath.get().path error:nil];
index 5f79190..4133ee7 100644 (file)
@@ -31,7 +31,6 @@
 #import <WebKit/WKUserContentControllerPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
 #import <WebKit/WKWebpagePreferencesPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <WebKit/_WKUserStyleSheet.h>
@@ -110,7 +109,7 @@ TEST(WKWebView, LocalStorageProcessCrashes)
     TestWebKitAPI::Util::run(&receivedScriptMessage);
     EXPECT_WK_STREQ(@"session:storage", [lastScriptMessage body]);
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     receivedScriptMessage = false;
     TestWebKitAPI::Util::run(&receivedScriptMessage);
@@ -163,7 +162,7 @@ TEST(WKWebView, LocalStorageProcessSuspends)
     TestWebKitAPI::Util::run(&receivedScriptMessage);
     EXPECT_WK_STREQ(@"value", [lastScriptMessage body]);
 
-    [configuration.get().websiteDataStore _sendNetworkProcessWillSuspendImminently];
+    [processPool.get() _sendNetworkProcessWillSuspendImminently];
 
     readyToContinue = false;
     [webView1 evaluateJavaScript:@"window.localStorage.setItem('key', 'newValue')" completionHandler:^(id, NSError *) {
@@ -178,7 +177,7 @@ TEST(WKWebView, LocalStorageProcessSuspends)
     }];
     TestWebKitAPI::Util::run(&readyToContinue);
     
-    [configuration.get().websiteDataStore _sendNetworkProcessDidResume];
+    [processPool.get() _sendNetworkProcessDidResume];
 
     receivedScriptMessage = false;
     TestWebKitAPI::Util::run(&receivedScriptMessage);
index 0e21f90..e60f880 100644 (file)
@@ -28,7 +28,7 @@
 #import "HTTPServer.h"
 #import "TestWKWebView.h"
 #import "Utilities.h"
-#import <WebKit/WKWebsiteDataStorePrivate.h>
+#import <WebKit/WKProcessPoolPrivate.h>
 #import <wtf/BlockPtr.h>
 #import <wtf/RetainPtr.h>
 #import <wtf/Vector.h>
@@ -37,14 +37,14 @@ TEST(WebKit, NetworkProcessEntitlements)
 {
     auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:[[[WKWebViewConfiguration alloc] init] autorelease]]);
     [webView synchronouslyLoadTestPageNamed:@"simple"];
-    WKWebsiteDataStore *store = [webView configuration].websiteDataStore;
-    bool hasEntitlement = [store _networkProcessHasEntitlementForTesting:@"com.apple.rootless.storage.WebKitNetworkingSandbox"];
+    WKProcessPool *pool = [webView configuration].processPool;
+    bool hasEntitlement = [pool _networkProcessHasEntitlementForTesting:@"com.apple.rootless.storage.WebKitNetworkingSandbox"];
 #if PLATFORM(MAC) && USE(APPLE_INTERNAL_SDK)
     EXPECT_TRUE(hasEntitlement);
 #else
     EXPECT_FALSE(hasEntitlement);
 #endif
-    EXPECT_FALSE([store _networkProcessHasEntitlementForTesting:@"test failure case"]);
+    EXPECT_FALSE([pool _networkProcessHasEntitlementForTesting:@"test failure case"]);
 }
 
 TEST(WebKit, HTTPReferer)
index 2f8a2e3..6098e8d 100644 (file)
@@ -72,7 +72,7 @@ static void checkRecoveryAfterCrash(WKWebsiteDataStore *dataStore)
     TestWebKitAPI::Util::run(&done);
     done = false;
 
-    [[webView configuration].websiteDataStore _terminateNetworkProcess];
+    [[webView configuration].processPool _terminateNetworkProcess];
     [webView loadRequest:[NSURLRequest requestWithURL:simple2]];
     TestWebKitAPI::Util::run(&done);
 }
index 0eeca49..e403062 100644 (file)
@@ -5385,7 +5385,7 @@ TEST(ProcessSwap, UsePrewarmedProcessAfterTerminatingNetworkProcess)
 
     TestWebKitAPI::Util::spinRunLoop(1);
 
-    [webViewConfiguration.get().websiteDataStore _terminateNetworkProcess];
+    [processPool _terminateNetworkProcess];
 
     auto webView2 = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:webViewConfiguration.get()]);
     [webView2 setNavigationDelegate:delegate.get()];
index a3aba23..0e10c34 100644 (file)
@@ -719,7 +719,7 @@ TEST(ResourceLoadStatistics, NetworkProcessRestart)
 
     TestWebKitAPI::Util::spinRunLoop(1);
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     auto webView2 = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
 
@@ -752,7 +752,7 @@ TEST(ResourceLoadStatistics, NetworkProcessRestart)
 
     TestWebKitAPI::Util::spinRunLoop(1);
 
-    [configuration.get().websiteDataStore _terminateNetworkProcess];
+    [configuration.get().processPool _terminateNetworkProcess];
 
     auto webView3 = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
 
@@ -1558,8 +1558,10 @@ TEST(ResourceLoadStatistics, MigrateDataFromMissingTopFrameUniqueRedirectSameSit
 
 TEST(ResourceLoadStatistics, CanAccessDataSummaryWithNoProcessPool)
 {
-    NSURL *itpRootURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"CanAccessDataSummaryWithNoProcessPoolTest"] isDirectory:YES];
     auto defaultFileManager = [NSFileManager defaultManager];
+    _WKWebsiteDataStoreConfiguration *dataStoreConfiguration = [[_WKWebsiteDataStoreConfiguration new] autorelease];
+    auto *dataStore = [[[WKWebsiteDataStore alloc] _initWithConfiguration:dataStoreConfiguration] autorelease];
+    NSURL *itpRootURL = [[dataStore _configuration] _resourceLoadStatisticsDirectory];
     NSURL *fileURL = [itpRootURL URLByAppendingPathComponent:@"observations.db"];
     [defaultFileManager removeItemAtPath:itpRootURL.path error:nil];
     EXPECT_FALSE([defaultFileManager fileExistsAtPath:itpRootURL.path]);
@@ -1570,10 +1572,6 @@ TEST(ResourceLoadStatistics, CanAccessDataSummaryWithNoProcessPool)
     EXPECT_TRUE([defaultFileManager fileExistsAtPath:newFileURL.path]);
     [defaultFileManager copyItemAtPath:newFileURL.path toPath:fileURL.path error:nil];
     EXPECT_TRUE([defaultFileManager fileExistsAtPath:fileURL.path]);
-
-    _WKWebsiteDataStoreConfiguration *dataStoreConfiguration = [[_WKWebsiteDataStoreConfiguration new] autorelease];
-    dataStoreConfiguration._resourceLoadStatisticsDirectory = itpRootURL;
-    auto *dataStore = [[[WKWebsiteDataStore alloc] _initWithConfiguration:dataStoreConfiguration] autorelease];
     [dataStore _setResourceLoadStatisticsEnabled:YES];
 
     static bool doneFlag = false;
@@ -1635,12 +1633,12 @@ TEST(ResourceLoadStatistics, StoreSuspension)
     [webView2 _test_waitForDidFinishNavigation];
 
     doneFlag = false;
-    [dataStore1 _sendNetworkProcessPrepareToSuspend:^{
+    [sharedProcessPool _sendNetworkProcessPrepareToSuspend:^{
         doneFlag = true;
     }];
     TestWebKitAPI::Util::run(&doneFlag);
 
-    [dataStore1 _sendNetworkProcessDidResume];
+    [sharedProcessPool _sendNetworkProcessDidResume];
 }
 
 @interface ResourceLoadStatisticsSchemeHandler : NSObject <WKURLSchemeHandler>
index 5493d3d..34a4f5c 100644 (file)
@@ -558,7 +558,7 @@ TEST(ServiceWorkers, UserAgentOverride)
 
     configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
 
-    messageHandler = adoptNS([[SWUserAgentMessageHandler alloc] initWithExpectedMessage:@"Message from worker: Foo Custom UserAgent"]);
+    messageHandler = adoptNS([[SWUserAgentMessageHandler alloc] initWithExpectedMessage:@"Message from worker: Bar Custom UserAgent"]);
     [[configuration userContentController] addScriptMessageHandler:messageHandler.get() name:@"sw"];
 
     webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
@@ -633,6 +633,8 @@ TEST(ServiceWorkers, CacheStorageRestoreFromDisk)
     TestWebKitAPI::Util::run(&done);
     done = false;
 
+    [WKWebsiteDataStore _deleteDefaultDataStoreForTesting];
+
     ServiceWorkerTCPServer server({
         { "text/html", mainCacheStorageBytes }
     }, {
@@ -980,7 +982,6 @@ TEST(ServiceWorkers, ServiceWorkerProcessCreation)
 
     RetainPtr<WKWebViewConfiguration> configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
     setConfigurationInjectedBundlePath(configuration.get());
-    RetainPtr<WKProcessPool> originalProcessPool = configuration.get().processPool;
 
     done = false;
 
@@ -1034,7 +1035,7 @@ TEST(ServiceWorkers, ServiceWorkerProcessCreation)
     done = false;
 
     // Make sure that loading the simple page did not start the service worker process.
-    EXPECT_EQ(1u, webView.get().configuration.processPool._serviceWorkerProcessCount);
+    EXPECT_EQ(0u, webView.get().configuration.processPool._serviceWorkerProcessCount);
 
     webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:newConfiguration.get()]);
     EXPECT_EQ(2u, webView.get().configuration.processPool._webProcessCountIgnoringPrewarmed);
@@ -1042,8 +1043,9 @@ TEST(ServiceWorkers, ServiceWorkerProcessCreation)
     TestWebKitAPI::Util::run(&done);
     done = false;
 
+    // Make sure that loading this page did start the service worker process.
     EXPECT_EQ(1u, webView.get().configuration.processPool._serviceWorkerProcessCount);
-    EXPECT_EQ(1u, originalProcessPool.get()._serviceWorkerProcessCount);
+
     [[configuration websiteDataStore] removeDataOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] modifiedSince:[NSDate distantPast] completionHandler:^() {
         done = true;
     }];
@@ -1616,35 +1618,21 @@ static size_t launchServiceWorkerProcess(bool useSeparateServiceWorkerProcess, b
     return webView.get().configuration.processPool._webProcessCountIgnoringPrewarmed;
 }
 
-TEST(ServiceWorkers, OutOfProcessServiceWorker)
+TEST(ServiceWorkers, OutOfAndInProcessServiceWorker)
 {
     bool useSeparateServiceWorkerProcess = true;
     bool firstLoadAboutBlank = true;
 
     EXPECT_EQ(1u, launchServiceWorkerProcess(!useSeparateServiceWorkerProcess, !firstLoadAboutBlank));
-}
-
-TEST(ServiceWorkers, InProcessServiceWorker)
-{
-    bool useSeparateServiceWorkerProcess = true;
-    bool firstLoadAboutBlank = true;
-
     EXPECT_EQ(2u, launchServiceWorkerProcess(useSeparateServiceWorkerProcess, !firstLoadAboutBlank));
 }
 
-TEST(ServiceWorkers, LoadAboutBlankBeforeNavigatingThroughOutOfProcessServiceWorker)
+TEST(ServiceWorkers, LoadAboutBlankBeforeNavigatingThroughServiceWorker)
 {
     bool useSeparateServiceWorkerProcess = true;
     bool firstLoadAboutBlank = true;
 
     EXPECT_EQ(1u, launchServiceWorkerProcess(!useSeparateServiceWorkerProcess, firstLoadAboutBlank));
-}
-
-TEST(ServiceWorkers, LoadAboutBlankBeforeNavigatingThroughInProcessServiceWorker)
-{
-    bool useSeparateServiceWorkerProcess = true;
-    bool firstLoadAboutBlank = true;
-
     EXPECT_EQ(2u, launchServiceWorkerProcess(useSeparateServiceWorkerProcess, firstLoadAboutBlank));
 }
 
@@ -1859,8 +1847,8 @@ TEST(ServiceWorkers, RestoreFromDiskNonDefaultStore)
     [[NSFileManager defaultManager] createDirectoryAtURL:swDBPath withIntermediateDirectories:YES attributes:nil error:nil];
     EXPECT_TRUE([[NSFileManager defaultManager] fileExistsAtPath:swDBPath.path]);
 
+    // We protect the process pool so that it outlives the WebsiteDataStore.
     RetainPtr<WKProcessPool> protectedProcessPool;
-    RetainPtr<WKWebsiteDataStore> protectedWebsiteDataStore;
 
     ServiceWorkerTCPServer server({
         { "text/html", mainRegisteringWorkerBytes },
@@ -1883,7 +1871,6 @@ TEST(ServiceWorkers, RestoreFromDiskNonDefaultStore)
 
         auto webView = adoptNS([[WKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration.get()]);
         protectedProcessPool = webView.get().configuration.processPool;
-        protectedWebsiteDataStore = webView.get().configuration.websiteDataStore;
 
         [webView loadRequest:server.request()];
 
@@ -1893,15 +1880,13 @@ TEST(ServiceWorkers, RestoreFromDiskNonDefaultStore)
         [webView.get().configuration.processPool _terminateServiceWorkers];
     }
 
-    // Make us more likely to lose any races with service worker initialization.
-    TestWebKitAPI::Util::spinRunLoop(10);
-    usleep(10000);
-    TestWebKitAPI::Util::spinRunLoop(10);
-
     @autoreleasepool {
         auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
 
-        configuration.get().websiteDataStore = protectedWebsiteDataStore.get();
+        auto websiteDataStoreConfiguration = adoptNS([[_WKWebsiteDataStoreConfiguration alloc] init]);
+        websiteDataStoreConfiguration.get()._serviceWorkerRegistrationDirectory = swDBPath;
+        auto nonDefaultDataStore = adoptNS([[WKWebsiteDataStore alloc] _initWithConfiguration:websiteDataStoreConfiguration.get()]);
+        configuration.get().websiteDataStore = nonDefaultDataStore.get();
 
         auto messageHandler = adoptNS([[SWMessageHandlerForRestoreFromDiskTest alloc] initWithExpectedMessage:@"PASS: Registration already has an active worker"]);
         [[configuration userContentController] addScriptMessageHandler:messageHandler.get() name:@"sw"];
@@ -1959,11 +1944,11 @@ TEST(ServiceWorkers, SuspendNetworkProcess)
 
     EXPECT_TRUE([[NSFileManager defaultManager] fileExistsAtPath:swDBPath.path]);
 
-    [webView.get().configuration.websiteDataStore _sendNetworkProcessWillSuspendImminently];
+    [ webView.get().configuration.processPool _sendNetworkProcessWillSuspendImminently];
 
     EXPECT_TRUE([[NSFileManager defaultManager] fileExistsAtPath:swDBPath.path]);
 
-    [webView.get().configuration.websiteDataStore _sendNetworkProcessDidResume];
+    [ webView.get().configuration.processPool _sendNetworkProcessDidResume];
 
     [webView loadRequest:server.request()];
     TestWebKitAPI::Util::run(&done);
index 3376092..a35f053 100644 (file)
@@ -479,6 +479,8 @@ static bool finished;
 }
 @end
 
+// FIXME: on iOS, UI process should be using the same cookie file as the network process for default session.
+#if PLATFORM(MAC)
 enum class ShouldEnableProcessPrewarming { No, Yes };
 void runWKHTTPCookieStoreWithoutProcessPool(ShouldEnableProcessPrewarming shouldEnableProcessPrewarming)
 {
@@ -587,66 +589,20 @@ TEST(WKHTTPCookieStore, WithoutProcessPoolWithPrewarming)
     runWKHTTPCookieStoreWithoutProcessPool(ShouldEnableProcessPrewarming::Yes);
 }
 
+#endif // PLATFORM(MAC)
+
 @interface CheckSessionCookieUIDelegate : NSObject <WKUIDelegate>
-- (NSString *)alertCookieHTML;
-- (NSString *)waitForMessage;
 @end
 
-@implementation CheckSessionCookieUIDelegate {
-    RetainPtr<NSString> _message;
-}
-
+@implementation CheckSessionCookieUIDelegate
 - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
 {
-    _message = message;
+    EXPECT_STREQ("SessionCookieName=CookieValue", message.UTF8String);
     finished = true;
     completionHandler();
 }
-
-- (NSString *)waitForMessage
-{
-    while (!_message)
-        TestWebKitAPI::Util::spinRunLoop();
-    return _message.autorelease();
-}
-
-- (NSString *)alertCookieHTML
-{
-    return @"<script>var cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i ++) { cookies[i] = cookies[i].trim(); } cookies.sort(); alert(cookies.join('; '));</script>";
-}
-
 @end
 
-TEST(WebKit, WKHTTPCookieStoreMultipleViews)
-{
-    TestWKWebView *webView1 = [[TestWKWebView new] autorelease];
-    [webView1 synchronouslyLoadHTMLString:@"start network process"];
-
-    NSHTTPCookie *sessionCookie = [NSHTTPCookie cookieWithProperties:@{
-        NSHTTPCookiePath: @"/",
-        NSHTTPCookieName: @"SessionCookieName",
-        NSHTTPCookieValue: @"CookieValue",
-        NSHTTPCookieDomain: @"127.0.0.1",
-    }];
-
-    __block bool setCookieDone = false;
-    [webView1.configuration.websiteDataStore.httpCookieStore setCookie:sessionCookie completionHandler:^{
-        setCookieDone = true;
-    }];
-    TestWebKitAPI::Util::run(&setCookieDone);
-
-    auto delegate = adoptNS([CheckSessionCookieUIDelegate new]);
-    [webView1 setUIDelegate:delegate.get()];
-
-    [webView1 loadHTMLString:[delegate alertCookieHTML] baseURL:[NSURL URLWithString:@"http://127.0.0.1"]];
-    EXPECT_WK_STREQ([delegate waitForMessage], "SessionCookieName=CookieValue");
-
-    TestWKWebView *webView2 = [[TestWKWebView new] autorelease];
-    [webView2 setUIDelegate:delegate.get()];
-    [webView2 loadHTMLString:[delegate alertCookieHTML] baseURL:[NSURL URLWithString:@"http://127.0.0.1"]];
-    EXPECT_WK_STREQ([delegate waitForMessage], "SessionCookieName=CookieValue");
-}
-
 TEST(WKHTTPCookieStore, WithoutProcessPoolEphemeralSession)
 {
     RetainPtr<WKWebsiteDataStore> ephemeralStoreWithCookies = [WKWebsiteDataStore nonPersistentDataStore];
@@ -671,8 +627,9 @@ TEST(WKHTTPCookieStore, WithoutProcessPoolEphemeralSession)
     TestWebKitAPI::Util::run(&finished);
     finished = false;
     
-    [webView loadHTMLString:[delegate alertCookieHTML] baseURL:[NSURL URLWithString:@"http://127.0.0.1"]];
-    EXPECT_WK_STREQ([delegate waitForMessage], "SessionCookieName=CookieValue");
+    NSString *alertCookieHTML = @"<script>var cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i ++) { cookies[i] = cookies[i].trim(); } cookies.sort(); alert(cookies.join('; '));</script>";
+    [webView loadHTMLString:alertCookieHTML baseURL:[NSURL URLWithString:@"http://127.0.0.1"]];
+    TestWebKitAPI::Util::run(&finished);
 }
 
 static bool areCookiesEqual(NSHTTPCookie *first, NSHTTPCookie *second)
index ac16535..ac7de41 100644 (file)
@@ -35,7 +35,6 @@
 #import <WebKit/WKURLSchemeTaskPrivate.h>
 #import <WebKit/WKWebViewConfigurationPrivate.h>
 #import <WebKit/WKWebViewPrivate.h>
-#import <WebKit/WKWebsiteDataStorePrivate.h>
 #import <WebKit/WebKit.h>
 #import <wtf/RetainPtr.h>
 #import <wtf/Vector.h>
@@ -153,7 +152,7 @@ TEST(URLSchemeHandler, Leaks3)
 
     runUntilTasksInFlight(2);
 
-    [webView1.get().configuration.websiteDataStore _terminateNetworkProcess];
+    [webView1.get().configuration.processPool _terminateNetworkProcess];
 
     runUntilTasksInFlight(0);
 }
index 3b131f7..92cf3a6 100644 (file)
@@ -244,7 +244,7 @@ static void runWebsiteDataStoreCustomPaths(ShouldEnableProcessPrewarming shouldE
     // Now, with brand new WKWebsiteDataStores pointing at the same custom cookie storage location,
     // in newly fired up NetworkProcesses, verify that the fetch and delete APIs work as expected.
 
-    [dataStore _terminateNetworkProcess];
+    [processPool _terminateNetworkProcess];
     auto newCustomDataStore = adoptNS([[WKWebsiteDataStore alloc] _initWithConfiguration:websiteDataStoreConfiguration.get()]);
 
     [newCustomDataStore fetchDataRecordsOfTypes:[NSSet setWithObjects:WKWebsiteDataTypeCookies, nil] completionHandler:^(NSArray<WKWebsiteDataRecord *> * records) {
@@ -255,7 +255,7 @@ static void runWebsiteDataStoreCustomPaths(ShouldEnableProcessPrewarming shouldE
     receivedScriptMessage = false;
     TestWebKitAPI::Util::run(&receivedScriptMessage);
 
-    [dataStore _terminateNetworkProcess];
+    [processPool _terminateNetworkProcess];
     newCustomDataStore = adoptNS([[WKWebsiteDataStore alloc] _initWithConfiguration:websiteDataStoreConfiguration.get()]);
 
     [newCustomDataStore removeDataOfTypes:[NSSet setWithObjects:WKWebsiteDataTypeCookies, nil] modifiedSince:[NSDate distantPast] completionHandler:^ {
@@ -385,10 +385,11 @@ TEST(WebKit, CustomDataStoreDestroyWhileFetchingNetworkProcessData)
 
         // Terminate the network process while a query is pending.
         auto* allProcessPools = [WKProcessPool _allProcessPoolsForTesting];
-        ASSERT_EQ(0U, [allProcessPools count]);
-        while (![dataStore _networkProcessIdentifier])
+        ASSERT_EQ(1U, [allProcessPools count]);
+        auto* processPool = allProcessPools[0];
+        while (![processPool _networkProcessIdentifier])
             TestWebKitAPI::Util::sleep(0.01);
-        kill([dataStore _networkProcessIdentifier], SIGKILL);
+        kill([processPool _networkProcessIdentifier], SIGKILL);
         allProcessPools = nil;
         dataStore = nil;
     }
@@ -464,9 +465,7 @@ TEST(WebKit, AlternativeServicesDefaultDirectoryCreation)
     
     [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:key];
 
-    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration new] autorelease];
-    configuration.websiteDataStore = [[[WKWebsiteDataStore alloc] _initWithConfiguration:[[[_WKWebsiteDataStoreConfiguration alloc] init] autorelease]] autorelease];
-    TestWKWebView *webView2 = [[[TestWKWebView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) configuration:configuration] autorelease];
+    TestWKWebView *webView2 = [[[TestWKWebView alloc] init] autorelease];
     [webView2 synchronouslyLoadHTMLString:@"start auxiliary processes" baseURL:nil];
 
     EXPECT_TRUE([[NSFileManager defaultManager] fileExistsAtPath:defaultDirectory.path]);
@@ -540,7 +539,7 @@ TEST(WebKit, DoLoadWithNonDefaultDataStoreAfterTerminatingNetworkProcess)
 
     TestWebKitAPI::Util::spinRunLoop(1);
 
-    [webViewConfiguration.get().websiteDataStore _terminateNetworkProcess];
+    [webViewConfiguration.get().processPool _terminateNetworkProcess];
 
     request = [NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"simple2" withExtension:@"html" subdirectory:@"TestWebKitAPI.resources"]];
     [webView loadRequest:request];
@@ -858,7 +857,7 @@ TEST(WebKit, MediaCache)
     EXPECT_FALSE(error);
 
     done = true;
-    [[webView configuration].websiteDataStore _terminateNetworkProcess];
+    [[webView configuration].processPool _terminateNetworkProcess];
 
     [fileManager removeItemAtPath:path error:&error];
     EXPECT_FALSE(error);
index 7b8478b..22e1a0a 100644 (file)
@@ -34,8 +34,6 @@
 #import "TestProtocol.h"
 #import <WebKit/WKContextPrivate.h>
 #import <WebKit/WKProcessGroupPrivate.h>
-#import <WebKit/WKViewPrivate.h>
-#import <WebKit/WKWebsiteDataStoreRef.h>
 #import <wtf/RetainPtr.h>
 
 static bool testFinished;
@@ -74,8 +72,6 @@ static WKProcessGroup *processGroup()
     return processGroup;
 }
 
-static RetainPtr<WKView> wkView;
-
 @interface CloseWhileStartingProtocol : TestProtocol
 @end
 
@@ -93,7 +89,7 @@ static RetainPtr<WKView> wkView;
         };
         WKContextSetClient([processGroup() _contextRef], &client.base);
 
-        kill(WKWebsiteDataStoreGetNetworkProcessIdentifier(WKPageGetWebsiteDataStore([wkView pageRef])), SIGKILL);
+        kill(WKContextGetNetworkProcessIdentifier([processGroup() _contextRef]), SIGKILL);
         [self.client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSCocoaErrorDomain code:0 userInfo:nil]];
     });
 }
@@ -146,7 +142,7 @@ namespace TestWebKitAPI {
 static void runTest()
 {
     RetainPtr<WKBrowsingContextGroup> browsingContextGroup = adoptNS([[WKBrowsingContextGroup alloc] initWithIdentifier:@"TestIdentifier"]);
-    wkView = adoptNS([[WKView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) processGroup:processGroup() browsingContextGroup:browsingContextGroup.get()]);
+    RetainPtr<WKView> wkView = adoptNS([[WKView alloc] initWithFrame:NSMakeRect(0, 0, 800, 600) processGroup:processGroup() browsingContextGroup:browsingContextGroup.get()]);
     RetainPtr<CustomProtocolsLoadDelegate> loadDelegate = adoptNS([[CustomProtocolsLoadDelegate alloc] init]);
     [wkView browsingContextController].loadDelegate = loadDelegate.get();
     [[wkView browsingContextController] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@://redirect?test", [TestProtocol scheme]]]]];
index ac5af87..1345c42 100644 (file)
@@ -1062,6 +1062,8 @@ bool TestController::resetStateToConsistentValues(const TestOptions& options, Re
 
     resetQuota();
 
+    WKContextSetAllowsAnySSLCertificateForServiceWorkerTesting(platformContext(), true);
+
     WKContextClearCurrentModifierStateForTesting(TestController::singleton().context());
 
     WKContextSetUseSeparateServiceWorkerProcess(TestController::singleton().context(), false);
@@ -1236,7 +1238,7 @@ void TestController::findAndDumpWebKitProcessIdentifiers()
     dumpResponse(makeString(TestController::webProcessName(), ": ",
         WKPageGetProcessIdentifier(TestController::singleton().mainWebView()->page()), '\n',
         TestController::networkProcessName(), ": ",
-        WKWebsiteDataStoreGetNetworkProcessIdentifier(websiteDataStore()), '\n'));
+        WKContextGetNetworkProcessIdentifier(m_context.get()), '\n'));
 #else
     dumpResponse("\n"_s);
 #endif
@@ -2296,7 +2298,7 @@ WKRetainPtr<WKTypeRef> TestController::getInjectedBundleInitializationUserData()
 
 void TestController::networkProcessDidCrash()
 {
-    pid_t pid = WKWebsiteDataStoreGetNetworkProcessIdentifier(websiteDataStore());
+    pid_t pid = WKContextGetNetworkProcessIdentifier(m_context.get());
     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", networkProcessName(), static_cast<long>(pid));
     exit(1);
 }
@@ -3135,7 +3137,7 @@ void TestController::setIgnoresViewportScaleLimits(bool ignoresViewportScaleLimi
 
 void TestController::terminateNetworkProcess()
 {
-    WKWebsiteDataStoreTerminateNetworkProcess(websiteDataStore());
+    WKContextTerminateNetworkProcess(platformContext());
 }
 
 void TestController::terminateServiceWorkers()
@@ -3166,8 +3168,9 @@ PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parent
     return new PlatformWebView(configuration, options);
 }
 
-WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef)
+WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
 {
+    WKContextSetPrimaryWebsiteDataStore(context, defaultWebsiteDataStore());
     return context;
 }