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