a0ecc10adbbdbc800c43963932a7fc5d7ae4807d
[WebKit-https.git] / Source / WebKit / NetworkProcess / NetworkProcess.h
1 /*
2  * Copyright (C) 2012-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 "DownloadManager.h"
31 #include "MessageReceiverMap.h"
32 #include <WebCore/DiagnosticLoggingClient.h>
33 #include <memory>
34 #include <pal/SessionID.h>
35 #include <wtf/Forward.h>
36 #include <wtf/Function.h>
37 #include <wtf/MemoryPressureHandler.h>
38 #include <wtf/NeverDestroyed.h>
39 #include <wtf/RetainPtr.h>
40
41 #if PLATFORM(IOS)
42 #include "WebSQLiteDatabaseTracker.h"
43 #endif
44
45 namespace PAL {
46 class SessionID;
47 }
48
49 namespace WebCore {
50 class DownloadID;
51 class CertificateInfo;
52 class NetworkStorageSession;
53 class ProtectionSpace;
54 class SecurityOrigin;
55 struct SecurityOriginData;
56 struct SoupNetworkProxySettings;
57 }
58
59 namespace WebKit {
60 class AuthenticationManager;
61 class NetworkConnectionToWebProcess;
62 class NetworkProcessSupplement;
63 class NetworkResourceLoader;
64 enum class WebsiteDataFetchOption;
65 enum class WebsiteDataType;
66 struct NetworkProcessCreationParameters;
67 struct WebsiteDataStoreParameters;
68
69 namespace NetworkCache {
70 class Cache;
71 }
72
73 class NetworkProcess : public ChildProcess, private DownloadManager::Client {
74     WTF_MAKE_NONCOPYABLE(NetworkProcess);
75     friend class NeverDestroyed<NetworkProcess>;
76     friend class NeverDestroyed<DownloadManager>;
77 public:
78     static NetworkProcess& singleton();
79
80     template <typename T>
81     T* supplement()
82     {
83         return static_cast<T*>(m_supplements.get(T::supplementName()));
84     }
85
86     template <typename T>
87     void addSupplement()
88     {
89         m_supplements.add(T::supplementName(), std::make_unique<T>(this));
90     }
91
92     void removeNetworkConnectionToWebProcess(NetworkConnectionToWebProcess*);
93
94     AuthenticationManager& authenticationManager();
95     DownloadManager& downloadManager();
96
97     NetworkCache::Cache* cache() { return m_cache.get(); }
98
99     bool canHandleHTTPSServerTrustEvaluation() const { return m_canHandleHTTPSServerTrustEvaluation; }
100
101     void processWillSuspendImminently(bool& handled);
102     void prepareToSuspend();
103     void cancelPrepareToSuspend();
104     void processDidResume();
105
106     // Diagnostic messages logging.
107     void logDiagnosticMessage(uint64_t webPageID, const String& message, const String& description, WebCore::ShouldSample);
108     void logDiagnosticMessageWithResult(uint64_t webPageID, const String& message, const String& description, WebCore::DiagnosticLoggingResultType, WebCore::ShouldSample);
109     void logDiagnosticMessageWithValue(uint64_t webPageID, const String& message, const String& description, double value, unsigned significantFigures, WebCore::ShouldSample);
110
111 #if PLATFORM(COCOA)
112     RetainPtr<CFDataRef> sourceApplicationAuditData() const;
113     void clearHSTSCache(WebCore::NetworkStorageSession&, std::chrono::system_clock::time_point modifiedSince);
114 #endif
115
116 #if USE(NETWORK_SESSION)
117     void findPendingDownloadLocation(NetworkDataTask&, ResponseCompletionHandler&&, const WebCore::ResourceResponse&);
118 #endif
119
120 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
121     void canAuthenticateAgainstProtectionSpace(NetworkResourceLoader&, const WebCore::ProtectionSpace&);
122 #endif
123
124     void prefetchDNS(const String&);
125
126     void ensurePrivateBrowsingSession(WebsiteDataStoreParameters&&);
127
128     void grantSandboxExtensionsToStorageProcessForBlobs(const Vector<String>& filenames, Function<void ()>&& completionHandler);
129
130 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
131     void updateCookiePartitioningForTopPrivatelyOwnedDomains(const Vector<String>& domainsToRemove, const Vector<String>& domainsToAdd, bool shouldClearFirst);
132 #endif
133
134     Seconds loadThrottleLatency() const { return m_loadThrottleLatency; }
135
136 private:
137     NetworkProcess();
138     ~NetworkProcess();
139
140     void platformInitializeNetworkProcess(const NetworkProcessCreationParameters&);
141
142     void terminate() override;
143     void platformTerminate();
144
145     void lowMemoryHandler(Critical);
146
147     enum class ShouldAcknowledgeWhenReadyToSuspend { No, Yes };
148     void actualPrepareToSuspend(ShouldAcknowledgeWhenReadyToSuspend);
149
150     // ChildProcess
151     void initializeProcess(const ChildProcessInitializationParameters&) override;
152     void initializeProcessName(const ChildProcessInitializationParameters&) override;
153     void initializeSandbox(const ChildProcessInitializationParameters&, SandboxInitializationParameters&) override;
154     void initializeConnection(IPC::Connection*) override;
155     bool shouldTerminate() override;
156
157     // IPC::Connection::Client
158     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
159     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
160     void didClose(IPC::Connection&) override;
161
162     // DownloadManager::Client
163     void didCreateDownload() override;
164     void didDestroyDownload() override;
165     IPC::Connection* downloadProxyConnection() override;
166     AuthenticationManager& downloadsAuthenticationManager() override;
167 #if USE(NETWORK_SESSION)
168     void pendingDownloadCanceled(DownloadID) override;
169 #endif
170
171     // Message Handlers
172     void didReceiveNetworkProcessMessage(IPC::Connection&, IPC::Decoder&);
173     void didReceiveSyncNetworkProcessMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
174     void initializeNetworkProcess(NetworkProcessCreationParameters&&);
175     void createNetworkConnectionToWebProcess();
176     void addWebsiteDataStore(WebsiteDataStoreParameters&&);
177     void destroySession(PAL::SessionID);
178
179     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, OptionSet<WebsiteDataFetchOption>, uint64_t callbackID);
180     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, std::chrono::system_clock::time_point modifiedSince, uint64_t callbackID);
181     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>& origins, const Vector<String>& cookieHostNames, uint64_t callbackID);
182
183     void clearCachedCredentials();
184
185     // FIXME: This should take a session ID so we can identify which disk cache to delete.
186     void clearDiskCache(std::chrono::system_clock::time_point modifiedSince, Function<void ()>&& completionHandler);
187
188     void downloadRequest(PAL::SessionID, DownloadID, const WebCore::ResourceRequest&, const String& suggestedFilename);
189     void resumeDownload(PAL::SessionID, DownloadID, const IPC::DataReference& resumeData, const String& path, const SandboxExtension::Handle&);
190     void cancelDownload(DownloadID);
191 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
192     void continueCanAuthenticateAgainstProtectionSpace(uint64_t resourceLoadIdentifier, bool canAuthenticate);
193 #endif
194 #if USE(NETWORK_SESSION)
195 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
196     void continueCanAuthenticateAgainstProtectionSpaceDownload(DownloadID, bool canAuthenticate);
197 #endif
198     void continueWillSendRequest(DownloadID, WebCore::ResourceRequest&&);
199 #endif
200     void continueDecidePendingDownloadDestination(DownloadID, String destination, const SandboxExtension::Handle& sandboxExtensionHandle, bool allowOverwrite);
201
202     void setCacheModel(uint32_t);
203     void allowSpecificHTTPSCertificateForHost(const WebCore::CertificateInfo&, const String& host);
204     void setCanHandleHTTPSServerTrustEvaluation(bool);
205     void getNetworkProcessStatistics(uint64_t callbackID);
206     void clearCacheForAllOrigins(uint32_t cachesToClear);
207     void setAllowsAnySSLCertificateForWebSocket(bool);
208     void syncAllCookies();
209
210     void didGrantSandboxExtensionsToStorageProcessForBlobs(uint64_t requestID);
211
212 #if USE(SOUP)
213     void setIgnoreTLSErrors(bool);
214     void userPreferredLanguagesChanged(const Vector<String>&);
215     void setNetworkProxySettings(const WebCore::SoupNetworkProxySettings&);
216 #endif
217
218     // Platform Helpers
219     void platformSetURLCacheSize(unsigned urlCacheMemoryCapacity, uint64_t urlCacheDiskCapacity);
220
221     // Connections to WebProcesses.
222     Vector<RefPtr<NetworkConnectionToWebProcess>> m_webProcessConnections;
223
224     String m_diskCacheDirectory;
225     bool m_hasSetCacheModel;
226     CacheModel m_cacheModel;
227     int64_t m_diskCacheSizeOverride { -1 };
228     bool m_suppressMemoryPressureHandler { false };
229     bool m_diskCacheIsDisabledForTesting;
230     bool m_canHandleHTTPSServerTrustEvaluation;
231     Seconds m_loadThrottleLatency;
232
233     RefPtr<NetworkCache::Cache> m_cache;
234
235     typedef HashMap<const char*, std::unique_ptr<NetworkProcessSupplement>, PtrHash<const char*>> NetworkProcessSupplementMap;
236     NetworkProcessSupplementMap m_supplements;
237
238     HashMap<uint64_t, Function<void ()>> m_sandboxExtensionForBlobsCompletionHandlers;
239     HashMap<uint64_t, Ref<NetworkResourceLoader>> m_waitingNetworkResourceLoaders;
240
241 #if PLATFORM(COCOA)
242     void platformInitializeNetworkProcessCocoa(const NetworkProcessCreationParameters&);
243     void setCookieStoragePartitioningEnabled(bool);
244
245     // FIXME: We'd like to be able to do this without the #ifdef, but WorkQueue + BinarySemaphore isn't good enough since
246     // multiple requests to clear the cache can come in before previous requests complete, and we need to wait for all of them.
247     // In the future using WorkQueue and a counting semaphore would work, as would WorkQueue supporting the libdispatch concept of "work groups".
248     dispatch_group_t m_clearCacheDispatchGroup;
249 #endif
250
251 #if PLATFORM(IOS)
252     WebSQLiteDatabaseTracker m_webSQLiteDatabaseTracker;
253 #endif
254 };
255
256 } // namespace WebKit