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