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