WebProcessPool should not ask to register all clients for each service worker process...
[WebKit-https.git] / Source / WebKit / WebProcess / WebProcess.h
1 /*
2  * Copyright (C) 2010-2017 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 "CacheModel.h"
29 #include "ChildProcess.h"
30 #include "PluginProcessConnectionManager.h"
31 #include "ResourceCachesToClear.h"
32 #include "SandboxExtension.h"
33 #include "TextCheckerState.h"
34 #include "ViewUpdateDispatcher.h"
35 #include "WebInspectorInterruptDispatcher.h"
36 #include <WebCore/ActivityState.h>
37 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
38 #include <WebCore/ScreenProperties.h>
39 #endif
40 #include <WebCore/Timer.h>
41 #include <pal/HysteresisActivity.h>
42 #include <pal/SessionID.h>
43 #include <wtf/Forward.h>
44 #include <wtf/HashMap.h>
45 #include <wtf/HashSet.h>
46 #include <wtf/RefCounter.h>
47 #include <wtf/text/AtomicString.h>
48 #include <wtf/text/AtomicStringHash.h>
49
50 #if PLATFORM(COCOA)
51 #include <dispatch/dispatch.h>
52 #include <WebCore/MachSendRight.h>
53 #endif
54
55 #if PLATFORM(IOS)
56 #include "WebSQLiteDatabaseTracker.h"
57 #endif
58
59 namespace API {
60 class Object;
61 }
62
63 namespace PAL {
64 class SessionID;
65 }
66
67 namespace WebCore {
68 class ApplicationCacheStorage;
69 class CPUMonitor;
70 class CertificateInfo;
71 class PageGroup;
72 class ResourceRequest;
73 class UserGestureToken;
74 struct MessagePortIdentifier;
75 struct MessageWithMessagePorts;
76 struct PluginInfo;
77 struct SecurityOriginData;
78 struct SoupNetworkProxySettings;
79
80 #if ENABLE(SERVICE_WORKER)
81 struct ServiceWorkerContextData;
82 #endif
83 }
84
85 namespace WebKit {
86
87 class EventDispatcher;
88 class GamepadData;
89 class InjectedBundle;
90 class LibWebRTCNetwork;
91 class NetworkProcessConnection;
92 class ObjCObjectGraph;
93 class UserData;
94 class WaylandCompositorDisplay;
95 class WebAutomationSessionProxy;
96 class WebCacheStorageProvider;
97 class WebConnectionToUIProcess;
98 class WebFrame;
99 class WebLoaderStrategy;
100 class WebPage;
101 class WebPageGroupProxy;
102 class WebProcessSupplement;
103 class WebToStorageProcessConnection;
104 enum class WebsiteDataType;
105 struct WebPageCreationParameters;
106 struct WebPageGroupData;
107 struct WebPreferencesStore;
108 struct WebProcessCreationParameters;
109 struct WebsiteData;
110 struct WebsiteDataStoreParameters;
111
112 class WebProcess : public ChildProcess {
113 public:
114     static WebProcess& singleton();
115
116     template <typename T>
117     T* supplement()
118     {
119         return static_cast<T*>(m_supplements.get(T::supplementName()));
120     }
121
122     template <typename T>
123     void addSupplement()
124     {
125         m_supplements.add(T::supplementName(), std::make_unique<T>(*this));
126     }
127
128     WebConnectionToUIProcess* webConnectionToUIProcess() const { return m_webConnection.get(); }
129
130     WebPage* webPage(uint64_t pageID) const;
131     void createWebPage(uint64_t pageID, WebPageCreationParameters&&);
132     void removeWebPage(uint64_t pageID);
133     WebPage* focusedWebPage() const;
134
135     InjectedBundle* injectedBundle() const { return m_injectedBundle.get(); }
136
137 #if PLATFORM(COCOA)
138     const WebCore::MachSendRight& compositingRenderServerPort() const { return m_compositingRenderServerPort; }
139 #endif
140
141     bool shouldPlugInAutoStartFromOrigin(WebPage&, const String& pageOrigin, const String& pluginOrigin, const String& mimeType);
142     void plugInDidStartFromOrigin(const String& pageOrigin, const String& pluginOrigin, const String& mimeType, PAL::SessionID);
143     void plugInDidReceiveUserInteraction(const String& pageOrigin, const String& pluginOrigin, const String& mimeType, PAL::SessionID);
144     void setPluginLoadClientPolicy(uint8_t policy, const String& host, const String& bundleIdentifier, const String& versionString);
145     void resetPluginLoadClientPolicies(const HashMap<String, HashMap<String, HashMap<String, uint8_t>>>&);
146     void clearPluginClientPolicies();
147     void refreshPlugins();
148
149     bool fullKeyboardAccessEnabled() const { return m_fullKeyboardAccessEnabled; }
150
151     WebFrame* webFrame(uint64_t) const;
152     void addWebFrame(uint64_t, WebFrame*);
153     void removeWebFrame(uint64_t);
154
155     WebPageGroupProxy* webPageGroup(WebCore::PageGroup*);
156     WebPageGroupProxy* webPageGroup(uint64_t pageGroupID);
157     WebPageGroupProxy* webPageGroup(const WebPageGroupData&);
158
159     uint64_t userGestureTokenIdentifier(RefPtr<WebCore::UserGestureToken>);
160     void userGestureTokenDestroyed(WebCore::UserGestureToken&);
161     
162     const TextCheckerState& textCheckerState() const { return m_textCheckerState; }
163     void setTextCheckerState(const TextCheckerState&);
164
165     void clearResourceCaches(ResourceCachesToClear = AllResourceCaches);
166     
167 #if ENABLE(NETSCAPE_PLUGIN_API)
168     PluginProcessConnectionManager& pluginProcessConnectionManager();
169 #endif
170
171     EventDispatcher& eventDispatcher() { return *m_eventDispatcher; }
172
173     NetworkProcessConnection& ensureNetworkProcessConnection();
174     void networkProcessConnectionClosed(NetworkProcessConnection*);
175     WebLoaderStrategy& webLoaderStrategy();
176
177 #if USE(LIBWEBRTC)
178     LibWebRTCNetwork& libWebRTCNetwork();
179 #endif
180
181     void webToStorageProcessConnectionClosed(WebToStorageProcessConnection*);
182     WebToStorageProcessConnection* existingWebToStorageProcessConnection() { return m_webToStorageProcessConnection.get(); }
183     WebToStorageProcessConnection& ensureWebToStorageProcessConnection(PAL::SessionID initialSessionID);
184
185     void setCacheModel(uint32_t);
186
187     void ensureLegacyPrivateBrowsingSessionInNetworkProcess();
188     void addWebsiteDataStore(WebsiteDataStoreParameters&&);
189     void destroySession(PAL::SessionID);
190
191     void pageDidEnterWindow(uint64_t pageID);
192     void pageWillLeaveWindow(uint64_t pageID);
193
194     void nonVisibleProcessCleanupTimerFired();
195
196 #if PLATFORM(COCOA)
197     RetainPtr<CFDataRef> sourceApplicationAuditData() const;
198     void destroyRenderingResources();
199 #endif
200
201     void updateActivePages();
202     void pageActivityStateDidChange(uint64_t pageID, WebCore::ActivityState::Flags changed);
203
204     void setHiddenPageDOMTimerThrottlingIncreaseLimit(int milliseconds);
205
206     void processWillSuspendImminently(bool& handled);
207     void prepareToSuspend();
208     void cancelPrepareToSuspend();
209     void processDidResume();
210
211 #if PLATFORM(IOS)
212     void resetAllGeolocationPermissions();
213 #endif
214
215 #if PLATFORM(WAYLAND)
216     WaylandCompositorDisplay* waylandCompositorDisplay() const { return m_waylandCompositorDisplay.get(); }
217 #endif
218
219     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
220     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
221
222 #if PLATFORM(COCOA)
223     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
224     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
225 #endif
226
227 #if ENABLE(SERVICE_CONTROLS)
228     bool hasImageServices() const { return m_hasImageServices; }
229     bool hasSelectionServices() const { return m_hasSelectionServices; }
230     bool hasRichContentServices() const { return m_hasRichContentServices; }
231 #endif
232
233     WebCore::ApplicationCacheStorage& applicationCacheStorage() { return *m_applicationCacheStorage; }
234
235     void prefetchDNS(const String&);
236
237     WebAutomationSessionProxy* automationSessionProxy() { return m_automationSessionProxy.get(); }
238
239     WebCacheStorageProvider& cacheStorageProvider() { return m_cacheStorageProvider.get(); }
240
241 #if PLATFORM(IOS)
242     void accessibilityProcessSuspendedNotification(bool);
243 #endif
244
245 private:
246     WebProcess();
247     ~WebProcess();
248
249     void initializeWebProcess(WebProcessCreationParameters&&);
250     void platformInitializeWebProcess(WebProcessCreationParameters&&);
251
252 #if USE(OS_STATE)
253     void registerWithStateDumper();
254 #endif
255
256     void markAllLayersVolatile(WTF::Function<void()>&& completionHandler);
257     void cancelMarkAllLayersVolatile();
258     void setAllLayerTreeStatesFrozen(bool);
259     void processSuspensionCleanupTimerFired();
260
261     void clearCachedCredentials();
262
263     void platformTerminate();
264
265     void registerURLSchemeAsEmptyDocument(const String&);
266     void registerURLSchemeAsSecure(const String&) const;
267     void registerURLSchemeAsBypassingContentSecurityPolicy(const String&) const;
268     void setDomainRelaxationForbiddenForURLScheme(const String&) const;
269     void registerURLSchemeAsLocal(const String&) const;
270     void registerURLSchemeAsNoAccess(const String&) const;
271     void registerURLSchemeAsDisplayIsolated(const String&) const;
272     void registerURLSchemeAsCORSEnabled(const String&) const;
273     void registerURLSchemeAsAlwaysRevalidated(const String&) const;
274     void registerURLSchemeAsCachePartitioned(const String&) const;
275     void registerURLSchemeAsCanDisplayOnlyIfCanRequest(const String&) const;
276
277     void setDefaultRequestTimeoutInterval(double);
278     void setAlwaysUsesComplexTextCodePath(bool);
279     void setShouldUseFontSmoothing(bool);
280     void setResourceLoadStatisticsEnabled(bool);
281     void clearResourceLoadStatistics();
282     void userPreferredLanguagesChanged(const Vector<String>&) const;
283     void fullKeyboardAccessModeChanged(bool fullKeyboardAccessEnabled);
284
285     bool isPlugInAutoStartOriginHash(unsigned plugInOriginHash, PAL::SessionID);
286     void didAddPlugInAutoStartOriginHash(unsigned plugInOriginHash, WallTime expirationTime, PAL::SessionID);
287     void resetPlugInAutoStartOriginDefaultHashes(const HashMap<unsigned, WallTime>& hashes);
288     void resetPlugInAutoStartOriginHashes(const HashMap<PAL::SessionID, HashMap<unsigned, WallTime>>& hashes);
289
290     void platformSetCacheModel(CacheModel);
291
292     void setEnhancedAccessibility(bool);
293     
294     void startMemorySampler(SandboxExtension::Handle&&, const String&, const double);
295     void stopMemorySampler();
296     
297     void getWebCoreStatistics(uint64_t callbackID);
298     void garbageCollectJavaScriptObjects();
299     void setJavaScriptGarbageCollectorTimerEnabled(bool flag);
300
301     void mainThreadPing();
302     void backgroundResponsivenessPing();
303
304     void syncIPCMessageWhileWaitingForSyncReplyForTesting();
305
306     void didTakeAllMessagesForPort(Vector<WebCore::MessageWithMessagePorts>&& messages, uint64_t messageCallbackIdentifier, uint64_t messageBatchIdentifier);
307     void checkProcessLocalPortForActivity(const WebCore::MessagePortIdentifier&, uint64_t callbackIdentifier);
308     void didCheckRemotePortForActivity(uint64_t callbackIdentifier, bool hasActivity);
309     void messagesAvailableForPort(const WebCore::MessagePortIdentifier&);
310
311 #if ENABLE(GAMEPAD)
312     void setInitialGamepads(const Vector<GamepadData>&);
313     void gamepadConnected(const GamepadData&);
314     void gamepadDisconnected(unsigned index);
315 #endif
316 #if USE(SOUP)
317     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
318 #endif
319 #if ENABLE(SERVICE_WORKER)
320     void establishWorkerContextConnectionToStorageProcess(uint64_t pageGroupID, uint64_t pageID, const WebPreferencesStore&, PAL::SessionID);
321     void registerServiceWorkerClients();
322 #endif
323
324     void releasePageCache();
325
326     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WebsiteData&);
327     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince);
328     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>& origins);
329
330     void setMemoryCacheDisabled(bool);
331
332 #if ENABLE(SERVICE_CONTROLS)
333     void setEnabledServices(bool hasImageServices, bool hasSelectionServices, bool hasRichContentServices);
334 #endif
335
336     void handleInjectedBundleMessage(const String& messageName, const UserData& messageBody);
337     void setInjectedBundleParameter(const String& key, const IPC::DataReference&);
338     void setInjectedBundleParameters(const IPC::DataReference&);
339
340     enum class ShouldAcknowledgeWhenReadyToSuspend { No, Yes };
341     void actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend);
342
343     void ensureAutomationSessionProxy(const String& sessionIdentifier);
344     void destroyAutomationSessionProxy();
345
346     void logDiagnosticMessageForNetworkProcessCrash();
347     bool hasVisibleWebPage() const;
348     void updateCPULimit();
349     enum class CPUMonitorUpdateReason { LimitHasChanged, VisibilityHasChanged };
350     void updateCPUMonitorState(CPUMonitorUpdateReason);
351
352     // ChildProcess
353     void initializeProcess(const ChildProcessInitializationParameters&) override;
354     void initializeProcessName(const ChildProcessInitializationParameters&) override;
355     void initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&) override;
356     void initializeConnection(IPC::Connection*) override;
357     bool shouldTerminate() override;
358     void terminate() override;
359
360 #if USE(APPKIT)
361     void stopRunLoop() override;
362 #endif
363
364     void platformInitializeProcess(const ChildProcessInitializationParameters&);
365
366     // IPC::Connection::Client
367     friend class WebConnectionToUIProcess;
368     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
369     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
370     void didClose(IPC::Connection&) override;
371
372     // Implemented in generated WebProcessMessageReceiver.cpp
373     void didReceiveWebProcessMessage(IPC::Connection&, IPC::Decoder&);
374     void didReceiveSyncWebProcessMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
375
376 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
377     void setScreenProperties(const HashMap<uint32_t, WebCore::ScreenProperties>&);
378     void scrollerStylePreferenceChanged(bool useOverlayScrollbars);
379 #endif
380
381     RefPtr<WebConnectionToUIProcess> m_webConnection;
382
383     HashMap<uint64_t, RefPtr<WebPage>> m_pageMap;
384     HashMap<uint64_t, RefPtr<WebPageGroupProxy>> m_pageGroupMap;
385     RefPtr<InjectedBundle> m_injectedBundle;
386
387     RefPtr<EventDispatcher> m_eventDispatcher;
388 #if PLATFORM(IOS)
389     RefPtr<ViewUpdateDispatcher> m_viewUpdateDispatcher;
390 #endif
391     RefPtr<WebInspectorInterruptDispatcher> m_webInspectorInterruptDispatcher;
392
393     HashMap<PAL::SessionID, HashMap<unsigned, WallTime>> m_plugInAutoStartOriginHashes;
394     HashSet<String> m_plugInAutoStartOrigins;
395
396     bool m_hasSetCacheModel { false };
397     CacheModel m_cacheModel { CacheModelDocumentViewer };
398
399 #if PLATFORM(COCOA)
400     WebCore::MachSendRight m_compositingRenderServerPort;
401 #endif
402
403     bool m_fullKeyboardAccessEnabled { false };
404
405     HashMap<uint64_t, WebFrame*> m_frameMap;
406
407     typedef HashMap<const char*, std::unique_ptr<WebProcessSupplement>, PtrHash<const char*>> WebProcessSupplementMap;
408     WebProcessSupplementMap m_supplements;
409
410     TextCheckerState m_textCheckerState;
411
412     RefPtr<NetworkProcessConnection> m_networkProcessConnection;
413     WebLoaderStrategy& m_webLoaderStrategy;
414
415     Ref<WebCacheStorageProvider> m_cacheStorageProvider;
416
417 #if USE(LIBWEBRTC)
418     std::unique_ptr<LibWebRTCNetwork> m_libWebRTCNetwork;
419 #endif
420
421     HashSet<String> m_dnsPrefetchedHosts;
422     PAL::HysteresisActivity m_dnsPrefetchHystereris;
423
424     std::unique_ptr<WebAutomationSessionProxy> m_automationSessionProxy;
425
426     RefPtr<WebToStorageProcessConnection> m_webToStorageProcessConnection;
427
428 #if ENABLE(NETSCAPE_PLUGIN_API)
429     RefPtr<PluginProcessConnectionManager> m_pluginProcessConnectionManager;
430 #endif
431
432 #if ENABLE(SERVICE_CONTROLS)
433     bool m_hasImageServices { false };
434     bool m_hasSelectionServices { false };
435     bool m_hasRichContentServices { false };
436 #endif
437
438     HashSet<uint64_t> m_pagesInWindows;
439     WebCore::Timer m_nonVisibleProcessCleanupTimer;
440
441     RefPtr<WebCore::ApplicationCacheStorage> m_applicationCacheStorage;
442
443 #if PLATFORM(IOS)
444     WebSQLiteDatabaseTracker m_webSQLiteDatabaseTracker;
445 #endif
446
447     enum PageMarkingLayersAsVolatileCounterType { };
448     using PageMarkingLayersAsVolatileCounter = RefCounter<PageMarkingLayersAsVolatileCounterType>;
449     std::unique_ptr<PageMarkingLayersAsVolatileCounter> m_pageMarkingLayersAsVolatileCounter;
450
451     bool m_suppressMemoryPressureHandler { false };
452 #if PLATFORM(MAC)
453     std::unique_ptr<WebCore::CPUMonitor> m_cpuMonitor;
454     std::optional<double> m_cpuLimit;
455 #endif
456
457     HashMap<WebCore::UserGestureToken *, uint64_t> m_userGestureTokens;
458
459 #if PLATFORM(WAYLAND)
460     std::unique_ptr<WaylandCompositorDisplay> m_waylandCompositorDisplay;
461 #endif
462 };
463
464 } // namespace WebKit