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