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)
70OBJC_CLASS NSMutableDictionary;
71OBJC_CLASS NSObject;
72OBJC_CLASS NSString;
73#endif
74
75#if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
76#include "DisplayLink.h"
77#endif
78
79namespace API {
80class AutomationClient;
81class CustomProtocolManagerClient;
82class DownloadClient;
83class HTTPCookieStore;
84class InjectedBundleClient;
85class LegacyContextHistoryClient;
86class Navigation;
87class PageConfiguration;
88}
89
90namespace WebCore {
91struct MockMediaDevice;
92}
93
94namespace WebKit {
95
96class DownloadProxy;
97class HighPerformanceGraphicsUsageSampler;
98class UIGamepad;
99class PerActivityStateCPUUsageSampler;
100class ServiceWorkerProcessProxy;
101class WebAutomationSession;
102class WebContextSupplement;
103class WebPageGroup;
104class WebPageProxy;
105class WebProcessCache;
106struct NetworkProcessCreationParameters;
107struct StatisticsData;
108struct WebProcessCreationParameters;
109struct WebProcessDataStoreParameters;
110
111typedef GenericCallback<API::Dictionary*> DictionaryCallback;
112
113#if PLATFORM(COCOA)
114int networkProcessLatencyQOS();
115int networkProcessThroughputQOS();
116int webProcessLatencyQOS();
117int webProcessThroughputQOS();
118#endif
119
120enum class ProcessSwapRequestedByClient;
121
122class WebProcessPool final : public API::ObjectImpl<API::Object::Type::ProcessPool>, public CanMakeWeakPtr<WebProcessPool>, private IPC::MessageReceiver {
123public:
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 setWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier);
509 void clearWebProcessIsPlayingAudibleMedia(WebCore::ProcessIdentifier);
510
511 void disableDelayedWebProcessLaunch() { m_isDelayedWebProcessLaunchDisabled = true; }
512
513private:
514 void platformInitialize();
515
516 void platformInitializeWebProcess(WebProcessCreationParameters&);
517 void platformInvalidateContext();
518
519 void processForNavigationInternal(WebPageProxy&, const API::Navigation&, Ref<WebProcessProxy>&& sourceProcess, const URL& sourceURL, ProcessSwapRequestedByClient, Ref<WebsiteDataStore>&&, CompletionHandler<void(Ref<WebProcessProxy>&&, SuspendedPageProxy*, const String&)>&&);
520
521 RefPtr<WebProcessProxy> tryTakePrewarmedProcess(WebsiteDataStore&);
522
523 WebProcessProxy& createNewWebProcess(WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
524 void initializeNewWebProcess(WebProcessProxy&, WebsiteDataStore*, WebProcessProxy::IsPrewarmed = WebProcessProxy::IsPrewarmed::No);
525 void sendWebProcessDataStoreParameters(WebProcessProxy&, WebsiteDataStore&);
526
527 void requestWebContentStatistics(StatisticsRequest&);
528 void requestNetworkingStatistics(StatisticsRequest&);
529
530 void platformInitializeNetworkProcess(NetworkProcessCreationParameters&);
531
532 void handleMessage(IPC::Connection&, const String& messageName, const UserData& messageBody);
533 void handleSynchronousMessage(IPC::Connection&, const String& messageName, const UserData& messageBody, CompletionHandler<void(UserData&&)>&&);
534
535 void didGetStatistics(const StatisticsData&, uint64_t callbackID);
536
537#if ENABLE(GAMEPAD)
538 void startedUsingGamepads(IPC::Connection&);
539 void stoppedUsingGamepads(IPC::Connection&);
540
541 void processStoppedUsingGamepads(WebProcessProxy&);
542#endif
543
544 void reinstateNetworkProcessAssertionState(NetworkProcessProxy&);
545 void updateProcessAssertions();
546
547 // IPC::MessageReceiver.
548 // Implemented in generated WebProcessPoolMessageReceiver.cpp
549 void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
550 void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
551
552 static void languageChanged(void* context);
553 void languageChanged();
554
555 bool usesSingleWebProcess() const { return m_configuration->usesSingleWebProcess(); }
556
557#if PLATFORM(IOS_FAMILY)
558 String cookieStorageDirectory() const;
559#endif
560
561#if PLATFORM(IOS_FAMILY)
562 String parentBundleDirectory() const;
563 String networkingCachesDirectory() const;
564 String webContentCachesDirectory() const;
565 String containerTemporaryDirectory() const;
566#endif
567
568#if PLATFORM(COCOA)
569 void registerNotificationObservers();
570 void unregisterNotificationObservers();
571#endif
572
573 void setApplicationIsActive(bool);
574
575 void addPlugInAutoStartOriginHash(const String& pageOrigin, unsigned plugInOriginHash, PAL::SessionID);
576 void plugInDidReceiveUserInteraction(unsigned plugInOriginHash, PAL::SessionID);
577
578 void setAnyPageGroupMightHavePrivateBrowsingEnabled(bool);
579
580 void resolvePathsForSandboxExtensions();
581 void platformResolvePathsForSandboxExtensions();
582
583 void addProcessToOriginCacheSet(WebProcessProxy&, const URL&);
584 void removeProcessFromOriginCacheSet(WebProcessProxy&);
585
586 void tryPrewarmWithDomainInformation(WebProcessProxy&, const WebCore::RegistrableDomain&);
587
588 void updateMaxSuspendedPageCount();
589
590#if PLATFORM(IOS)
591 static float displayBrightness();
592 static void backlightLevelDidChangeCallback(CFNotificationCenterRef, void *observer, CFStringRef name, const void *, CFDictionaryRef userInfo);
593#endif
594
595 Ref<API::ProcessPoolConfiguration> m_configuration;
596
597 IPC::MessageReceiverMap m_messageReceiverMap;
598
599 Vector<RefPtr<WebProcessProxy>> m_processes;
600 WebProcessProxy* m_prewarmedProcess { nullptr };
601 WebProcessProxy* m_dummyProcessProxy { nullptr }; // A lightweight WebProcessProxy without backing process.
602
603 WebProcessProxy* m_processWithPageCache { nullptr };
604#if ENABLE(SERVICE_WORKER)
605 HashMap<WebCore::RegistrableDomain, ServiceWorkerProcessProxy*> m_serviceWorkerProcesses;
606 bool m_waitingForWorkerContextProcessConnection { false };
607 bool m_allowsAnySSLCertificateForServiceWorker { false };
608 bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
609 String m_serviceWorkerUserAgent;
610 Optional<WebPreferencesStore> m_serviceWorkerPreferences;
611 HashMap<String, bool> m_mayHaveRegisteredServiceWorkers;
612#endif
613
614 Ref<WebPageGroup> m_defaultPageGroup;
615
616 RefPtr<API::Object> m_injectedBundleInitializationUserData;
617 std::unique_ptr<API::InjectedBundleClient> m_injectedBundleClient;
618
619 WebContextClient m_client;
620 WebContextConnectionClient m_connectionClient;
621 std::unique_ptr<API::AutomationClient> m_automationClient;
622 std::unique_ptr<API::DownloadClient> m_downloadClient;
623 std::unique_ptr<API::LegacyContextHistoryClient> m_historyClient;
624 std::unique_ptr<API::CustomProtocolManagerClient> m_customProtocolManagerClient;
625
626 RefPtr<WebAutomationSession> m_automationSession;
627
628#if ENABLE(NETSCAPE_PLUGIN_API)
629 PluginInfoStore m_pluginInfoStore;
630#endif
631 Ref<VisitedLinkStore> m_visitedLinkStore;
632 bool m_visitedLinksPopulated { false };
633
634 PlugInAutoStartProvider m_plugInAutoStartProvider { this };
635
636 HashSet<String> m_schemesToRegisterAsEmptyDocument;
637 HashSet<String> m_schemesToRegisterAsSecure;
638 HashSet<String> m_schemesToRegisterAsBypassingContentSecurityPolicy;
639 HashSet<String> m_schemesToSetDomainRelaxationForbiddenFor;
640 HashSet<String> m_schemesToRegisterAsLocal;
641 HashSet<String> m_schemesToRegisterAsNoAccess;
642 HashSet<String> m_schemesToRegisterAsDisplayIsolated;
643 HashSet<String> m_schemesToRegisterAsCORSEnabled;
644 HashSet<String> m_schemesToRegisterAsAlwaysRevalidated;
645 HashSet<String> m_schemesToRegisterAsCachePartitioned;
646 HashSet<String> m_schemesServiceWorkersCanHandle;
647 HashSet<String> m_schemesToRegisterAsCanDisplayOnlyIfCanRequest;
648
649 bool m_alwaysUsesComplexTextCodePath { false };
650 bool m_shouldUseFontSmoothing { true };
651
652 Vector<String> m_fontWhitelist;
653
654 // Messages that were posted before any pages were created.
655 // The client should use initialization messages instead, so that a restarted process would get the same state.
656 Vector<std::pair<String, RefPtr<API::Object>>> m_messagesToInjectedBundlePostedToEmptyContext;
657
658 bool m_memorySamplerEnabled { false };
659 double m_memorySamplerInterval { 1400.0 };
660
661 RefPtr<API::WebsiteDataStore> m_websiteDataStore;
662
663 typedef HashMap<const char*, RefPtr<WebContextSupplement>, PtrHash<const char*>> WebContextSupplementMap;
664 WebContextSupplementMap m_supplements;
665
666#if USE(SOUP)
667 HTTPCookieAcceptPolicy m_initialHTTPCookieAcceptPolicy { HTTPCookieAcceptPolicyOnlyFromMainDocumentDomain };
668 WebCore::SoupNetworkProxySettings m_networkProxySettings;
669#endif
670 HashSet<String, ASCIICaseInsensitiveHash> m_urlSchemesRegisteredForCustomProtocols;
671
672#if PLATFORM(MAC)
673 RetainPtr<NSObject> m_enhancedAccessibilityObserver;
674 RetainPtr<NSObject> m_automaticTextReplacementNotificationObserver;
675 RetainPtr<NSObject> m_automaticSpellingCorrectionNotificationObserver;
676 RetainPtr<NSObject> m_automaticQuoteSubstitutionNotificationObserver;
677 RetainPtr<NSObject> m_automaticDashSubstitutionNotificationObserver;
678 RetainPtr<NSObject> m_accessibilityDisplayOptionsNotificationObserver;
679#if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
680 RetainPtr<NSObject> m_scrollerStyleNotificationObserver;
681#endif
682 RetainPtr<NSObject> m_activationObserver;
683 RetainPtr<NSObject> m_deactivationObserver;
684
685 std::unique_ptr<HighPerformanceGraphicsUsageSampler> m_highPerformanceGraphicsUsageSampler;
686 std::unique_ptr<PerActivityStateCPUUsageSampler> m_perActivityStateCPUUsageSampler;
687#endif
688
689#if PLATFORM(IOS_FAMILY)
690 RetainPtr<NSObject> m_accessibilityEnabledObserver;
691#endif
692
693 bool m_shouldUseTestingNetworkSession { false };
694
695 bool m_processTerminationEnabled { true };
696
697 bool m_canHandleHTTPSServerTrustEvaluation { true };
698 bool m_didNetworkProcessCrash { false };
699 std::unique_ptr<NetworkProcessProxy> m_networkProcess;
700
701 HashMap<uint64_t, RefPtr<DictionaryCallback>> m_dictionaryCallbacks;
702 HashMap<uint64_t, RefPtr<StatisticsRequest>> m_statisticsRequests;
703
704#if USE(SOUP)
705 bool m_ignoreTLSErrors { true };
706#endif
707
708 bool m_memoryCacheDisabled { false };
709 bool m_javaScriptConfigurationFileEnabled { false };
710 bool m_alwaysRunsAtBackgroundPriority;
711 bool m_shouldTakeUIBackgroundAssertion;
712 bool m_shouldMakeNextWebProcessLaunchFailForTesting { false };
713 bool m_shouldMakeNextNetworkProcessLaunchFailForTesting { false };
714
715 UserObservablePageCounter m_userObservablePageCounter;
716 ProcessSuppressionDisabledCounter m_processSuppressionDisabledForPageCounter;
717 HiddenPageThrottlingAutoIncreasesCounter m_hiddenPageThrottlingAutoIncreasesCounter;
718 RunLoop::Timer<WebProcessPool> m_hiddenPageThrottlingTimer;
719
720#if PLATFORM(COCOA)
721 RetainPtr<NSMutableDictionary> m_bundleParameters;
722 ProcessSuppressionDisabledToken m_pluginProcessManagerProcessSuppressionDisabledToken;
723#endif
724
725#if ENABLE(CONTENT_EXTENSIONS)
726 HashMap<String, String> m_encodedContentExtensions;
727#endif
728
729#if ENABLE(NETSCAPE_PLUGIN_API)
730 HashMap<String, HashMap<String, HashMap<String, uint8_t>>> m_pluginLoadClientPolicies;
731#endif
732
733#if ENABLE(GAMEPAD)
734 HashSet<WebProcessProxy*> m_processesUsingGamepads;
735#endif
736
737#if PLATFORM(COCOA)
738 bool m_cookieStoragePartitioningEnabled { false };
739 bool m_storageAccessAPIEnabled { false };
740#endif
741
742 struct Paths {
743 String injectedBundlePath;
744 String applicationCacheDirectory;
745 String webSQLDatabaseDirectory;
746 String mediaCacheDirectory;
747 String mediaKeyStorageDirectory;
748 String uiProcessBundleResourcePath;
749 String indexedDatabaseDirectory;
750
751#if PLATFORM(IOS_FAMILY)
752 String cookieStorageDirectory;
753 String containerCachesDirectory;
754 String containerTemporaryDirectory;
755#endif
756
757 Vector<String> additionalWebProcessSandboxExtensionPaths;
758 };
759 Paths m_resolvedPaths;
760
761 HashMap<PAL::SessionID, HashSet<uint64_t>> m_sessionToPageIDsMap;
762 RunLoop::Timer<WebProcessPool> m_serviceWorkerProcessesTerminationTimer;
763
764#if PLATFORM(IOS_FAMILY)
765 ForegroundWebProcessCounter m_foregroundWebProcessCounter;
766 BackgroundWebProcessCounter m_backgroundWebProcessCounter;
767 ProcessThrottler::ForegroundActivityToken m_foregroundTokenForNetworkProcess;
768 ProcessThrottler::BackgroundActivityToken m_backgroundTokenForNetworkProcess;
769#if ENABLE(SERVICE_WORKER)
770 HashMap<WebCore::RegistrableDomain, ProcessThrottler::ForegroundActivityToken> m_foregroundTokensForServiceWorkerProcesses;
771 HashMap<WebCore::RegistrableDomain, ProcessThrottler::BackgroundActivityToken> m_backgroundTokensForServiceWorkerProcesses;
772#endif
773#endif
774
775 Deque<std::unique_ptr<SuspendedPageProxy>> m_suspendedPages;
776 unsigned m_maxSuspendedPageCount { 0 };
777
778 UniqueRef<WebProcessCache> m_webProcessCache;
779 HashMap<WebCore::RegistrableDomain, RefPtr<WebProcessProxy>> m_swappedProcessesPerRegistrableDomain;
780
781 HashMap<WebCore::RegistrableDomain, std::unique_ptr<WebCore::PrewarmInformation>> m_prewarmInformationPerRegistrableDomain;
782
783#if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
784 Vector<std::unique_ptr<DisplayLink>> m_displayLinks;
785#endif
786
787#if PLATFORM(GTK) || PLATFORM(WPE)
788 bool m_sandboxEnabled { false };
789 HashMap<CString, SandboxPermission> m_extraSandboxPaths;
790#endif
791
792 HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesWithUploads;
793 std::unique_ptr<ProcessAssertion> m_uiProcessUploadAssertion;
794
795 HashMap<WebCore::ProcessIdentifier, std::unique_ptr<ProcessAssertion>> m_processesPlayingAudibleMedia;
796 std::unique_ptr<ProcessAssertion> m_uiProcessMediaPlaybackAssertion;
797
798#if PLATFORM(IOS)
799 // FIXME: Delayed process launch is currently disabled on iOS for performance reasons (rdar://problem/49074131).
800 bool m_isDelayedWebProcessLaunchDisabled { true };
801#else
802 bool m_isDelayedWebProcessLaunchDisabled { false };
803#endif
804};
805
806template<typename T>
807void WebProcessPool::sendToNetworkingProcess(T&& message)
808{
809 if (m_networkProcess && m_networkProcess->canSendMessage())
810 m_networkProcess->send(std::forward<T>(message), 0);
811}
812
813template<typename T>
814void WebProcessPool::sendToNetworkingProcessRelaunchingIfNecessary(T&& message)
815{
816 ensureNetworkProcess();
817 m_networkProcess->send(std::forward<T>(message), 0);
818}
819
820template<typename T>
821void WebProcessPool::sendToAllProcesses(const T& message)
822{
823 size_t processCount = m_processes.size();
824 for (size_t i = 0; i < processCount; ++i) {
825 WebProcessProxy* process = m_processes[i].get();
826 if (process->canSendMessage())
827 process->send(T(message), 0);
828 }
829}
830
831template<typename T>
832void WebProcessPool::sendToAllProcessesRelaunchingThemIfNecessary(const T& message)
833{
834 // 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.
835 sendToAllProcesses(message);
836}
837
838template<typename T>
839void WebProcessPool::sendToOneProcess(T&& message)
840{
841 bool messageSent = false;
842 size_t processCount = m_processes.size();
843 for (size_t i = 0; i < processCount; ++i) {
844 WebProcessProxy* process = m_processes[i].get();
845 if (process->canSendMessage()) {
846 process->send(std::forward<T>(message), 0);
847 messageSent = true;
848 break;
849 }
850 }
851
852 if (!messageSent) {
853 prewarmProcess();
854 RefPtr<WebProcessProxy> process = m_processes.last();
855 if (process->canSendMessage())
856 process->send(std::forward<T>(message), 0);
857 }
858}
859
860} // namespace WebKit
861