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