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