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