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