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