Move WKProcessPool._registerURLSchemeServiceWorkersCanHandle to _WKWebsiteDataStoreCo...
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessPool.h
1 /*
2  * Copyright (C) 2010-2019 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 "GenericCallback.h"
32 #include "HiddenPageThrottlingAutoIncreasesCounter.h"
33 #include "MessageReceiver.h"
34 #include "MessageReceiverMap.h"
35 #include "NetworkProcessProxy.h"
36 #include "PlugInAutoStartProvider.h"
37 #include "PluginInfoStore.h"
38 #include "ProcessThrottler.h"
39 #include "StatisticsRequest.h"
40 #include "VisitedLinkStore.h"
41 #include "WebContextClient.h"
42 #include "WebContextConnectionClient.h"
43 #include "WebPreferencesStore.h"
44 #include "WebProcessProxy.h"
45 #include "WebsiteDataStore.h"
46 #include <WebCore/CrossSiteNavigationDataTransfer.h>
47 #include <WebCore/ProcessIdentifier.h>
48 #include <WebCore/RegistrableDomain.h>
49 #include <WebCore/SecurityOriginHash.h>
50 #include <WebCore/SharedStringHash.h>
51 #include <pal/SessionID.h>
52 #include <wtf/Forward.h>
53 #include <wtf/HashMap.h>
54 #include <wtf/HashSet.h>
55 #include <wtf/MemoryPressureHandler.h>
56 #include <wtf/OptionSet.h>
57 #include <wtf/RefCounter.h>
58 #include <wtf/RefPtr.h>
59 #include <wtf/text/StringHash.h>
60 #include <wtf/text/WTFString.h>
61
62 #if ENABLE(MEDIA_SESSION)
63 #include "WebMediaSessionFocusManager.h"
64 #endif
65
66 #if USE(SOUP)
67 #include <WebCore/SoupNetworkProxySettings.h>
68 #endif
69
70 #if PLATFORM(COCOA)
71 OBJC_CLASS NSMutableDictionary;
72 OBJC_CLASS NSObject;
73 OBJC_CLASS NSSet;
74 OBJC_CLASS NSString;
75 #endif
76
77 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
78 #include "DisplayLink.h"
79 #endif
80
81 namespace API {
82 class AutomationClient;
83 class CustomProtocolManagerClient;
84 class DownloadClient;
85 class HTTPCookieStore;
86 class InjectedBundleClient;
87 class LegacyContextHistoryClient;
88 class Navigation;
89 class PageConfiguration;
90 }
91
92 namespace WebCore {
93 struct MockMediaDevice;
94 }
95
96 namespace WebKit {
97
98 class HighPerformanceGraphicsUsageSampler;
99 class UIGamepad;
100 class PerActivityStateCPUUsageSampler;
101 class SuspendedPageProxy;
102 class WebAutomationSession;
103 class WebContextSupplement;
104 class WebPageGroup;
105 class WebPageProxy;
106 class WebProcessCache;
107 struct NetworkProcessCreationParameters;
108 struct StatisticsData;
109 struct WebProcessCreationParameters;
110 struct WebProcessDataStoreParameters;
111     
112 typedef GenericCallback<API::Dictionary*> DictionaryCallback;
113
114 #if PLATFORM(COCOA)
115 int networkProcessLatencyQOS();
116 int networkProcessThroughputQOS();
117 int webProcessLatencyQOS();
118 int webProcessThroughputQOS();
119 #endif
120
121 enum class ProcessSwapRequestedByClient;
122
123 class WebProcessPool final : public API::ObjectImpl<API::Object::Type::ProcessPool>, public CanMakeWeakPtr<WebProcessPool>, private IPC::MessageReceiver {
124 public:
125     static Ref<WebProcessPool> create(API::ProcessPoolConfiguration&);
126
127     explicit WebProcessPool(API::ProcessPoolConfiguration&);        
128     virtual ~WebProcessPool();
129
130     void notifyThisWebProcessPoolWasCreated();
131
132     API::ProcessPoolConfiguration& configuration() { return m_configuration.get(); }
133
134     static const Vector<WebProcessPool*>& allProcessPools();
135
136     template <typename T>
137     T* supplement()
138     {
139         return static_cast<T*>(m_supplements.get(T::supplementName()));
140     }
141
142     template <typename T>
143     void addSupplement()
144     {
145         m_supplements.add(T::supplementName(), T::create(this));
146     }
147
148     void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&);
149     void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&);
150     void removeMessageReceiver(IPC::StringReference messageReceiverName);
151     void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID);
152     
153     template <typename T>
154     void addMessageReceiver(IPC::StringReference messageReceiverName, ObjectIdentifier<T> destinationID, IPC::MessageReceiver& receiver)
155     {
156         addMessageReceiver(messageReceiverName, destinationID.toUInt64(), receiver);
157     }
158     
159     template <typename T>
160     void removeMessageReceiver(IPC::StringReference messageReceiverName, ObjectIdentifier<T> destinationID)
161     {
162         removeMessageReceiver(messageReceiverName, destinationID.toUInt64());
163     }
164
165     bool dispatchMessage(IPC::Connection&, IPC::Decoder&);
166     bool dispatchSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
167
168     void initializeClient(const WKContextClientBase*);
169     void setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&&);
170     void initializeConnectionClient(const WKContextConnectionClientBase*);
171     void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&&);
172     void setDownloadClient(UniqueRef<API::DownloadClient>&&);
173     void setAutomationClient(std::unique_ptr<API::AutomationClient>&&);
174     void setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&&);
175
176     void setCustomWebContentServiceBundleIdentifier(const String&);
177     const String& customWebContentServiceBundleIdentifier() { return m_configuration->customWebContentServiceBundleIdentifier(); }
178
179     const Vector<RefPtr<WebProcessProxy>>& processes() const { return m_processes; }
180
181     // WebProcessProxy object which does not have a running process which is used for convenience, to avoid
182     // null checks in WebPageProxy.
183     WebProcessProxy* dummyProcessProxy() const { return m_dummyProcessProxy; }
184
185     // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null.
186     IPC::Connection* networkingProcessConnection();
187
188     template<typename T> void sendToAllProcesses(const T& message);
189     template<typename T> void sendToAllProcessesForSession(const T& message, PAL::SessionID);
190     template<typename T> void sendToAllProcessesRelaunchingThemIfNecessary(const T& message);
191     template<typename T> void sendToOneProcess(T&& message);
192
193     // Sends the message to WebProcess or NetworkProcess as approporiate for current process model.
194     template<typename T> void sendToNetworkingProcess(T&& message);
195     template<typename T, typename U> void sendSyncToNetworkingProcess(T&& message, U&& reply);
196     template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message);
197
198     void processDidFinishLaunching(WebProcessProxy*);
199
200     WebProcessCache& webProcessCache() { return m_webProcessCache.get(); }
201
202     // Disconnect the process from the context.
203     void disconnectProcess(WebProcessProxy*);
204
205     WebKit::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); }
206     void setPrimaryDataStore(WebKit::WebsiteDataStore& dataStore) { m_websiteDataStore = &dataStore; }
207
208     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
209
210     void pageBeginUsingWebsiteDataStore(WebPageProxyIdentifier, WebsiteDataStore&);
211     void pageEndUsingWebsiteDataStore(WebPageProxyIdentifier, WebsiteDataStore&);
212     bool hasPagesUsingWebsiteDataStore(WebsiteDataStore&) const;
213
214     const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); }
215 #if PLATFORM(COCOA)
216     NSSet *allowedClassesForParameterCoding() const;
217     void initializeClassesForParameterCoding();
218 #endif
219
220     DownloadProxy& download(WebsiteDataStore&, WebPageProxy* initiatingPage, const WebCore::ResourceRequest&, const String& suggestedFilename = { });
221     DownloadProxy& resumeDownload(WebsiteDataStore&, WebPageProxy* initiatingPage, const API::Data& resumeData, const String& path);
222
223     void setInjectedBundleInitializationUserData(RefPtr<API::Object>&& userData) { m_injectedBundleInitializationUserData = WTFMove(userData); }
224
225     void postMessageToInjectedBundle(const String&, API::Object*);
226
227     void populateVisitedLinks();
228
229 #if PLATFORM(IOS_FAMILY)
230     static void applicationIsAboutToSuspend();
231 #endif
232
233     void handleMemoryPressureWarning(Critical);
234
235 #if ENABLE(NETSCAPE_PLUGIN_API)
236     void setAdditionalPluginsDirectory(const String&);
237     void refreshPlugins();
238
239     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
240
241     void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString);
242     void resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&&);
243     void clearPluginClientPolicies();
244     const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>& pluginLoadClientPolicies() const { return m_pluginLoadClientPolicies; }
245 #endif
246
247 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
248     void startDisplayLink(IPC::Connection&, unsigned observerID, uint32_t displayID);
249     void stopDisplayLink(IPC::Connection&, unsigned observerID, uint32_t displayID);
250     void stopDisplayLinks(IPC::Connection&);
251 #endif
252
253     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
254     void clearSupportedPlugins();
255
256     ProcessID networkProcessIdentifier();
257     ProcessID prewarmedProcessIdentifier();
258     void activePagesOriginsInWebProcessForTesting(ProcessID, CompletionHandler<void(Vector<String>&&)>&&);
259     bool networkProcessHasEntitlementForTesting(const String&);
260
261     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
262
263     void setAlwaysUsesComplexTextCodePath(bool);
264     void setShouldUseFontSmoothing(bool);
265     
266     void registerURLSchemeAsEmptyDocument(const String&);
267     void registerURLSchemeAsSecure(const String&);
268     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
269     void setDomainRelaxationForbiddenForURLScheme(const String&);
270     void registerURLSchemeAsLocal(const String&);
271     void registerURLSchemeAsNoAccess(const String&);
272     void registerURLSchemeAsDisplayIsolated(const String&);
273     void registerURLSchemeAsCORSEnabled(const String&);
274     void registerURLSchemeAsCachePartitioned(const String&);
275     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&);
276
277     VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }
278
279     void setCacheModel(CacheModel);
280
281     void setDefaultRequestTimeoutInterval(double);
282
283     void startMemorySampler(const double interval);
284     void stopMemorySampler();
285
286 #if USE(SOUP)
287     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
288     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
289 #endif
290     void setEnhancedAccessibility(bool);
291     
292     // Downloads.
293     DownloadProxy& createDownloadProxy(WebsiteDataStore&, const WebCore::ResourceRequest&, WebPageProxy* originatingPage);
294     API::DownloadClient& downloadClient() { return m_downloadClient.get(); }
295
296     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
297     WebContextClient& client() { return m_client; }
298
299     API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
300
301     struct Statistics {
302         unsigned wkViewCount;
303         unsigned wkPageCount;
304         unsigned wkFrameCount;
305     };
306     static Statistics& statistics();    
307
308     void useTestingNetworkSession();
309     bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; }
310
311     void setAllowsAnySSLCertificateForWebSocket(bool);
312
313     void clearCachedCredentials();
314     void terminateNetworkProcess();
315     void sendNetworkProcessWillSuspendImminentlyForTesting();
316     void sendNetworkProcessDidResume();
317     void terminateServiceWorkerProcesses();
318
319     void syncNetworkProcessCookies();
320     void syncLocalStorage(CompletionHandler<void()>&& callback);
321     void clearLegacyPrivateBrowsingLocalStorage(CompletionHandler<void()>&& callback);
322
323     void setShouldMakeNextWebProcessLaunchFailForTesting(bool value) { m_shouldMakeNextWebProcessLaunchFailForTesting = value; }
324     bool shouldMakeNextWebProcessLaunchFailForTesting() const { return m_shouldMakeNextWebProcessLaunchFailForTesting; }
325     void setShouldMakeNextNetworkProcessLaunchFailForTesting(bool value) { m_shouldMakeNextNetworkProcessLaunchFailForTesting = value; }
326     bool shouldMakeNextNetworkProcessLaunchFailForTesting() const { return m_shouldMakeNextNetworkProcessLaunchFailForTesting; }
327
328     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
329
330     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
331
332     WebProcessProxy& processForRegistrableDomain(WebsiteDataStore&, WebPageProxy*, const WebCore::RegistrableDomain&); // Will return an existing one if limit is met or due to caching.
333
334     void prewarmProcess();
335
336     bool shouldTerminate(WebProcessProxy*);
337
338     void disableProcessTermination() { m_processTerminationEnabled = false; }
339     void enableProcessTermination();
340
341     void updateAutomationCapabilities() const;
342     void setAutomationSession(RefPtr<WebAutomationSession>&&);
343     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
344
345     // Defaults to false.
346     void setHTTPPipeliningEnabled(bool);
347     bool httpPipeliningEnabled() const;
348
349     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
350     
351     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
352     void setJavaScriptConfigurationFileEnabled(bool flag);
353 #if PLATFORM(IOS_FAMILY)
354     void setJavaScriptConfigurationFileEnabledFromDefaults();
355 #endif
356
357     void garbageCollectJavaScriptObjects();
358     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
359
360 #if PLATFORM(COCOA)
361     static bool omitPDFSupport();
362 #endif
363
364     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
365 #if OS(LINUX)
366     void sendMemoryPressureEvent(bool isCritical);
367 #endif
368     void textCheckerStateChanged();
369
370     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
371     void setPlugInAutoStartOriginHashes(API::Dictionary&);
372     void setPlugInAutoStartOrigins(API::Array&);
373     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
374
375     // Network Process Management
376     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
377     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
378     void networkProcessCrashed(NetworkProcessProxy&, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
379
380     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
381
382     bool isServiceWorkerPageID(WebPageProxyIdentifier) const;
383 #if ENABLE(SERVICE_WORKER)
384     void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::RegistrableDomain&&, PAL::SessionID);
385     size_t serviceWorkerProxiesCount() const { return m_serviceWorkerProcesses.size(); }
386     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
387     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
388     void updateServiceWorkerUserAgent(const String& userAgent);
389     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
390 #endif
391
392 #if PLATFORM(COCOA)
393     bool processSuppressionEnabled() const;
394 #endif
395
396     void windowServerConnectionStateChanged();
397
398 #if USE(SOUP)
399     void setIgnoreTLSErrors(bool);
400     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
401 #endif
402
403     static void setInvalidMessageCallback(void (*)(WKStringRef));
404     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
405
406     void processDidCachePage(WebProcessProxy*);
407
408     bool isURLKnownHSTSHost(const String& urlString) const;
409     void resetHSTSHosts();
410     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
411
412     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
413     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
414
415 #if PLATFORM(COCOA)
416     void updateProcessSuppressionState();
417
418     NSMutableDictionary *ensureBundleParameters();
419     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
420 #else
421     void updateProcessSuppressionState() const { }
422 #endif
423
424     void updateHiddenPageThrottlingAutoIncreaseLimit();
425
426     void setMemoryCacheDisabled(bool);
427     void setFontWhitelist(API::Array*);
428
429     UserObservablePageCounter::Token userObservablePageCount()
430     {
431         return m_userObservablePageCounter.count();
432     }
433
434     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
435     {
436         return m_processSuppressionDisabledForPageCounter.count();
437     }
438
439     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
440     {
441         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
442     }
443
444     void clearResourceLoadStatistics();
445
446     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
447     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
448
449     void synthesizeAppIsBackground(bool background);
450     
451 #if ENABLE(GAMEPAD)
452     void gamepadConnected(const UIGamepad&);
453     void gamepadDisconnected(const UIGamepad&);
454
455     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
456 #endif
457
458 #if PLATFORM(COCOA)
459     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
460     void setCookieStoragePartitioningEnabled(bool);
461
462     void clearPermanentCredentialsForProtectionSpace(WebCore::ProtectionSpace&&);
463 #endif
464     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
465     void setStorageAccessAPIEnabled(bool);
466
467     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
468     static void unregisterProcessPoolCreationListener(uint64_t identifier);
469
470 #if PLATFORM(IOS_FAMILY)
471     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
472     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
473 #endif
474
475     void processForNavigation(WebPageProxy&, const API::Navigation&, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient, Ref<WebsiteDataStore>&&, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&&);
476
477     // SuspendedPageProxy management.
478     void addSuspendedPage(std::unique_ptr<SuspendedPageProxy>&&);
479     void removeAllSuspendedPagesForPage(WebPageProxy&, WebProcessProxy* = nullptr);
480     std::unique_ptr<SuspendedPageProxy> takeSuspendedPage(SuspendedPageProxy&);
481     void removeSuspendedPage(SuspendedPageProxy&);
482     bool hasSuspendedPageFor(WebProcessProxy&, WebPageProxy&) const;
483     unsigned maxSuspendedPageCount() const { return m_maxSuspendedPageCount; }
484     RefPtr<WebProcessProxy> findReusableSuspendedPageProcess(const WebCore::RegistrableDomain&, WebPageProxy&, WebsiteDataStore&);
485
486     void clearSuspendedPages(AllowProcessCaching);
487
488     void didReachGoodTimeToPrewarm();
489
490     void didCollectPrewarmInformation(const WebCore::RegistrableDomain&, const WebCore::PrewarmInformation&);
491
492     void screenPropertiesStateChanged();
493
494     void addMockMediaDevice(const WebCore::MockMediaDevice&);
495     void clearMockMediaDevices();
496     void removeMockMediaDevice(const String& persistentId);
497     void resetMockMediaDevices();
498
499     void sendDisplayConfigurationChangedMessageForTesting();
500     void clearCurrentModifierStateForTesting();
501
502 #if ENABLE(RESOURCE_LOAD_STATISTICS)
503     void didCommitCrossSiteLoadWithDataTransfer(PAL::SessionID, const WebCore::RegistrableDomain& fromDomain, const WebCore::RegistrableDomain& toDomain, OptionSet<WebCore::CrossSiteNavigationDataTransfer::Flag>, WebPageProxyIdentifier, WebCore::PageIdentifier);
504 #endif
505
506 #if PLATFORM(GTK) || PLATFORM(WPE)
507     void setSandboxEnabled(bool enabled) { m_sandboxEnabled = enabled; };
508     void addSandboxPath(const CString& path, SandboxPermission permission) { m_extraSandboxPaths.add(path, permission); };
509     const HashMap<CString, SandboxPermission>& sandboxPaths() const { return m_extraSandboxPaths; };
510     bool sandboxEnabled() const { return m_sandboxEnabled; };
511 #endif
512     
513     void setWebProcessHasUploads(WebCore::ProcessIdentifier);
514     void clearWebProcessHasUploads(WebCore::ProcessIdentifier);
515
516     void setWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier);
517     void clearWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier);
518
519     void disableDelayedWebProcessLaunch() { m_isDelayedWebProcessLaunchDisabled = true; }
520
521     void setJavaScriptConfigurationDirectory(String&& directory) { m_javaScriptConfigurationDirectory = directory; }
522     const String& javaScriptConfigurationDirectory() const { return m_javaScriptConfigurationDirectory; }
523     
524     WebProcessDataStoreParameters webProcessDataStoreParameters(WebProcessProxy&, WebsiteDataStore&);
525     
526     PlugInAutoStartProvider& plugInAutoStartProvider() { return m_plugInAutoStartProvider; }
527
528 private:
529     void platformInitialize();
530
531     void platformInitializeWebProcess(const WebProcessProxy&, WebProcessCreationParameters&);
532     void platformInvalidateContext();
533
534     void processForNavigationInternal(WebPageProxy&, const API::Navigation&, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient, Ref<WebsiteDataStore>&&, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&&);
535
536     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
537
538     WebProcessProxy& createNewWebProcess(WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
539     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
540
541     void requestWebContentStatistics(StatisticsRequest&);
542     void requestNetworkingStatistics(StatisticsRequest&);
543
544     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
545
546     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
547     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&&);
548
549     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
550
551 #if ENABLE(GAMEPAD)
552     void startedUsingGamepads(IPC::Connection&);
553     void stoppedUsingGamepads(IPC::Connection&);
554
555     void processStoppedUsingGamepads(WebProcessProxy&);
556 #endif
557
558     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
559     void updateProcessAssertions();
560
561     // IPC::MessageReceiver.
562     // Implemented in generated WebProcessPoolMessageReceiver.cpp
563     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
564     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
565
566     static void languageChanged(void* context);
567     void languageChanged();
568
569     bool usesSingleWebProcess() const { return m_configuration->usesSingleWebProcess(); }
570
571 #if PLATFORM(IOS_FAMILY)
572     static String cookieStorageDirectory();
573     static String parentBundleDirectory();
574     static String networkingCachesDirectory();
575     static String webContentCachesDirectory();
576     static String containerTemporaryDirectory();
577 #endif
578
579 #if PLATFORM(COCOA)
580     void registerNotificationObservers();
581     void unregisterNotificationObservers();
582 #endif
583
584     void setApplicationIsActive(bool);
585
586     void resolvePathsForSandboxExtensions();
587     void platformResolvePathsForSandboxExtensions();
588
589     void addProcessToOriginCacheSet(WebProcessProxy&, const URL&);
590     void removeProcessFromOriginCacheSet(WebProcessProxy&);
591
592     void tryPrewarmWithDomainInformation(WebProcessProxy&, const WebCore::RegistrableDomain&);
593
594     void updateMaxSuspendedPageCount();
595
596 #if PLATFORM(IOS)
597     static float displayBrightness();
598     static void backlightLevelDidChangeCallback(CFNotificationCenterRef, void *observer, CFStringRef name, const void *, CFDictionaryRef userInfo);    
599 #endif
600
601     Ref<API::ProcessPoolConfiguration> m_configuration;
602
603     IPC::MessageReceiverMap m_messageReceiverMap;
604
605     Vector<RefPtr<WebProcessProxy>> m_processes;
606     WebProcessProxy* m_prewarmedProcess { nullptr };
607     WebProcessProxy* m_dummyProcessProxy { nullptr }; // A lightweight WebProcessProxy without backing process.
608
609     WebProcessProxy* m_processWithPageCache { nullptr };
610 #if ENABLE(SERVICE_WORKER)
611     using RegistrableDomainWithSessionID = std::pair<WebCore::RegistrableDomain, PAL::SessionID>;
612     HashMap<RegistrableDomainWithSessionID, WebProcessProxy*> m_serviceWorkerProcesses;
613     bool m_waitingForWorkerContextProcessConnection { false };
614     bool m_allowsAnySSLCertificateForServiceWorker { false };
615     String m_serviceWorkerUserAgent;
616     Optional<WebPreferencesStore> m_serviceWorkerPreferences;
617     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
618 #endif
619
620     Ref<WebPageGroup> m_defaultPageGroup;
621
622     RefPtr<API::Object> m_injectedBundleInitializationUserData;
623     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
624
625     WebContextClient m_client;
626     WebContextConnectionClient m_connectionClient;
627     std::unique_ptr<API::AutomationClient> m_automationClient;
628     UniqueRef<API::DownloadClient> m_downloadClient;
629     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
630     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
631
632     RefPtr<WebAutomationSession> m_automationSession;
633
634 #if ENABLE(NETSCAPE_PLUGIN_API)
635     PluginInfoStore m_pluginInfoStore;
636 #endif
637     Ref<VisitedLinkStore> m_visitedLinkStore;
638     bool m_visitedLinksPopulated { false };
639
640     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
641         
642     HashSet<String> m_schemesToRegisterAsEmptyDocument;
643     HashSet<String> m_schemesToRegisterAsSecure;
644     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
645     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
646     HashSet<String> m_schemesToRegisterAsLocal;
647     HashSet<String> m_schemesToRegisterAsNoAccess;
648     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
649     HashSet<String> m_schemesToRegisterAsCORSEnabled;
650     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
651     HashSet<String> m_schemesToRegisterAsCachePartitioned;
652     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
653
654     bool m_alwaysUsesComplexTextCodePath { false };
655     bool m_shouldUseFontSmoothing { true };
656
657     Vector<String> m_fontWhitelist;
658
659     // Messages that were posted before any pages were created.
660     // The client should use initialization messages instead, so that a restarted process would get the same state.
661     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
662
663     bool m_memorySamplerEnabled { false };
664     double m_memorySamplerInterval { 1400.0 };
665
666     RefPtr<WebKit::WebsiteDataStore> m_websiteDataStore;
667
668     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
669     WebContextSupplementMap m_supplements;
670
671 #if USE(SOUP)
672     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicy::OnlyFromMainDocumentDomain };
673     WebCore::SoupNetworkProxySettings m_networkProxySettings;
674 #endif
675
676 #if PLATFORM(MAC)
677     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
678     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
679     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
680     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
681     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
682     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
683 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
684     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
685 #endif
686     RetainPtr<NSObject> m_activationObserver;
687     RetainPtr<NSObject> m_deactivationObserver;
688
689     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
690     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
691 #endif
692
693 #if PLATFORM(IOS_FAMILY)
694     RetainPtr<NSObject> m_accessibilityEnabledObserver;
695 #endif
696
697     bool m_shouldUseTestingNetworkSession { false };
698
699     bool m_processTerminationEnabled { true };
700
701     bool m_didNetworkProcessCrash { false };
702     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
703
704     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
705     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
706
707 #if USE(SOUP)
708     bool m_ignoreTLSErrors { true };
709 #endif
710
711     bool m_memoryCacheDisabled { false };
712     bool m_javaScriptConfigurationFileEnabled { false };
713     String m_javaScriptConfigurationDirectory;
714     bool m_alwaysRunsAtBackgroundPriority;
715     bool m_shouldTakeUIBackgroundAssertion;
716     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
717     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
718
719     UserObservablePageCounter m_userObservablePageCounter;
720     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
721     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
722     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
723
724 #if PLATFORM(COCOA)
725     RetainPtr<NSMutableDictionary> m_bundleParameters;
726     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
727     mutable RetainPtr<NSSet> m_classesForParameterCoder;
728 #endif
729
730 #if ENABLE(CONTENT_EXTENSIONS)
731     HashMap<String, String> m_encodedContentExtensions;
732 #endif
733
734 #if ENABLE(NETSCAPE_PLUGIN_API)
735     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
736 #endif
737
738 #if ENABLE(GAMEPAD)
739     HashSet<WebProcessProxy*> m_processesUsingGamepads;
740 #endif
741
742 #if PLATFORM(COCOA)
743     bool m_cookieStoragePartitioningEnabled { false };
744 #endif
745     bool m_storageAccessAPIEnabled { false };
746
747     struct Paths {
748         String injectedBundlePath;
749         String uiProcessBundleResourcePath;
750
751 #if PLATFORM(IOS_FAMILY)
752         String cookieStorageDirectory;
753         String containerCachesDirectory;
754         String containerTemporaryDirectory;
755 #endif
756
757         Vector<String> additionalWebProcessSandboxExtensionPaths;
758     };
759     Paths m_resolvedPaths;
760
761     HashMap<PAL::SessionID, HashSet<WebPageProxyIdentifier>> m_sessionToPageIDsMap;
762     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
763
764 #if PLATFORM(IOS_FAMILY)
765     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
766     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
767     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
768     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
769 #if ENABLE(SERVICE_WORKER)
770     HashMap<WebCore::RegistrableDomain, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
771     HashMap<WebCore::RegistrableDomain, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
772 #endif
773 #endif
774
775     Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
776     unsigned m_maxSuspendedPageCount { 0 };
777
778     UniqueRef<WebProcessCache> m_webProcessCache;
779     HashMap<WebCore::RegistrableDomain, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
780
781     HashMap<WebCore::RegistrableDomain, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
782
783 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
784     Vector<std::unique_ptr<DisplayLink>> m_displayLinks;
785 #endif
786
787 #if PLATFORM(GTK) || PLATFORM(WPE)
788     bool m_sandboxEnabled { false };
789     HashMap<CString, SandboxPermission> m_extraSandboxPaths;
790 #endif
791
792     HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesWithUploads;
793     std::unique_ptr<ProcessAssertion> m_uiProcessUploadAssertion;
794
795     HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesPlayingAudibleMedia;
796     std::unique_ptr<ProcessAssertion> m_uiProcessMediaPlaybackAssertion;
797
798 #if PLATFORM(IOS)
799     // FIXME: Delayed process launch is currently disabled on iOS for performance reasons (rdar://problem/49074131).
800     bool m_isDelayedWebProcessLaunchDisabled { true };
801 #else
802     bool m_isDelayedWebProcessLaunchDisabled { false };
803 #endif
804 };
805
806 template<typename T>
807 void WebProcessPool::sendToNetworkingProcess(T&& message)
808 {
809     if (m_networkProcess && m_networkProcess->canSendMessage())
810         m_networkProcess->send(std::forward<T>(message), 0);
811 }
812
813 template<typename T>
814 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
815 {
816     ensureNetworkProcess();
817     m_networkProcess->send(std::forward<T>(message), 0);
818 }
819
820 template<typename T>
821 void WebProcessPool::sendToAllProcesses(const T& message)
822 {
823     size_t processCount = m_processes.size();
824     for (size_t i = 0; i < processCount; ++i) {
825         WebProcessProxy* process = m_processes[i].get();
826         if (process->canSendMessage())
827             process->send(T(message), 0);
828     }
829 }
830
831 template<typename T>
832 void WebProcessPool::sendToAllProcessesForSession(const T& message, PAL::SessionID sessionID)
833 {
834     size_t processCount = m_processes.size();
835     for (size_t i = 0; i < processCount; ++i) {
836         WebProcessProxy* process = m_processes[i].get();
837         if (process->canSendMessage() && !process->isPrewarmed() && process->sessionID() == sessionID)
838             process->send(T(message), 0);
839     }
840 }
841
842 template<typename T>
843 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
844 {
845     // 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.
846     sendToAllProcesses(message);
847 }
848
849 template<typename T>
850 void WebProcessPool::sendToOneProcess(T&& message)
851 {
852     bool messageSent = false;
853     size_t processCount = m_processes.size();
854     for (size_t i = 0; i < processCount; ++i) {
855         WebProcessProxy* process = m_processes[i].get();
856         if (process->canSendMessage()) {
857             process->send(std::forward<T>(message), 0);
858             messageSent = true;
859             break;
860         }
861     }
862
863     if (!messageSent) {
864         prewarmProcess();
865         RefPtr<WebProcessProxy> process = m_processes.last();
866         if (process->canSendMessage())
867             process->send(std::forward<T>(message), 0);
868     }
869 }
870
871 } // namespace WebKit