Switch from PLATFORM(IOS) to PLATFORM(IOS_FAMILY)
[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 "WebProcessProxy.h"
47 #include <WebCore/SecurityOriginHash.h>
48 #include <WebCore/SharedStringHash.h>
49 #include <pal/SessionID.h>
50 #include <wtf/Forward.h>
51 #include <wtf/HashMap.h>
52 #include <wtf/HashSet.h>
53 #include <wtf/MemoryPressureHandler.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 WebCore {
86 struct MockMediaDevice;
87 }
88
89 namespace WebKit {
90
91 class DownloadProxy;
92 class HighPerformanceGraphicsUsageSampler;
93 class UIGamepad;
94 class PerActivityStateCPUUsageSampler;
95 class ServiceWorkerProcessProxy;
96 class WebAutomationSession;
97 class WebContextSupplement;
98 class WebPageGroup;
99 class WebPageProxy;
100 struct NetworkProcessCreationParameters;
101 struct StatisticsData;
102 struct WebProcessCreationParameters;
103     
104 typedef GenericCallback<API::Dictionary*> DictionaryCallback;
105
106 #if PLATFORM(COCOA)
107 int networkProcessLatencyQOS();
108 int networkProcessThroughputQOS();
109 int webProcessLatencyQOS();
110 int webProcessThroughputQOS();
111 #endif
112
113 enum class ProcessSwapRequestedByClient;
114
115 class WebProcessPool final : public API::ObjectImpl<API::Object::Type::ProcessPool>, public CanMakeWeakPtr<WebProcessPool>, private IPC::MessageReceiver {
116 public:
117     static Ref<WebProcessPool> create(API::ProcessPoolConfiguration&);
118
119     explicit WebProcessPool(API::ProcessPoolConfiguration&);        
120     virtual ~WebProcessPool();
121
122     void notifyThisWebProcessPoolWasCreated();
123
124     API::ProcessPoolConfiguration& configuration() { return m_configuration.get(); }
125
126     static const Vector<WebProcessPool*>& allProcessPools();
127
128     template <typename T>
129     T* supplement()
130     {
131         return static_cast<T*>(m_supplements.get(T::supplementName()));
132     }
133
134     template <typename T>
135     void addSupplement()
136     {
137         m_supplements.add(T::supplementName(), T::create(this));
138     }
139
140     void addMessageReceiver(IPC::StringReference messageReceiverName, IPC::MessageReceiver&);
141     void addMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID, IPC::MessageReceiver&);
142     void removeMessageReceiver(IPC::StringReference messageReceiverName);
143     void removeMessageReceiver(IPC::StringReference messageReceiverName, uint64_t destinationID);
144
145     bool dispatchMessage(IPC::Connection&, IPC::Decoder&);
146     bool dispatchSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
147
148     void initializeClient(const WKContextClientBase*);
149     void setInjectedBundleClient(std::unique_ptr<API::InjectedBundleClient>&&);
150     void initializeConnectionClient(const WKContextConnectionClientBase*);
151     void setHistoryClient(std::unique_ptr<API::LegacyContextHistoryClient>&&);
152     void setDownloadClient(std::unique_ptr<API::DownloadClient>&&);
153     void setAutomationClient(std::unique_ptr<API::AutomationClient>&&);
154     void setLegacyCustomProtocolManagerClient(std::unique_ptr<API::CustomProtocolManagerClient>&&);
155
156     void setMaximumNumberOfProcesses(unsigned); // Can only be called when there are no processes running.
157     unsigned maximumNumberOfProcesses() const { return !m_configuration->maximumProcessCount() ? UINT_MAX : m_configuration->maximumProcessCount(); }
158
159     void setCustomWebContentServiceBundleIdentifier(const String&);
160     const String& customWebContentServiceBundleIdentifier() { return m_configuration->customWebContentServiceBundleIdentifier(); }
161
162     const Vector<RefPtr<WebProcessProxy>>& processes() const { return m_processes; }
163
164     // WebProcess or NetworkProcess as approporiate for current process model. The connection must be non-null.
165     IPC::Connection* networkingProcessConnection();
166
167     template<typename T> void sendToAllProcesses(const T& message);
168     template<typename T> void sendToAllProcessesRelaunchingThemIfNecessary(const T& message);
169     template<typename T> void sendToOneProcess(T&& message);
170
171     // Sends the message to WebProcess or NetworkProcess as approporiate for current process model.
172     template<typename T> void sendToNetworkingProcess(T&& message);
173     template<typename T, typename U> void sendSyncToNetworkingProcess(T&& message, U&& reply);
174     template<typename T> void sendToNetworkingProcessRelaunchingIfNecessary(T&& message);
175
176     void processDidFinishLaunching(WebProcessProxy*);
177
178     // Disconnect the process from the context.
179     void disconnectProcess(WebProcessProxy*);
180
181     API::WebsiteDataStore* websiteDataStore() const { return m_websiteDataStore.get(); }
182     void setPrimaryDataStore(API::WebsiteDataStore& dataStore) { m_websiteDataStore = &dataStore; }
183
184     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
185
186     void pageBeginUsingWebsiteDataStore(WebPageProxy&);
187     void pageEndUsingWebsiteDataStore(WebPageProxy&);
188
189     const String& injectedBundlePath() const { return m_configuration->injectedBundlePath(); }
190
191     DownloadProxy* download(WebPageProxy* initiatingPage, const WebCore::ResourceRequest&, const String& suggestedFilename = { });
192     DownloadProxy* resumeDownload(const API::Data* resumeData, const String& path);
193
194     void setInjectedBundleInitializationUserData(RefPtr<API::Object>&& userData) { m_injectedBundleInitializationUserData = WTFMove(userData); }
195
196     void postMessageToInjectedBundle(const String&, API::Object*);
197
198     void populateVisitedLinks();
199
200     void handleMemoryPressureWarning(Critical);
201
202 #if ENABLE(NETSCAPE_PLUGIN_API)
203     void setAdditionalPluginsDirectory(const String&);
204     void refreshPlugins();
205
206     PluginInfoStore& pluginInfoStore() { return m_pluginInfoStore; }
207
208     void setPluginLoadClientPolicy(WebCore::PluginLoadClientPolicy, const String& host, const String& bundleIdentifier, const String& versionString);
209     void resetPluginLoadClientPolicies(HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&&);
210     void clearPluginClientPolicies();
211     const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>& pluginLoadClientPolicies() const { return m_pluginLoadClientPolicies; }
212 #endif
213
214     void addSupportedPlugin(String&& matchingDomain, String&& name, HashSet<String>&& mimeTypes, HashSet<String> extensions);
215     void clearSupportedPlugins();
216
217     ProcessID networkProcessIdentifier();
218
219     WebPageGroup& defaultPageGroup() { return m_defaultPageGroup.get(); }
220
221     void setAlwaysUsesComplexTextCodePath(bool);
222     void setShouldUseFontSmoothing(bool);
223     
224     void registerURLSchemeAsEmptyDocument(const String&);
225     void registerURLSchemeAsSecure(const String&);
226     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&);
227     void setDomainRelaxationForbiddenForURLScheme(const String&);
228     void setCanHandleHTTPSServerTrustEvaluation(bool);
229     void registerURLSchemeAsLocal(const String&);
230     void registerURLSchemeAsNoAccess(const String&);
231     void registerURLSchemeAsDisplayIsolated(const String&);
232     void registerURLSchemeAsCORSEnabled(const String&);
233     void registerURLSchemeAsCachePartitioned(const String&);
234     void registerURLSchemeServiceWorkersCanHandle(const String&);
235     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&);
236
237     void preconnectToServer(const WebCore::URL&);
238
239     VisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }
240
241     void setCacheModel(CacheModel);
242     CacheModel cacheModel() const { return m_configuration->cacheModel(); }
243
244     void setDefaultRequestTimeoutInterval(double);
245
246     void startMemorySampler(const double interval);
247     void stopMemorySampler();
248
249 #if USE(SOUP)
250     void setInitialHTTPCookieAcceptPolicy(HTTPCookieAcceptPolicy policy) { m_initialHTTPCookieAcceptPolicy = policy; }
251     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
252 #endif
253     void setEnhancedAccessibility(bool);
254     
255     // Downloads.
256     DownloadProxy* createDownloadProxy(const WebCore::ResourceRequest&, WebPageProxy* originatingPage);
257     API::DownloadClient& downloadClient() { return *m_downloadClient; }
258
259     API::LegacyContextHistoryClient& historyClient() { return *m_historyClient; }
260     WebContextClient& client() { return m_client; }
261
262     API::CustomProtocolManagerClient& customProtocolManagerClient() const { return *m_customProtocolManagerClient; }
263
264     struct Statistics {
265         unsigned wkViewCount;
266         unsigned wkPageCount;
267         unsigned wkFrameCount;
268     };
269     static Statistics& statistics();    
270
271     void useTestingNetworkSession();
272     bool isUsingTestingNetworkSession() const { return m_shouldUseTestingNetworkSession; }
273
274     void setAllowsAnySSLCertificateForWebSocket(bool);
275
276     void clearCachedCredentials();
277     void terminateNetworkProcess();
278     void terminateServiceWorkerProcesses();
279     void disableServiceWorkerProcessTerminationDelay();
280
281     void syncNetworkProcessCookies();
282
283     void setShouldMakeNextWebProcessLaunchFailForTesting(bool value) { m_shouldMakeNextWebProcessLaunchFailForTesting = value; }
284     bool shouldMakeNextWebProcessLaunchFailForTesting() const { return m_shouldMakeNextWebProcessLaunchFailForTesting; }
285     void setShouldMakeNextNetworkProcessLaunchFailForTesting(bool value) { m_shouldMakeNextNetworkProcessLaunchFailForTesting = value; }
286     bool shouldMakeNextNetworkProcessLaunchFailForTesting() const { return m_shouldMakeNextNetworkProcessLaunchFailForTesting; }
287
288     void reportWebContentCPUTime(Seconds cpuTime, uint64_t activityState);
289
290     void allowSpecificHTTPSCertificateForHost(const WebCertificateInfo*, const String& host);
291
292     WebProcessProxy& createNewWebProcessRespectingProcessCountLimit(WebsiteDataStore&); // Will return an existing one if limit is met.
293     void prewarmProcess();
294
295     bool shouldTerminate(WebProcessProxy*);
296
297     void disableProcessTermination() { m_processTerminationEnabled = false; }
298     void enableProcessTermination();
299
300     void updateAutomationCapabilities() const;
301     void setAutomationSession(RefPtr<WebAutomationSession>&&);
302     WebAutomationSession* automationSession() const { return m_automationSession.get(); }
303
304     // Defaults to false.
305     void setHTTPPipeliningEnabled(bool);
306     bool httpPipeliningEnabled() const;
307
308     void getStatistics(uint32_t statisticsMask, Function<void (API::Dictionary*, CallbackBase::Error)>&&);
309     
310     bool javaScriptConfigurationFileEnabled() { return m_javaScriptConfigurationFileEnabled; }
311     void setJavaScriptConfigurationFileEnabled(bool flag);
312 #if PLATFORM(IOS_FAMILY)
313     void setJavaScriptConfigurationFileEnabledFromDefaults();
314 #endif
315
316     void garbageCollectJavaScriptObjects();
317     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
318
319 #if PLATFORM(COCOA)
320     static bool omitPDFSupport();
321 #endif
322
323     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
324 #if OS(LINUX)
325     void sendMemoryPressureEvent(bool isCritical);
326 #endif
327     void textCheckerStateChanged();
328
329     Ref<API::Dictionary> plugInAutoStartOriginHashes() const;
330     void setPlugInAutoStartOriginHashes(API::Dictionary&);
331     void setPlugInAutoStartOrigins(API::Array&);
332     void setPlugInAutoStartOriginsFilteringOutEntriesAddedAfterTime(API::Dictionary&, WallTime);
333
334     // Network Process Management
335     NetworkProcessProxy& ensureNetworkProcess(WebsiteDataStore* withWebsiteDataStore = nullptr);
336     NetworkProcessProxy* networkProcess() { return m_networkProcess.get(); }
337     void networkProcessCrashed(NetworkProcessProxy&, Vector<std::pair<RefPtr<WebProcessProxy>, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>>&&);
338
339     void getNetworkProcessConnection(WebProcessProxy&, Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
340
341 #if ENABLE(SERVICE_WORKER)
342     void establishWorkerContextConnectionToNetworkProcess(NetworkProcessProxy&, WebCore::SecurityOriginData&&, std::optional<PAL::SessionID>);
343     ServiceWorkerProcessProxy* serviceWorkerProcessProxyFromPageID(uint64_t pageID) const;
344     const HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*>& serviceWorkerProxies() const { return m_serviceWorkerProcesses; }
345     void setAllowsAnySSLCertificateForServiceWorker(bool allows) { m_allowsAnySSLCertificateForServiceWorker = allows; }
346     bool allowsAnySSLCertificateForServiceWorker() const { return m_allowsAnySSLCertificateForServiceWorker; }
347     void updateServiceWorkerUserAgent(const String& userAgent);
348     bool mayHaveRegisteredServiceWorkers(const WebsiteDataStore&);
349 #endif
350
351 #if PLATFORM(COCOA)
352     bool processSuppressionEnabled() const;
353 #endif
354
355     void windowServerConnectionStateChanged();
356
357     static void willStartUsingPrivateBrowsing();
358     static void willStopUsingPrivateBrowsing();
359
360 #if USE(SOUP)
361     void setIgnoreTLSErrors(bool);
362     bool ignoreTLSErrors() const { return m_ignoreTLSErrors; }
363 #endif
364
365     static void setInvalidMessageCallback(void (*)(WKStringRef));
366     static void didReceiveInvalidMessage(const IPC::StringReference& messageReceiverName, const IPC::StringReference& messageName);
367
368     void processDidCachePage(WebProcessProxy*);
369
370     bool isURLKnownHSTSHost(const String& urlString, bool privateBrowsingEnabled) const;
371     void resetHSTSHosts();
372     void resetHSTSHostsAddedAfterDate(double startDateIntervalSince1970);
373
374     void registerSchemeForCustomProtocol(const String&);
375     void unregisterSchemeForCustomProtocol(const String&);
376
377     static void registerGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
378     static void unregisterGlobalURLSchemeAsHavingCustomProtocolHandlers(const String&);
379
380 #if PLATFORM(COCOA)
381     void updateProcessSuppressionState();
382
383     NSMutableDictionary *ensureBundleParameters();
384     NSMutableDictionary *bundleParameters() { return m_bundleParameters.get(); }
385 #else
386     void updateProcessSuppressionState() const { }
387 #endif
388
389     void updateHiddenPageThrottlingAutoIncreaseLimit();
390
391     void setMemoryCacheDisabled(bool);
392     void setFontWhitelist(API::Array*);
393
394     UserObservablePageCounter::Token userObservablePageCount()
395     {
396         return m_userObservablePageCounter.count();
397     }
398
399     ProcessSuppressionDisabledToken processSuppressionDisabledForPageCount()
400     {
401         return m_processSuppressionDisabledForPageCounter.count();
402     }
403
404     HiddenPageThrottlingAutoIncreasesCounter::Token hiddenPageThrottlingAutoIncreasesCount()
405     {
406         return m_hiddenPageThrottlingAutoIncreasesCounter.count();
407     }
408
409     void setResourceLoadStatisticsEnabled(bool);
410     void clearResourceLoadStatistics();
411
412     bool alwaysRunsAtBackgroundPriority() const { return m_alwaysRunsAtBackgroundPriority; }
413     bool shouldTakeUIBackgroundAssertion() const { return m_shouldTakeUIBackgroundAssertion; }
414
415 #if ENABLE(GAMEPAD)
416     void gamepadConnected(const UIGamepad&);
417     void gamepadDisconnected(const UIGamepad&);
418
419     void setInitialConnectedGamepads(const Vector<std::unique_ptr<UIGamepad>>&);
420 #endif
421
422 #if PLATFORM(COCOA)
423     bool cookieStoragePartitioningEnabled() const { return m_cookieStoragePartitioningEnabled; }
424     void setCookieStoragePartitioningEnabled(bool);
425     bool storageAccessAPIEnabled() const { return m_storageAccessAPIEnabled; }
426     void setStorageAccessAPIEnabled(bool);
427 #endif
428
429 #if ENABLE(SERVICE_WORKER)
430     void postMessageToServiceWorkerClient(const WebCore::ServiceWorkerClientIdentifier& destinationIdentifier, WebCore::MessageWithMessagePorts&&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
431     void postMessageToServiceWorker(WebCore::ServiceWorkerIdentifier destination, WebCore::MessageWithMessagePorts&&, const WebCore::ServiceWorkerOrClientIdentifier& source, WebCore::SWServerConnectionIdentifier);
432 #endif
433
434     static uint64_t registerProcessPoolCreationListener(Function<void(WebProcessPool&)>&&);
435     static void unregisterProcessPoolCreationListener(uint64_t identifier);
436
437 #if PLATFORM(IOS_FAMILY)
438     ForegroundWebProcessToken foregroundWebProcessToken() const { return ForegroundWebProcessToken(m_foregroundWebProcessCounter.count()); }
439     BackgroundWebProcessToken backgroundWebProcessToken() const { return BackgroundWebProcessToken(m_backgroundWebProcessCounter.count()); }
440 #endif
441
442     Ref<WebProcessProxy> processForNavigation(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, WebCore::PolicyAction&, String& reason);
443
444     // SuspendedPageProxy management.
445     void addSuspendedPageProxy(std::unique_ptr<SuspendedPageProxy>&&);
446     void removeAllSuspendedPageProxiesForPage(WebPageProxy&);
447     std::unique_ptr<SuspendedPageProxy> takeSuspendedPageProxy(SuspendedPageProxy&);
448     bool hasSuspendedPageProxyFor(WebProcessProxy&);
449
450     void didReachGoodTimeToPrewarm();
451
452     void didCollectPrewarmInformation(const String& registrableDomain, const WebCore::PrewarmInformation&);
453
454     void screenPropertiesStateChanged();
455
456     void addMockMediaDevice(const WebCore::MockMediaDevice&);
457     void clearMockMediaDevices();
458     void removeMockMediaDevice(const String& persistentId);
459     void resetMockMediaDevices();
460
461     void sendDisplayConfigurationChangedMessageForTesting();
462
463 #if PLATFORM(GTK) || PLATFORM(WPE)
464     void setSandboxEnabled(bool enabled) { m_sandboxEnabled = enabled; };
465     bool sandboxEnabled() const { return m_sandboxEnabled; };
466 #endif
467
468 private:
469     void platformInitialize();
470
471     void platformInitializeWebProcess(WebProcessCreationParameters&);
472     void platformInvalidateContext();
473
474     Ref<WebProcessProxy> processForNavigationInternal(WebPageProxy&, const API::Navigation&, ProcessSwapRequestedByClient, WebCore::PolicyAction&, String& reason);
475
476     RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
477
478     WebProcessProxy& createNewWebProcess(WebsiteDataStore&, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
479     void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore&);
480
481     void requestWebContentStatistics(StatisticsRequest*);
482     void requestNetworkingStatistics(StatisticsRequest*);
483
484     void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
485
486     void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
487     void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, UserData& returnUserData);
488
489     void didGetStatistics(const StatisticsData&, uint64_t callbackID);
490
491 #if ENABLE(GAMEPAD)
492     void startedUsingGamepads(IPC::Connection&);
493     void stoppedUsingGamepads(IPC::Connection&);
494
495     void processStoppedUsingGamepads(WebProcessProxy&);
496 #endif
497
498     void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
499     void updateProcessAssertions();
500
501     // IPC::MessageReceiver.
502     // Implemented in generated WebProcessPoolMessageReceiver.cpp
503     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
504     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
505
506     static void languageChanged(void* context);
507     void languageChanged();
508
509 #if PLATFORM(IOS_FAMILY)
510     String cookieStorageDirectory() const;
511 #endif
512
513 #if PLATFORM(IOS_FAMILY)
514     String parentBundleDirectory() const;
515     String networkingCachesDirectory() const;
516     String webContentCachesDirectory() const;
517     String containerTemporaryDirectory() const;
518 #endif
519
520 #if PLATFORM(COCOA)
521     void registerNotificationObservers();
522     void unregisterNotificationObservers();
523 #endif
524
525     void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
526     void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
527
528     void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
529
530     void resolvePathsForSandboxExtensions();
531     void platformResolvePathsForSandboxExtensions();
532
533     void addProcessToOriginCacheSet(WebPageProxy&);
534     void removeProcessFromOriginCacheSet(WebProcessProxy&);
535
536     void tryPrewarmWithDomainInformation(WebProcessProxy&, const WebCore::URL&);
537
538     Ref<API::ProcessPoolConfiguration> m_configuration;
539
540     IPC::MessageReceiverMap m_messageReceiverMap;
541
542     Vector<RefPtr<WebProcessProxy>> m_processes;
543     WebProcessProxy* m_prewarmedProcess { nullptr };
544
545     WebProcessProxy* m_processWithPageCache { nullptr };
546 #if ENABLE(SERVICE_WORKER)
547     HashMap<WebCore::SecurityOriginData, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
548     bool m_waitingForWorkerContextProcessConnection { false };
549     bool m_allowsAnySSLCertificateForServiceWorker { false };
550     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
551     String m_serviceWorkerUserAgent;
552     std::optional<WebPreferencesStore> m_serviceWorkerPreferences;
553     HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
554 #endif
555
556     Ref<WebPageGroup> m_defaultPageGroup;
557
558     RefPtr<API::Object> m_injectedBundleInitializationUserData;
559     std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
560
561     WebContextClient m_client;
562     WebContextConnectionClient m_connectionClient;
563     std::unique_ptr<API::AutomationClient> m_automationClient;
564     std::unique_ptr<API::DownloadClient> m_downloadClient;
565     std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
566     std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
567
568     RefPtr<WebAutomationSession> m_automationSession;
569
570 #if ENABLE(NETSCAPE_PLUGIN_API)
571     PluginInfoStore m_pluginInfoStore;
572 #endif
573     Ref<VisitedLinkStore> m_visitedLinkStore;
574     bool m_visitedLinksPopulated { false };
575
576     PlugInAutoStartProvider m_plugInAutoStartProvider { this };
577         
578     HashSet<String> m_schemesToRegisterAsEmptyDocument;
579     HashSet<String> m_schemesToRegisterAsSecure;
580     HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
581     HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
582     HashSet<String> m_schemesToRegisterAsLocal;
583     HashSet<String> m_schemesToRegisterAsNoAccess;
584     HashSet<String> m_schemesToRegisterAsDisplayIsolated;
585     HashSet<String> m_schemesToRegisterAsCORSEnabled;
586     HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
587     HashSet<String> m_schemesToRegisterAsCachePartitioned;
588     HashSet<String> m_schemesServiceWorkersCanHandle;
589     HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
590
591     bool m_alwaysUsesComplexTextCodePath { false };
592     bool m_shouldUseFontSmoothing { true };
593
594     Vector<String> m_fontWhitelist;
595
596     // Messages that were posted before any pages were created.
597     // The client should use initialization messages instead, so that a restarted process would get the same state.
598     Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
599
600     bool m_memorySamplerEnabled { false };
601     double m_memorySamplerInterval { 1400.0 };
602
603     RefPtr<API::WebsiteDataStore> m_websiteDataStore;
604
605     typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
606     WebContextSupplementMap m_supplements;
607
608 #if USE(SOUP)
609     HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
610     WebCore::SoupNetworkProxySettings m_networkProxySettings;
611 #endif
612     HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
613
614 #if PLATFORM(MAC)
615     RetainPtr<NSObject> m_enhancedAccessibilityObserver;
616     RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
617     RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
618     RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
619     RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
620     RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
621 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
622     RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
623 #endif
624
625     std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
626     std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
627 #endif
628
629     bool m_shouldUseTestingNetworkSession { false };
630
631     bool m_processTerminationEnabled { true };
632
633     bool m_canHandleHTTPSServerTrustEvaluation { true };
634     bool m_didNetworkProcessCrash { false };
635     std::unique_ptr<NetworkProcessProxy> m_networkProcess;
636
637     HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
638     HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
639
640 #if USE(SOUP)
641     bool m_ignoreTLSErrors { true };
642 #endif
643
644     bool m_memoryCacheDisabled { false };
645     bool m_javaScriptConfigurationFileEnabled { false };
646     bool m_alwaysRunsAtBackgroundPriority;
647     bool m_shouldTakeUIBackgroundAssertion;
648     bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
649     bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
650
651     UserObservablePageCounter m_userObservablePageCounter;
652     ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
653     HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
654     RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
655
656 #if PLATFORM(COCOA)
657     RetainPtr<NSMutableDictionary> m_bundleParameters;
658     ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
659 #endif
660
661 #if ENABLE(CONTENT_EXTENSIONS)
662     HashMap<String, String> m_encodedContentExtensions;
663 #endif
664
665 #if ENABLE(NETSCAPE_PLUGIN_API)
666     HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
667 #endif
668
669 #if ENABLE(GAMEPAD)
670     HashSet<WebProcessProxy*> m_processesUsingGamepads;
671 #endif
672
673 #if PLATFORM(COCOA)
674     bool m_cookieStoragePartitioningEnabled { false };
675     bool m_storageAccessAPIEnabled { false };
676 #endif
677
678     struct Paths {
679         String injectedBundlePath;
680         String applicationCacheDirectory;
681         String webSQLDatabaseDirectory;
682         String mediaCacheDirectory;
683         String mediaKeyStorageDirectory;
684         String uiProcessBundleResourcePath;
685         String indexedDatabaseDirectory;
686
687 #if PLATFORM(IOS_FAMILY)
688         String cookieStorageDirectory;
689         String containerCachesDirectory;
690         String containerTemporaryDirectory;
691 #endif
692
693         Vector<String> additionalWebProcessSandboxExtensionPaths;
694     };
695     Paths m_resolvedPaths;
696
697     HashMap<PAL::SessionID, HashSet<WebPageProxy*>> m_sessionToPagesMap;
698     RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
699
700 #if PLATFORM(IOS_FAMILY)
701     ForegroundWebProcessCounter m_foregroundWebProcessCounter;
702     BackgroundWebProcessCounter m_backgroundWebProcessCounter;
703     ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
704     ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
705 #if ENABLE(SERVICE_WORKER)
706     HashMap<WebCore::SecurityOriginData, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
707     HashMap<WebCore::SecurityOriginData, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
708 #endif
709 #endif
710
711     Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
712     HashMap<String, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
713
714     HashMap<String, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
715
716 #if PLATFORM(GTK) || PLATFORM(WPE)
717     bool m_sandboxEnabled { false };
718 #endif
719 };
720
721 template<typename T>
722 void WebProcessPool::sendToNetworkingProcess(T&& message)
723 {
724     if (m_networkProcess && m_networkProcess->canSendMessage())
725         m_networkProcess->send(std::forward<T>(message), 0);
726 }
727
728 template<typename T>
729 void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
730 {
731     ensureNetworkProcess();
732     m_networkProcess->send(std::forward<T>(message), 0);
733 }
734
735 template<typename T>
736 void WebProcessPool::sendToAllProcesses(const T& message)
737 {
738     size_t processCount = m_processes.size();
739     for (size_t i = 0; i < processCount; ++i) {
740         WebProcessProxy* process = m_processes[i].get();
741         if (process->canSendMessage())
742             process->send(T(message), 0);
743     }
744 }
745
746 template<typename T>
747 void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
748 {
749     // 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.
750     sendToAllProcesses(message);
751 }
752
753 template<typename T>
754 void WebProcessPool::sendToOneProcess(T&& message)
755 {
756     bool messageSent = false;
757     size_t processCount = m_processes.size();
758     for (size_t i = 0; i < processCount; ++i) {
759         WebProcessProxy* process = m_processes[i].get();
760         if (process->canSendMessage()) {
761             process->send(std::forward<T>(message), 0);
762             messageSent = true;
763             break;
764         }
765     }
766
767     if (!messageSent) {
768         prewarmProcess();
769         RefPtr<WebProcessProxy> process = m_processes.last();
770         if (process->canSendMessage())
771             process->send(std::forward<T>(message), 0);
772     }
773 }
774
775 } // namespace WebKit