Enable library validation on the Web Content service
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessProxy.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 "APIUserInitiatedAction.h"
29 #include "BackgroundProcessResponsivenessTimer.h"
30 #include "ChildProcessProxy.h"
31 #include "MessageReceiverMap.h"
32 #include "PluginInfoStore.h"
33 #include "ProcessLauncher.h"
34 #include "ProcessTerminationReason.h"
35 #include "ProcessThrottler.h"
36 #include "ProcessThrottlerClient.h"
37 #include "ResponsivenessTimer.h"
38 #include "VisibleWebPageCounter.h"
39 #include "WebConnectionToWebProcess.h"
40 #include "WebProcessProxyMessages.h"
41 #include <WebCore/MessagePortChannelProvider.h>
42 #include <WebCore/MessagePortIdentifier.h>
43 #include <WebCore/Process.h>
44 #include <WebCore/SharedStringHash.h>
45 #include <memory>
46 #include <pal/SessionID.h>
47 #include <wtf/Forward.h>
48 #include <wtf/HashMap.h>
49 #include <wtf/HashSet.h>
50 #include <wtf/RefCounted.h>
51 #include <wtf/RefPtr.h>
52
53 namespace API {
54 class PageConfiguration;
55 }
56
57 namespace WebCore {
58 class ResourceRequest;
59 class URL;
60 struct PluginInfo;
61 struct SecurityOriginData;
62 }
63
64 namespace WebKit {
65
66 class NetworkProcessProxy;
67 class ObjCObjectGraph;
68 class PageClient;
69 class UserMediaCaptureManagerProxy;
70 class VisitedLinkStore;
71 class WebBackForwardListItem;
72 class WebFrameProxy;
73 class WebPageGroup;
74 class WebPageProxy;
75 class WebProcessPool;
76 class WebUserContentControllerProxy;
77 class WebsiteDataStore;
78 enum class WebsiteDataType;
79 struct WebNavigationDataStore;
80 struct WebPageCreationParameters;
81 struct WebsiteData;
82
83 #if PLATFORM(IOS)
84 enum ForegroundWebProcessCounterType { };
85 typedef RefCounter<ForegroundWebProcessCounterType> ForegroundWebProcessCounter;
86 typedef ForegroundWebProcessCounter::Token ForegroundWebProcessToken;
87 enum BackgroundWebProcessCounterType { };
88 typedef RefCounter<BackgroundWebProcessCounterType> BackgroundWebProcessCounter;
89 typedef BackgroundWebProcessCounter::Token BackgroundWebProcessToken;
90 #endif
91
92 class WebProcessProxy : public ChildProcessProxy, public ResponsivenessTimer::Client, private ProcessThrottlerClient {
93 public:
94     typedef HashMap<uint64_t, RefPtr<WebBackForwardListItem>> WebBackForwardListItemMap;
95     typedef HashMap<uint64_t, RefPtr<WebFrameProxy>> WebFrameProxyMap;
96     typedef HashMap<uint64_t, WebPageProxy*> WebPageProxyMap;
97     typedef HashMap<uint64_t, RefPtr<API::UserInitiatedAction>> UserInitiatedActionMap;
98
99     static Ref<WebProcessProxy> create(WebProcessPool&, WebsiteDataStore&);
100     ~WebProcessProxy();
101
102     WebConnection* webConnection() const { return m_webConnection.get(); }
103
104     WebProcessPool& processPool() { return m_processPool; }
105
106     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2
107     WebsiteDataStore& websiteDataStore() const { return m_websiteDataStore.get(); }
108
109     static WebProcessProxy* processForIdentifier(WebCore::ProcessIdentifier);
110     static WebPageProxy* webPage(uint64_t pageID);
111     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
112     void addExistingWebPage(WebPageProxy&, uint64_t pageID);
113     void removeWebPage(WebPageProxy&, uint64_t pageID);
114
115     typename WebPageProxyMap::ValuesConstIteratorRange pages() const { return m_pageMap.values(); }
116     unsigned pageCount() const { return m_pageMap.size(); }
117     unsigned visiblePageCount() const { return m_visiblePageCounter.value(); }
118
119     virtual bool isServiceWorkerProcess() const { return false; }
120
121     void addVisitedLinkStore(VisitedLinkStore&);
122     void addWebUserContentControllerProxy(WebUserContentControllerProxy&, WebPageCreationParameters&);
123     void didDestroyVisitedLinkStore(VisitedLinkStore&);
124     void didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy&);
125
126     WebBackForwardListItem* webBackForwardItem(uint64_t itemID) const;
127     RefPtr<API::UserInitiatedAction> userInitiatedActivity(uint64_t);
128
129     ResponsivenessTimer& responsivenessTimer() { return m_responsivenessTimer; }
130     bool isResponsive() const;
131
132     WebFrameProxy* webFrame(uint64_t) const;
133     bool canCreateFrame(uint64_t frameID) const;
134     void frameCreated(uint64_t, WebFrameProxy*);
135     void disconnectFramesFromPage(WebPageProxy*); // Including main frame.
136     size_t frameCountInPage(WebPageProxy*) const; // Including main frame.
137
138     VisibleWebPageToken visiblePageToken() const;
139
140     void testIncomingSyncIPCMessageWhileWaitingForSyncReply(bool& handled);
141
142     void updateTextCheckerState();
143
144     void registerNewWebBackForwardListItem(WebBackForwardListItem&);
145     void removeBackForwardItem(uint64_t);
146
147     void willAcquireUniversalFileReadSandboxExtension() { m_mayHaveUniversalFileReadSandboxExtension = true; }
148     void assumeReadAccessToBaseURL(const String&);
149     bool hasAssumedReadAccessToURL(const WebCore::URL&) const;
150
151     bool checkURLReceivedFromWebProcess(const String&);
152     bool checkURLReceivedFromWebProcess(const WebCore::URL&);
153
154     static bool fullKeyboardAccessEnabled();
155
156     void didSaveToPageCache();
157     void releasePageCache();
158
159     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, Function<void(WebsiteData)>&& completionHandler);
160     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince, Function<void()>&& completionHandler);
161     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>&, Function<void()>&& completionHandler);
162     static void deleteWebsiteDataForTopPrivatelyControlledDomainsInAllPersistentDataStores(OptionSet<WebsiteDataType>, Vector<String>&& topPrivatelyControlledDomains, bool shouldNotifyPages, Function<void (const HashSet<String>&)>&& completionHandler);
163     static void topPrivatelyControlledDomainsWithWebsiteData(OptionSet<WebsiteDataType> dataTypes, bool shouldNotifyPage, Function<void(HashSet<String>&&)>&& completionHandler);
164     static void notifyPageStatisticsAndDataRecordsProcessed();
165     static void notifyPageStatisticsTelemetryFinished(API::Object* messageBody);
166
167     void enableSuddenTermination();
168     void disableSuddenTermination();
169     bool isSuddenTerminationEnabled() { return !m_numberOfTimesSuddenTerminationWasDisabled; }
170
171     void requestTermination(ProcessTerminationReason);
172
173     void stopResponsivenessTimer();
174
175     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
176     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
177
178 #if PLATFORM(COCOA)
179     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
180     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
181 #endif
182
183     void windowServerConnectionStateChanged();
184
185     void processReadyToSuspend();
186     void didCancelProcessSuspension();
187
188     void setIsHoldingLockedFiles(bool);
189
190     ProcessThrottler& throttler() { return m_throttler; }
191
192     void isResponsive(WTF::Function<void(bool isWebProcessResponsive)>&&);
193     void didReceiveMainThreadPing();
194     void didReceiveBackgroundResponsivenessPing();
195
196     void memoryPressureStatusChanged(bool isUnderMemoryPressure) { m_isUnderMemoryPressure = isUnderMemoryPressure; }
197     bool isUnderMemoryPressure() const { return m_isUnderMemoryPressure; }
198     void didExceedInactiveMemoryLimitWhileActive();
199
200     void processTerminated();
201
202     void didExceedCPULimit();
203     void didExceedActiveMemoryLimit();
204     void didExceedInactiveMemoryLimit();
205
206     void checkProcessLocalPortForActivity(const WebCore::MessagePortIdentifier&, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>&&);
207
208 protected:
209     static uint64_t generatePageID();
210     WebProcessProxy(WebProcessPool&, WebsiteDataStore&);
211
212     // ChildProcessProxy
213     void getLaunchOptions(ProcessLauncher::LaunchOptions&) override;
214     void connectionWillOpen(IPC::Connection&) override;
215     void processWillShutDown(IPC::Connection&) override;
216
217 private:
218     // Called when the web process has crashed or we know that it will terminate soon.
219     // Will potentially cause the WebProcessProxy object to be freed.
220     void shutDown();
221
222     // IPC message handlers.
223     void addBackForwardItem(uint64_t itemID, uint64_t pageID, const PageState&);
224     void didDestroyFrame(uint64_t);
225     void didDestroyUserGestureToken(uint64_t);
226
227     void shouldTerminate(bool& shouldTerminate);
228
229     void createNewMessagePortChannel(const WebCore::MessagePortIdentifier& port1, const WebCore::MessagePortIdentifier& port2);
230     void entangleLocalPortInThisProcessToRemote(const WebCore::MessagePortIdentifier& local, const WebCore::MessagePortIdentifier& remote);
231     void messagePortDisentangled(const WebCore::MessagePortIdentifier&);
232     void messagePortClosed(const WebCore::MessagePortIdentifier&);
233     void takeAllMessagesForPort(const WebCore::MessagePortIdentifier&, uint64_t messagesCallbackIdentifier);
234     void postMessageToRemote(WebCore::MessageWithMessagePorts&&, const WebCore::MessagePortIdentifier&);
235     void checkRemotePortForActivity(const WebCore::MessagePortIdentifier, uint64_t callbackIdentifier);
236     void didDeliverMessagePortMessages(uint64_t messageBatchIdentifier);
237     void didCheckProcessLocalPortForActivity(uint64_t callbackIdentifier, bool isLocallyReachable);
238
239     // Plugins
240 #if ENABLE(NETSCAPE_PLUGIN_API)
241     void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins, Vector<WebCore::PluginInfo>& applicationPlugins);
242 #endif // ENABLE(NETSCAPE_PLUGIN_API)
243 #if ENABLE(NETSCAPE_PLUGIN_API)
244     void getPluginProcessConnection(uint64_t pluginProcessToken, Ref<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>&&);
245 #endif
246     void getNetworkProcessConnection(Ref<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>&&);
247     void getStorageProcessConnection(PAL::SessionID initialSessionID, Ref<Messages::WebProcessProxy::GetStorageProcessConnection::DelayedReply>&&);
248
249     bool platformIsBeingDebugged() const;
250     bool shouldAllowNonValidInjectedCode() const;
251
252     static const HashSet<String>& platformPathsWithAssumedReadAccess();
253
254     void updateBackgroundResponsivenessTimer();
255
256     // IPC::Connection::Client
257     friend class WebConnectionToWebProcess;
258     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
259     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
260     void didClose(IPC::Connection&) override;
261     void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override;
262
263     // ResponsivenessTimer::Client
264     void didBecomeUnresponsive() override;
265     void didBecomeResponsive() override;
266     void willChangeIsResponsive() override;
267     void didChangeIsResponsive() override;
268     bool mayBecomeUnresponsive() override;
269
270     // ProcessThrottlerClient
271     void sendProcessWillSuspendImminently() override;
272     void sendPrepareToSuspend() override;
273     void sendCancelPrepareToSuspend() override;
274     void sendProcessDidResume() override;
275     void didSetAssertionState(AssertionState) override;
276
277     // ProcessLauncher::Client
278     void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override;
279
280     // Implemented in generated WebProcessProxyMessageReceiver.cpp
281     void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&);
282     void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
283
284     bool canTerminateChildProcess();
285
286     void logDiagnosticMessageForResourceLimitTermination(const String& limitKey);
287
288     ResponsivenessTimer m_responsivenessTimer;
289     BackgroundProcessResponsivenessTimer m_backgroundResponsivenessTimer;
290     
291     RefPtr<WebConnectionToWebProcess> m_webConnection;
292     Ref<WebProcessPool> m_processPool;
293
294     bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it.
295     HashSet<String> m_localPathsWithAssumedReadAccess;
296
297     WebPageProxyMap m_pageMap;
298     WebFrameProxyMap m_frameMap;
299     WebBackForwardListItemMap m_backForwardListItemMap;
300     UserInitiatedActionMap m_userInitiatedActionMap;
301
302     HashSet<VisitedLinkStore*> m_visitedLinkStores;
303     HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies;
304
305     int m_numberOfTimesSuddenTerminationWasDisabled;
306     ProcessThrottler m_throttler;
307     ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles;
308 #if PLATFORM(IOS)
309     ForegroundWebProcessToken m_foregroundToken;
310     BackgroundWebProcessToken m_backgroundToken;
311 #endif
312
313     HashMap<String, uint64_t> m_pageURLRetainCountMap;
314
315     enum class NoOrMaybe { No, Maybe } m_isResponsive;
316     Vector<WTF::Function<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks;
317
318     VisibleWebPageCounter m_visiblePageCounter;
319
320     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2. Get rid of this member.
321     Ref<WebsiteDataStore> m_websiteDataStore;
322
323     bool m_isUnderMemoryPressure { false };
324
325 #if PLATFORM(COCOA) && ENABLE(MEDIA_STREAM)
326     std::unique_ptr<UserMediaCaptureManagerProxy> m_userMediaCaptureManagerProxy;
327 #endif
328
329     HashSet<WebCore::MessagePortIdentifier> m_processEntangledPorts;
330     HashMap<uint64_t, CompletionHandler<void()>> m_messageBatchDeliveryCompletionHandlers;
331     HashMap<uint64_t, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>> m_localPortActivityCompletionHandlers;
332 };
333
334 } // namespace WebKit