Process swapping on navigation needs to handle server redirects.
[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     void didCommitProvisionalLoad() { m_hasCommittedAnyProvisionalLoads = true; }
209     bool hasCommittedAnyProvisionalLoads() const { return m_hasCommittedAnyProvisionalLoads; }
210
211 protected:
212     static uint64_t generatePageID();
213     WebProcessProxy(WebProcessPool&, WebsiteDataStore&);
214
215     // ChildProcessProxy
216     void getLaunchOptions(ProcessLauncher::LaunchOptions&) override;
217     void connectionWillOpen(IPC::Connection&) override;
218     void processWillShutDown(IPC::Connection&) override;
219
220 private:
221     // Called when the web process has crashed or we know that it will terminate soon.
222     // Will potentially cause the WebProcessProxy object to be freed.
223     void shutDown();
224
225     // IPC message handlers.
226     void addOrUpdateBackForwardItem(uint64_t itemID, uint64_t pageID, const PageState&);
227     void didDestroyFrame(uint64_t);
228     void didDestroyUserGestureToken(uint64_t);
229
230     void shouldTerminate(bool& shouldTerminate);
231
232     void createNewMessagePortChannel(const WebCore::MessagePortIdentifier& port1, const WebCore::MessagePortIdentifier& port2);
233     void entangleLocalPortInThisProcessToRemote(const WebCore::MessagePortIdentifier& local, const WebCore::MessagePortIdentifier& remote);
234     void messagePortDisentangled(const WebCore::MessagePortIdentifier&);
235     void messagePortClosed(const WebCore::MessagePortIdentifier&);
236     void takeAllMessagesForPort(const WebCore::MessagePortIdentifier&, uint64_t messagesCallbackIdentifier);
237     void postMessageToRemote(WebCore::MessageWithMessagePorts&&, const WebCore::MessagePortIdentifier&);
238     void checkRemotePortForActivity(const WebCore::MessagePortIdentifier, uint64_t callbackIdentifier);
239     void didDeliverMessagePortMessages(uint64_t messageBatchIdentifier);
240     void didCheckProcessLocalPortForActivity(uint64_t callbackIdentifier, bool isLocallyReachable);
241
242     // Plugins
243 #if ENABLE(NETSCAPE_PLUGIN_API)
244     void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins, Vector<WebCore::PluginInfo>& applicationPlugins, std::optional<Vector<WebCore::SupportedPluginName>>&);
245 #endif // ENABLE(NETSCAPE_PLUGIN_API)
246 #if ENABLE(NETSCAPE_PLUGIN_API)
247     void getPluginProcessConnection(uint64_t pluginProcessToken, Ref<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>&&);
248 #endif
249     void getNetworkProcessConnection(Ref<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>&&);
250     void getStorageProcessConnection(PAL::SessionID initialSessionID, Ref<Messages::WebProcessProxy::GetStorageProcessConnection::DelayedReply>&&);
251
252     bool platformIsBeingDebugged() const;
253     bool shouldAllowNonValidInjectedCode() const;
254
255     static const HashSet<String>& platformPathsWithAssumedReadAccess();
256
257     void updateBackgroundResponsivenessTimer();
258
259     // IPC::Connection::Client
260     friend class WebConnectionToWebProcess;
261     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
262     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
263     void didClose(IPC::Connection&) override;
264     void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override;
265
266     // ResponsivenessTimer::Client
267     void didBecomeUnresponsive() override;
268     void didBecomeResponsive() override;
269     void willChangeIsResponsive() override;
270     void didChangeIsResponsive() override;
271     bool mayBecomeUnresponsive() override;
272
273     // ProcessThrottlerClient
274     void sendProcessWillSuspendImminently() override;
275     void sendPrepareToSuspend() override;
276     void sendCancelPrepareToSuspend() override;
277     void sendProcessDidResume() override;
278     void didSetAssertionState(AssertionState) override;
279
280     // ProcessLauncher::Client
281     void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override;
282
283     // Implemented in generated WebProcessProxyMessageReceiver.cpp
284     void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&);
285     void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
286
287     bool canTerminateChildProcess();
288
289     void logDiagnosticMessageForResourceLimitTermination(const String& limitKey);
290
291     ResponsivenessTimer m_responsivenessTimer;
292     BackgroundProcessResponsivenessTimer m_backgroundResponsivenessTimer;
293     
294     RefPtr<WebConnectionToWebProcess> m_webConnection;
295     Ref<WebProcessPool> m_processPool;
296
297     bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it.
298     HashSet<String> m_localPathsWithAssumedReadAccess;
299
300     WebPageProxyMap m_pageMap;
301     WebFrameProxyMap m_frameMap;
302     WebBackForwardListItemMap m_backForwardListItemMap;
303     UserInitiatedActionMap m_userInitiatedActionMap;
304
305     HashSet<VisitedLinkStore*> m_visitedLinkStores;
306     HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies;
307
308     int m_numberOfTimesSuddenTerminationWasDisabled;
309     ProcessThrottler m_throttler;
310     ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles;
311 #if PLATFORM(IOS)
312     ForegroundWebProcessToken m_foregroundToken;
313     BackgroundWebProcessToken m_backgroundToken;
314 #endif
315
316     HashMap<String, uint64_t> m_pageURLRetainCountMap;
317
318     enum class NoOrMaybe { No, Maybe } m_isResponsive;
319     Vector<WTF::Function<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks;
320
321     VisibleWebPageCounter m_visiblePageCounter;
322
323     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2. Get rid of this member.
324     Ref<WebsiteDataStore> m_websiteDataStore;
325
326     bool m_isUnderMemoryPressure { false };
327
328 #if PLATFORM(COCOA) && ENABLE(MEDIA_STREAM)
329     std::unique_ptr<UserMediaCaptureManagerProxy> m_userMediaCaptureManagerProxy;
330 #endif
331
332     HashSet<WebCore::MessagePortIdentifier> m_processEntangledPorts;
333     HashMap<uint64_t, Function<void()>> m_messageBatchDeliveryCompletionHandlers;
334     HashMap<uint64_t, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>> m_localPortActivityCompletionHandlers;
335
336     bool m_hasCommittedAnyProvisionalLoads { false };
337 };
338
339 } // namespace WebKit