Keep around a pre-warmed process when doing process swap on navigation
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessPool.h
1 /*
2  * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #pragma once
27
28 #include "APIDictionary.h"
29 #include "APIObject.h"
30 #include "APIProcessPoolConfiguration.h"
31 #include "APIWebsiteDataStore.h"
32 #include "DownloadProxyMap.h"
33 #include "GenericCallback.h"
34 #include "HiddenPageThrottlingAutoIncreasesCounter.h"
35 #include "MessageReceiver.h"
36 #include "MessageReceiverMap.h"
37 #include "NetworkProcessProxy.h"
38 #include "PlugInAutoStartProvider.h"
39 #include "PluginInfoStore.h"
40 #include "ProcessThrottler.h"
41 #include "ServiceWorkerProcessProxy.h"
42 #include "StatisticsRequest.h"
43 #include "StorageProcessProxy.h"
44 #include "VisitedLinkStore.h"
45 #include "WebContextClient.h"
46 #include "WebContextConnectionClient.h"
47 #include "WebProcessProxy.h"
48 #include <WebCore/SecurityOriginHash.h>
49 #include <WebCore/SharedStringHash.h>
50 #include <pal/SessionID.h>
51 #include <wtf/Forward.h>
52 #include <wtf/HashMap.h>
53 #include <wtf/HashSet.h>
54 #include <wtf/ProcessID.h>
55 #include <wtf/RefCounter.h>
56 #include <wtf/RefPtr.h>
57 #include <wtf/text/StringHash.h>
58 #include <wtf/text/WTFString.h>
59
60 #if ENABLE(MEDIA_SESSION)
61 #include "WebMediaSessionFocusManager.h"
62 #endif
63
64 #if USE(SOUP)
65 #include <WebCore/SoupNetworkProxySettings.h>
66 #endif
67
68 #if PLATFORM(COCOA)
69 OBJC_CLASS NSMutableDictionary;
70 OBJC_CLASS NSObject;
71 OBJC_CLASS NSString;
72 #endif
73
74 namespace API {
75 class AutomationClient;
76 class CustomProtocolManagerClient;
77 class DownloadClient;
78 class HTTPCookieStore;
79 class InjectedBundleClient;
80 class LegacyContextHistoryClient;
81 class Navigation;
82 class PageConfiguration;
83 }
84
85 namespace WebKit {
86
87 class DownloadProxy;
88 class HighPerformanceGraphicsUsageSampler;
89 class UIGamepad;
90 class PerActivityStateCPUUsageSampler;
91 class ServiceWorkerProcessProxy;
92 class WebAutomationSession;
93 class WebContextSupplement;
94 class WebPageGroup;
95 class WebPageProxy;
96 struct NetworkProcessCreationParameters;
97 struct StatisticsData;
98 struct WebProcessCreationParameters;
99     
100 typedef GenericCallback<API::Dictionary*> DictionaryCallback;
101
102 #if PLATFORM(COCOA)
103 int networkProcessLatencyQOS();
104 int networkProcessThroughputQOS();
105 int webProcessLatencyQOS();
106 int webProcessThroughputQOS();
107 #endif
108
109 class WebProcessPool final : public API::ObjectImpl<API::Object::Type::ProcessPool>, private IPC::MessageReceiver {
110 public:
111     static Ref<WebProcessPool> create(API::ProcessPoolConfiguration&);
112
113     explicit WebProcessPool(API::ProcessPoolConfiguration&);        
114     virtual ~WebProcessPool();
115
116     void notifyThisWebProcessPoolWasCreated();
117
118     API::ProcessPoolConfiguration& configuration() { return m_configuration.get(); }
119
120     static const Vector<WebProcessPool*>& allProcessPools();
121
122     template <typename T>
123     T* supplement()
124     {
125         return static_cast<T*>(m_supplements.get(T::supplementName()));
126     }
127
128     template <typename T>
129     void addSupplement()
130     {
131         m_supplements.add(T::supplementName(), T::create(this));
132     }
133
134     void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&);
135     void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&);
136     void removeMessageReceiver(IPC::StringReference messageReceiverName);
137     void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID);
138
139     bool dispatchMessage(IPC::Connection&, IPC::Decoder&);
140     bool dispatchSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
141
142     void initializeClient(const WKContextClientBase*);
143     void setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&&);
144     void initializeConnectionClient(const WKContextConnectionClientBase*);
145     void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&&);
146     void setDownloadClient(std::unique_ptr<API::DownloadClient>&&);
147     void setAutomationClient(std::unique_ptr<API::AutomationClient>&&);
148     void setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&&);
149
150     void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running.
151     unsigned maximumNumberOfProcesses() const { return !m_configuration->maximumProcessCount() ? UINT_MAX : m_configuration->maximumProcessCount(); }
152
153     const Vector<RefPtr<WebProcessProxy>>& processes() const { return m_processes; }
154
155     // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null.
156     IPC::Connection* networkingProcessConnection();
157
158     template<typename T> void sendToAllProcesses(const T& message);
159     template<typename T> void sendToAllProcessesRelaunchingThemIfNecessary(const T& message);
160     template<typename T> void sendToOneProcess(T&& message);
161
162     // Sends the message to WebProcess or NetworkProcess as approporiate for current process model.
163     template<typename T> void sendToNetworkingProcess(T&& message);
164     template<typename T, typename U> void sendSyncToNetworkingProcess(T&& message, U&& reply);
165     template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message);
166
167     // Sends the message to WebProcess or StorageProcess as approporiate for current process model.
168     template<typename T> void sendToStorageProcessRelaunchingIfNecessary(T&& message);
169
170     void processDidFinishLaunching(WebProcessProxy*);
171
172     // Disconnect the process from the context.
173     void disconnectProcess(WebProcessProxy*);
174
175     API::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); }
176     void setPrimaryDataStore(API::WebsiteDataStore& dataStore) { m_websiteDataStore = &dataStore; }
177
178     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
179
180     void pageBeginUsingWebsiteDataStore(WebPageProxy&);
181     void pageEndUsingWebsiteDataStore(WebPageProxy&);
182
183     const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); }
184
185     DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&, const String& suggestedFilename = { });
186     DownloadProxy* resumeDownload(const API::Data* resumeData, const String& path);
187
188     void setInjectedBundleInitializationUserData(RefPtr<API::Object>&& userData) { m_injectedBundleInitializationUserData = WTFMove(userData); }
189
190     void postMessageToInjectedBundle(const String&, API::Object*);
191
192     void populateVisitedLinks();
193
194 #if ENABLE(NETSCAPE_PLUGIN_API)
195     void setAdditionalPluginsDirectory(const String&);
196     void refreshPlugins();
197
198     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
199
200     void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString);
201     void resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&&);
202     void clearPluginClientPolicies();
203     const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>& pluginLoadClientPolicies() const { return m_pluginLoadClientPolicies; }
204 #endif
205
206     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
207     void clearSupportedPlugins();
208
209     ProcessID networkProcessIdentifier();
210     ProcessID storageProcessIdentifier();
211
212     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
213
214     void setAlwaysUsesComplexTextCodePath(bool);
215     void setShouldUseFontSmoothing(bool);
216     
217     void registerURLSchemeAsEmptyDocument(const String&);
218     void registerURLSchemeAsSecure(const String&);
219     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
220     void setDomainRelaxationForbiddenForURLScheme(const String&);
221     void setCanHandleHTTPSServerTrustEvaluation(bool);
222     void registerURLSchemeAsLocal(const String&);
223     void registerURLSchemeAsNoAccess(const String&);
224     void registerURLSchemeAsDisplayIsolated(const String&);
225     void registerURLSchemeAsCORSEnabled(const String&);
226     void registerURLSchemeAsCachePartitioned(const String&);
227     void registerURLSchemeServiceWorkersCanHandle(const String&);
228     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&);
229
230     void preconnectToServer(const WebCore::URL&);
231
232     VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }
233
234     void setCacheModel(CacheModel);
235     CacheModel cacheModel() const { return m_configuration->cacheModel(); }
236
237     void setDefaultRequestTimeoutInterval(double);
238
239     void startMemorySampler(const double interval);
240     void stopMemorySampler();
241
242 #if USE(SOUP)
243     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
244     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
245 #endif
246     void setEnhancedAccessibility(bool);
247     
248     // Downloads.
249     DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&, WebPageProxy* originatingPage);
250     API::DownloadClient& downloadClient() { return *m_downloadClient; }
251
252     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
253     WebContextClient& client() { return m_client; }
254
255     API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
256
257     struct Statistics {
258         unsigned wkViewCount;
259         unsigned wkPageCount;
260         unsigned wkFrameCount;
261     };
262     static Statistics& statistics();    
263
264     void setCookieStorageDirectory(const String& dir) { m_overrideCookieStorageDirectory = dir; }
265
266     void useTestingNetworkSession();
267     bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; }
268
269     void setAllowsAnySSLCertificateForWebSocket(bool);
270
271     void clearCachedCredentials();
272     void terminateStorageProcess();
273     void terminateNetworkProcess();
274     void terminateServiceWorkerProcesses();
275     void disableServiceWorkerProcessTerminationDelay();
276
277     void syncNetworkProcessCookies();
278
279     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
280
281     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
282
283     WebProcessProxy& createNewWebProcessRespectingProcessCountLimit(WebsiteDataStore&); // Will return an existing one if limit is met.
284     void warmInitialProcess();
285
286     bool shouldTerminate(WebProcessProxy*);
287
288     void disableProcessTermination() { m_processTerminationEnabled = false; }
289     void enableProcessTermination();
290
291     void updateAutomationCapabilities() const;
292     void setAutomationSession(RefPtr<WebAutomationSession>&&);
293     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
294
295     // Defaults to false.
296     void setHTTPPipeliningEnabled(bool);
297     bool httpPipeliningEnabled() const;
298
299     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
300     
301     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
302     void setJavaScriptConfigurationFileEnabled(bool flag);
303 #if PLATFORM(IOS)
304     void setJavaScriptConfigurationFileEnabledFromDefaults();
305 #endif
306
307     void garbageCollectJavaScriptObjects();
308     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
309
310 #if PLATFORM(COCOA)
311     static bool omitPDFSupport();
312 #endif
313
314     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
315
316     void textCheckerStateChanged();
317
318     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
319     void setPlugInAutoStartOriginHashes(API::Dictionary&);
320     void setPlugInAutoStartOrigins(API::Array&);
321     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
322
323     // Network Process Management
324     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
325     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
326     void networkProcessCrashed(NetworkProcessProxy&, Vector<Ref<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
327     void networkProcessFailedToLaunch(NetworkProcessProxy&);
328
329     void getNetworkProcessConnection(Ref<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>&&);
330
331     void ensureStorageProcessAndWebsiteDataStore(WebsiteDataStore* relevantDataStore);
332     StorageProcessProxy* storageProcess() { return m_storageProcess.get(); }
333     void getStorageProcessConnection(WebProcessProxy&, PAL::SessionID initialSessionID, Ref<Messages::WebProcessProxy::GetStorageProcessConnection::DelayedReply>&&);
334     void storageProcessCrashed(StorageProcessProxy*);
335 #if ENABLE(SERVICE_WORKER)
336     void establishWorkerContextConnectionToStorageProcess(StorageProcessProxy&, WebCore::SecurityOriginData&&, std::optional<PAL::SessionID>);
337     ServiceWorkerProcessProxy* serviceWorkerProcessProxyFromPageID(uint64_t pageID) const;
338     const HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*>& serviceWorkerProxies() const { return m_serviceWorkerProcesses; }
339     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
340     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
341     void updateServiceWorkerUserAgent(const String& userAgent);
342     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
343 #endif
344
345 #if PLATFORM(COCOA)
346     bool processSuppressionEnabled() const;
347 #endif
348
349     void windowServerConnectionStateChanged();
350
351     static void willStartUsingPrivateBrowsing();
352     static void willStopUsingPrivateBrowsing();
353
354 #if USE(SOUP)
355     void setIgnoreTLSErrors(bool);
356     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
357 #endif
358
359     static void setInvalidMessageCallback(void (*)(WKStringRef));
360     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
361
362     void processDidCachePage(WebProcessProxy*);
363
364     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
365     void resetHSTSHosts();
366     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
367
368     void registerSchemeForCustomProtocol(const String&);
369     void unregisterSchemeForCustomProtocol(const String&);
370
371     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
372     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
373
374 #if PLATFORM(COCOA)
375     void updateProcessSuppressionState();
376
377     NSMutableDictionary *ensureBundleParameters();
378     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
379 #else
380     void updateProcessSuppressionState() const { }
381 #endif
382
383     void updateHiddenPageThrottlingAutoIncreaseLimit();
384
385     void setMemoryCacheDisabled(bool);
386     void setFontWhitelist(API::Array*);
387
388     UserObservablePageCounter::Token userObservablePageCount()
389     {
390         return m_userObservablePageCounter.count();
391     }
392
393     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
394     {
395         return m_processSuppressionDisabledForPageCounter.count();
396     }
397
398     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
399     {
400         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
401     }
402
403     // FIXME: Move these to API::WebsiteDataStore.
404     static String legacyPlatformDefaultLocalStorageDirectory();
405     static String legacyPlatformDefaultIndexedDBDatabaseDirectory();
406     static String legacyPlatformDefaultWebSQLDatabaseDirectory();
407     static String legacyPlatformDefaultMediaKeysStorageDirectory();
408     static String legacyPlatformDefaultMediaCacheDirectory();
409     static String legacyPlatformDefaultApplicationCacheDirectory();
410     static String legacyPlatformDefaultNetworkCacheDirectory();
411     static String legacyPlatformDefaultJavaScriptConfigurationDirectory();
412     static bool isNetworkCacheEnabled();
413
414     bool resourceLoadStatisticsEnabled() { return m_resourceLoadStatisticsEnabled; }
415     void setResourceLoadStatisticsEnabled(bool);
416     void clearResourceLoadStatistics();
417
418     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
419     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
420
421 #if ENABLE(GAMEPAD)
422     void gamepadConnected(const UIGamepad&);
423     void gamepadDisconnected(const UIGamepad&);
424
425     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
426 #endif
427
428 #if PLATFORM(COCOA)
429     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
430     void setCookieStoragePartitioningEnabled(bool);
431     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
432     void setStorageAccessAPIEnabled(bool);
433 #endif
434
435 #if ENABLE(SERVICE_WORKER)
436     void postMessageToServiceWorkerClient(const WebCore::ServiceWorkerClientIdentifier& destinationIdentifier, WebCore::MessageWithMessagePorts&&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
437     void postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&&, const WebCore::ServiceWorkerOrClientIdentifier& source, WebCore::SWServerConnectionIdentifier);
438 #endif
439
440     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
441     static void unregisterProcessPoolCreationListener(uint64_t identifier);
442
443 #if PLATFORM(IOS)
444     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
445     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
446 #endif
447
448     Ref<WebProcessProxy> processForNavigation(WebPageProxy&, const API::Navigation&, WebCore::PolicyAction&);
449     void registerSuspendedPageProxy(SuspendedPageProxy&);
450     void unregisterSuspendedPageProxy(SuspendedPageProxy&);
451     void didReachGoodTimeToPrewarm();
452
453 private:
454     void platformInitialize();
455
456     void platformInitializeWebProcess(WebProcessCreationParameters&);
457     void platformInvalidateContext();
458
459     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
460
461     WebProcessProxy& createNewWebProcess(WebsiteDataStore&, WebProcessProxy::IsInPrewarmedPool = WebProcessProxy::IsInPrewarmedPool::No);
462     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore&);
463
464     void requestWebContentStatistics(StatisticsRequest*);
465     void requestNetworkingStatistics(StatisticsRequest*);
466
467     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
468
469     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
470     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData);
471
472     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
473
474 #if ENABLE(GAMEPAD)
475     void startedUsingGamepads(IPC::Connection&);
476     void stoppedUsingGamepads(IPC::Connection&);
477
478     void processStoppedUsingGamepads(WebProcessProxy&);
479 #endif
480
481     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
482     void updateProcessAssertions();
483
484     // IPC::MessageReceiver.
485     // Implemented in generated WebProcessPoolMessageReceiver.cpp
486     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
487     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
488
489     static void languageChanged(void* context);
490     void languageChanged();
491
492 #if PLATFORM(IOS)
493     String cookieStorageDirectory() const;
494 #endif
495
496 #if PLATFORM(IOS)
497     String parentBundleDirectory() const;
498     String networkingCachesDirectory() const;
499     String webContentCachesDirectory() const;
500     String containerTemporaryDirectory() const;
501 #endif
502
503 #if PLATFORM(COCOA)
504     void registerNotificationObservers();
505     void unregisterNotificationObservers();
506 #endif
507
508     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
509     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
510
511     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
512
513     void resolvePathsForSandboxExtensions();
514     void platformResolvePathsForSandboxExtensions();
515
516     Ref<API::ProcessPoolConfiguration> m_configuration;
517
518     IPC::MessageReceiverMap m_messageReceiverMap;
519
520     Vector<RefPtr<WebProcessProxy>> m_processes;
521     unsigned m_prewarmedProcessCount { 0 };
522
523     WebProcessProxy* m_processWithPageCache { nullptr };
524 #if ENABLE(SERVICE_WORKER)
525     HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
526     bool m_waitingForWorkerContextProcessConnection { false };
527     bool m_allowsAnySSLCertificateForServiceWorker { false };
528     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
529     String m_serviceWorkerUserAgent;
530     std::optional<WebPreferencesStore> m_serviceWorkerPreferences;
531     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
532 #endif
533
534     Ref<WebPageGroup> m_defaultPageGroup;
535
536     RefPtr<API::Object> m_injectedBundleInitializationUserData;
537     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
538
539     WebContextClient m_client;
540     WebContextConnectionClient m_connectionClient;
541     std::unique_ptr<API::AutomationClient> m_automationClient;
542     std::unique_ptr<API::DownloadClient> m_downloadClient;
543     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
544     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
545
546     RefPtr<WebAutomationSession> m_automationSession;
547
548 #if ENABLE(NETSCAPE_PLUGIN_API)
549     PluginInfoStore m_pluginInfoStore;
550 #endif
551     Ref<VisitedLinkStore> m_visitedLinkStore;
552     bool m_visitedLinksPopulated { false };
553
554     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
555         
556     HashSet<String> m_schemesToRegisterAsEmptyDocument;
557     HashSet<String> m_schemesToRegisterAsSecure;
558     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
559     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
560     HashSet<String> m_schemesToRegisterAsLocal;
561     HashSet<String> m_schemesToRegisterAsNoAccess;
562     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
563     HashSet<String> m_schemesToRegisterAsCORSEnabled;
564     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
565     HashSet<String> m_schemesToRegisterAsCachePartitioned;
566     HashSet<String> m_schemesServiceWorkersCanHandle;
567     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
568
569     bool m_alwaysUsesComplexTextCodePath { false };
570     bool m_shouldUseFontSmoothing { true };
571
572     Vector<String> m_fontWhitelist;
573
574     // Messages that were posted before any pages were created.
575     // The client should use initialization messages instead, so that a restarted process would get the same state.
576     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
577
578     bool m_memorySamplerEnabled { false };
579     double m_memorySamplerInterval { 1400.0 };
580
581     RefPtr<API::WebsiteDataStore> m_websiteDataStore;
582
583     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
584     WebContextSupplementMap m_supplements;
585
586 #if USE(SOUP)
587     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
588     WebCore::SoupNetworkProxySettings m_networkProxySettings;
589 #endif
590     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
591
592 #if PLATFORM(MAC)
593     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
594     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
595     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
596     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
597     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
598 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
599     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
600 #endif
601
602     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
603     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
604 #endif
605
606     String m_overrideCookieStorageDirectory;
607
608     bool m_shouldUseTestingNetworkSession { false };
609
610     bool m_processTerminationEnabled { true };
611
612     bool m_canHandleHTTPSServerTrustEvaluation { true };
613     bool m_didNetworkProcessCrash { false };
614     RefPtr<NetworkProcessProxy> m_networkProcess;
615     RefPtr<StorageProcessProxy> m_storageProcess;
616
617     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
618     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
619
620 #if USE(SOUP)
621     bool m_ignoreTLSErrors { true };
622 #endif
623
624     bool m_memoryCacheDisabled { false };
625     bool m_resourceLoadStatisticsEnabled { false };
626     bool m_javaScriptConfigurationFileEnabled { false };
627     bool m_alwaysRunsAtBackgroundPriority;
628     bool m_shouldTakeUIBackgroundAssertion;
629
630     UserObservablePageCounter m_userObservablePageCounter;
631     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
632     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
633     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
634
635 #if PLATFORM(COCOA)
636     RetainPtr<NSMutableDictionary> m_bundleParameters;
637     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
638 #endif
639
640 #if ENABLE(CONTENT_EXTENSIONS)
641     HashMap<String, String> m_encodedContentExtensions;
642 #endif
643
644 #if ENABLE(NETSCAPE_PLUGIN_API)
645     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
646 #endif
647
648 #if ENABLE(GAMEPAD)
649     HashSet<WebProcessProxy*> m_processesUsingGamepads;
650 #endif
651
652 #if PLATFORM(COCOA)
653     bool m_cookieStoragePartitioningEnabled { false };
654     bool m_storageAccessAPIEnabled { false };
655 #endif
656
657     struct Paths {
658         String injectedBundlePath;
659         String applicationCacheDirectory;
660         String webSQLDatabaseDirectory;
661         String mediaCacheDirectory;
662         String mediaKeyStorageDirectory;
663         String uiProcessBundleResourcePath;
664         String indexedDatabaseDirectory;
665
666 #if PLATFORM(IOS)
667         String cookieStorageDirectory;
668         String containerCachesDirectory;
669         String containerTemporaryDirectory;
670 #endif
671
672         Vector<String> additionalWebProcessSandboxExtensionPaths;
673     };
674     Paths m_resolvedPaths;
675
676     HashMap<PAL::SessionID, HashSet<WebPageProxy*>> m_sessionToPagesMap;
677     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
678
679 #if PLATFORM(IOS)
680     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
681     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
682     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
683     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
684 #if ENABLE(SERVICE_WORKER)
685     HashMap<WebCore::SecurityOriginData, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
686     HashMap<WebCore::SecurityOriginData, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
687 #endif
688 #endif
689
690     HashMap<WebCore::SecurityOriginData, Vector<SuspendedPageProxy*>> m_suspendedPages;
691 };
692
693 template<typename T>
694 void WebProcessPool::sendToNetworkingProcess(T&& message)
695 {
696     if (m_networkProcess && m_networkProcess->canSendMessage())
697         m_networkProcess->send(std::forward<T>(message), 0);
698 }
699
700 template<typename T>
701 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
702 {
703     ensureNetworkProcess();
704     m_networkProcess->send(std::forward<T>(message), 0);
705 }
706
707 template<typename T>
708 void WebProcessPool::sendToStorageProcessRelaunchingIfNecessary(T&& message)
709 {
710     ensureStorageProcessAndWebsiteDataStore(nullptr);
711     m_storageProcess->send(std::forward<T>(message), 0);
712 }
713
714 template<typename T>
715 void WebProcessPool::sendToAllProcesses(const T& message)
716 {
717     size_t processCount = m_processes.size();
718     for (size_t i = 0; i < processCount; ++i) {
719         WebProcessProxy* process = m_processes[i].get();
720         if (process->canSendMessage())
721             process->send(T(message), 0);
722     }
723 }
724
725 template<typename T>
726 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
727 {
728     // FIXME (Multi-WebProcess): WebProcessPool doesn't track processes that have exited, so it cannot relaunch these. Perhaps this functionality won't be needed in this mode.
729     sendToAllProcesses(message);
730 }
731
732 template<typename T>
733 void WebProcessPool::sendToOneProcess(T&& message)
734 {
735     bool messageSent = false;
736     size_t processCount = m_processes.size();
737     for (size_t i = 0; i < processCount; ++i) {
738         WebProcessProxy* process = m_processes[i].get();
739         if (process->canSendMessage()) {
740             process->send(std::forward<T>(message), 0);
741             messageSent = true;
742             break;
743         }
744     }
745
746     if (!messageSent) {
747         warmInitialProcess();
748         RefPtr<WebProcessProxy> process = m_processes.last();
749         if (process->canSendMessage())
750             process->send(std::forward<T>(message), 0);
751     }
752 }
753
754 } // namespace WebKit