Enable service worker to use cache storage api
[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(const WebPreferencesStore&);
303 #endif
304
305     void releasePageCache();
306
307     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WebsiteData&);
308     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, std::chrono::system_clock::time_point modifiedSince);
309     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>& origins);
310
311     void setMemoryCacheDisabled(bool);
312
313 #if ENABLE(SERVICE_CONTROLS)
314     void setEnabledServices(bool hasImageServices, bool hasSelectionServices, bool hasRichContentServices);
315 #endif
316
317     void handleInjectedBundleMessage(const String& messageName, const UserData& messageBody);
318     void setInjectedBundleParameter(const String& key, const IPC::DataReference&);
319     void setInjectedBundleParameters(const IPC::DataReference&);
320
321     enum class ShouldAcknowledgeWhenReadyToSuspend { No, Yes };
322     void actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend);
323
324     void ensureAutomationSessionProxy(const String& sessionIdentifier);
325     void destroyAutomationSessionProxy();
326
327     void logDiagnosticMessageForNetworkProcessCrash();
328     bool hasVisibleWebPage() const;
329     void updateCPULimit();
330     enum class CPUMonitorUpdateReason { LimitHasChanged, VisibilityHasChanged };
331     void updateCPUMonitorState(CPUMonitorUpdateReason);
332
333     // ChildProcess
334     void initializeProcess(const ChildProcessInitializationParameters&) override;
335     void initializeProcessName(const ChildProcessInitializationParameters&) override;
336     void initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&) override;
337     void initializeConnection(IPC::Connection*) override;
338     bool shouldTerminate() override;
339     void terminate() override;
340
341 #if USE(APPKIT)
342     void stopRunLoop() override;
343 #endif
344
345     void platformInitializeProcess(const ChildProcessInitializationParameters&);
346
347     // IPC::Connection::Client
348     friend class WebConnectionToUIProcess;
349     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
350     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
351     void didClose(IPC::Connection&) override;
352
353     // Implemented in generated WebProcessMessageReceiver.cpp
354     void didReceiveWebProcessMessage(IPC::Connection&, IPC::Decoder&);
355     void didReceiveSyncWebProcessMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
356
357     RefPtr<WebConnectionToUIProcess> m_webConnection;
358
359     HashMap<uint64_t, RefPtr<WebPage>> m_pageMap;
360     HashMap<uint64_t, RefPtr<WebPageGroupProxy>> m_pageGroupMap;
361     RefPtr<InjectedBundle> m_injectedBundle;
362
363     RefPtr<EventDispatcher> m_eventDispatcher;
364 #if PLATFORM(IOS)
365     RefPtr<ViewUpdateDispatcher> m_viewUpdateDispatcher;
366 #endif
367     RefPtr<WebInspectorInterruptDispatcher> m_webInspectorInterruptDispatcher;
368
369     HashMap<PAL::SessionID, HashMap<unsigned, double>> m_plugInAutoStartOriginHashes;
370     HashSet<String> m_plugInAutoStartOrigins;
371
372     bool m_hasSetCacheModel { false };
373     CacheModel m_cacheModel { CacheModelDocumentViewer };
374
375 #if PLATFORM(COCOA)
376     WebCore::MachSendRight m_compositingRenderServerPort;
377 #endif
378
379     bool m_fullKeyboardAccessEnabled { false };
380
381     HashMap<uint64_t, WebFrame*> m_frameMap;
382
383     typedef HashMap<const char*, std::unique_ptr<WebProcessSupplement>, PtrHash<const char*>> WebProcessSupplementMap;
384     WebProcessSupplementMap m_supplements;
385
386     TextCheckerState m_textCheckerState;
387
388     void ensureNetworkProcessConnection();
389     RefPtr<NetworkProcessConnection> m_networkProcessConnection;
390     WebLoaderStrategy& m_webLoaderStrategy;
391
392     Ref<WebCacheStorageProvider> m_cacheStorageProvider;
393
394 #if USE(LIBWEBRTC)
395     std::unique_ptr<LibWebRTCNetwork> m_libWebRTCNetwork;
396 #endif
397
398     HashSet<String> m_dnsPrefetchedHosts;
399     PAL::HysteresisActivity m_dnsPrefetchHystereris;
400
401     std::unique_ptr<WebAutomationSessionProxy> m_automationSessionProxy;
402
403     void ensureWebToStorageProcessConnection();
404     RefPtr<WebToStorageProcessConnection> m_webToStorageProcessConnection;
405
406 #if ENABLE(NETSCAPE_PLUGIN_API)
407     RefPtr<PluginProcessConnectionManager> m_pluginProcessConnectionManager;
408 #endif
409
410 #if ENABLE(SERVICE_CONTROLS)
411     bool m_hasImageServices { false };
412     bool m_hasSelectionServices { false };
413     bool m_hasRichContentServices { false };
414 #endif
415
416     HashSet<uint64_t> m_pagesInWindows;
417     WebCore::Timer m_nonVisibleProcessCleanupTimer;
418
419     RefPtr<WebCore::ApplicationCacheStorage> m_applicationCacheStorage;
420
421 #if PLATFORM(IOS)
422     WebSQLiteDatabaseTracker m_webSQLiteDatabaseTracker;
423 #endif
424
425     enum PageMarkingLayersAsVolatileCounterType { };
426     using PageMarkingLayersAsVolatileCounter = RefCounter<PageMarkingLayersAsVolatileCounterType>;
427     std::unique_ptr<PageMarkingLayersAsVolatileCounter> m_pageMarkingLayersAsVolatileCounter;
428
429     bool m_suppressMemoryPressureHandler { false };
430 #if PLATFORM(MAC)
431     std::unique_ptr<WebCore::CPUMonitor> m_cpuMonitor;
432     std::optional<double> m_cpuLimit;
433 #endif
434
435     HashMap<WebCore::UserGestureToken *, uint64_t> m_userGestureTokens;
436
437 #if PLATFORM(WAYLAND)
438     std::unique_ptr<WaylandCompositorDisplay> m_waylandCompositorDisplay;
439 #endif
440 #if ENABLE(SERVICE_WORKER)
441     std::optional<ServiceWorkerContextManager> m_serviceWorkerManager;
442 #endif
443 };
444
445 } // namespace WebKit