Drop NetworkCacheStatistics code
[WebKit-https.git] / Source / WebKit / NetworkProcess / cocoa / NetworkProcessCocoa.mm
1 /*
2  * Copyright (C) 2014-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 #import "config.h"
27 #import "NetworkProcess.h"
28
29 #import "CookieStorageUtilsCF.h"
30 #import "Logging.h"
31 #import "NetworkCache.h"
32 #import "NetworkProcessCreationParameters.h"
33 #import "NetworkProximityManager.h"
34 #import "NetworkResourceLoader.h"
35 #import "NetworkSessionCocoa.h"
36 #import "SandboxExtension.h"
37 #import <WebCore/NetworkStorageSession.h>
38 #import <WebCore/PublicSuffix.h>
39 #import <WebCore/ResourceRequestCFNet.h>
40 #import <WebCore/RuntimeApplicationChecks.h>
41 #import <WebCore/SecurityOrigin.h>
42 #import <WebCore/SecurityOriginData.h>
43 #import <pal/spi/cf/CFNetworkSPI.h>
44 #import <wtf/BlockPtr.h>
45 #import <wtf/CallbackAggregator.h>
46 #import <wtf/ProcessPrivilege.h>
47 #import <wtf/RetainPtr.h>
48
49 namespace WebKit {
50
51 static void initializeNetworkSettings()
52 {
53     static const unsigned preferredConnectionCount = 6;
54
55     _CFNetworkHTTPConnectionCacheSetLimit(kHTTPLoadWidth, preferredConnectionCount);
56
57     Boolean keyExistsAndHasValidFormat = false;
58     Boolean prefValue = CFPreferencesGetAppBooleanValue(CFSTR("WebKitEnableHTTPPipelining"), kCFPreferencesCurrentApplication, &keyExistsAndHasValidFormat);
59     if (keyExistsAndHasValidFormat)
60         WebCore::ResourceRequest::setHTTPPipeliningEnabled(prefValue);
61
62     if (WebCore::ResourceRequest::resourcePrioritiesEnabled()) {
63         const unsigned fastLaneConnectionCount = 1;
64
65         _CFNetworkHTTPConnectionCacheSetLimit(kHTTPPriorityNumLevels, toPlatformRequestPriority(WebCore::ResourceLoadPriority::Highest));
66         _CFNetworkHTTPConnectionCacheSetLimit(kHTTPMinimumFastLanePriority, toPlatformRequestPriority(WebCore::ResourceLoadPriority::Medium));
67         _CFNetworkHTTPConnectionCacheSetLimit(kHTTPNumFastLanes, fastLaneConnectionCount);
68     }
69 }
70
71 void NetworkProcess::platformInitializeNetworkProcessCocoa(const NetworkProcessCreationParameters& parameters)
72 {
73     WebCore::setApplicationBundleIdentifier(parameters.uiProcessBundleIdentifier);
74     WebCore::setApplicationSDKVersion(parameters.uiProcessSDKVersion);
75
76 #if PLATFORM(IOS_FAMILY)
77     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
78     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
79     SandboxExtension::consumePermanently(parameters.parentBundleDirectoryExtensionHandle);
80 #if ENABLE(INDEXED_DATABASE)
81     SandboxExtension::consumePermanently(parameters.defaultDataStoreParameters.indexedDatabaseTempBlobDirectoryExtensionHandle);
82 #endif
83 #endif
84     m_diskCacheDirectory = parameters.diskCacheDirectory;
85
86     _CFNetworkSetATSContext(parameters.networkATSContext.get());
87
88     m_uiProcessBundleIdentifier = parameters.uiProcessBundleIdentifier;
89
90 #if PLATFORM(IOS_FAMILY)
91     NetworkSessionCocoa::setCTDataConnectionServiceType(parameters.ctDataConnectionServiceType);
92 #endif
93
94     initializeNetworkSettings();
95
96 #if PLATFORM(MAC)
97     setSharedHTTPCookieStorage(parameters.uiProcessCookieStorageIdentifier);
98 #endif
99
100     WebCore::NetworkStorageSession::setStorageAccessAPIEnabled(parameters.storageAccessAPIEnabled);
101     m_suppressesConnectionTerminationOnSystemChange = parameters.suppressesConnectionTerminationOnSystemChange;
102
103     // FIXME: Most of what this function does for cache size gets immediately overridden by setCacheModel().
104     // - memory cache size passed from UI process is always ignored;
105     // - disk cache size passed from UI process is effectively a minimum size.
106     // One non-obvious constraint is that we need to use -setSharedURLCache: even in testing mode, to prevent creating a default one on disk later, when some other code touches the cache.
107
108     ASSERT(!m_diskCacheIsDisabledForTesting);
109
110     if (m_diskCacheDirectory.isNull())
111         return;
112
113     SandboxExtension::consumePermanently(parameters.diskCacheDirectoryExtensionHandle);
114     OptionSet<NetworkCache::Cache::Option> cacheOptions { NetworkCache::Cache::Option::RegisterNotify };
115     if (parameters.shouldUseTestingNetworkSession)
116         cacheOptions.add(NetworkCache::Cache::Option::TestingMode);
117 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
118     if (parameters.shouldEnableNetworkCacheSpeculativeRevalidation)
119         cacheOptions.add(NetworkCache::Cache::Option::SpeculativeRevalidation);
120 #endif
121
122     m_cache = NetworkCache::Cache::open(*this, m_diskCacheDirectory, cacheOptions);
123     if (!m_cache)
124         RELEASE_LOG_ERROR(NetworkCache, "Failed to initialize the WebKit network disk cache");
125
126     // Disable NSURLCache.
127     auto urlCache(adoptNS([[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]));
128     [NSURLCache setSharedURLCache:urlCache.get()];
129 }
130
131 std::unique_ptr<WebCore::NetworkStorageSession> NetworkProcess::platformCreateDefaultStorageSession() const
132 {
133     return std::make_unique<WebCore::NetworkStorageSession>(PAL::SessionID::defaultSessionID());
134 }
135
136 RetainPtr<CFDataRef> NetworkProcess::sourceApplicationAuditData() const
137 {
138 #if USE(SOURCE_APPLICATION_AUDIT_DATA)
139     ASSERT(parentProcessConnection());
140     if (!parentProcessConnection())
141         return nullptr;
142     Optional<audit_token_t> auditToken = parentProcessConnection()->getAuditToken();
143     if (!auditToken)
144         return nullptr;
145     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&*auditToken, sizeof(*auditToken)));
146 #else
147     return nullptr;
148 #endif
149 }
150
151 static void filterPreloadHSTSEntry(const void* key, const void* value, void* context)
152 {
153     HashSet<String>* hostnames = static_cast<HashSet<String>*>(context);
154     auto val = static_cast<CFDictionaryRef>(value);
155     if (CFDictionaryGetValue(val, _kCFNetworkHSTSPreloaded) != kCFBooleanTrue)
156         hostnames->add((CFStringRef)key);
157 }
158
159 void NetworkProcess::getHostNamesWithHSTSCache(WebCore::NetworkStorageSession& session, HashSet<String>& hostNames)
160 {
161     auto HSTSPolicies = adoptCF(_CFNetworkCopyHSTSPolicies(session.platformSession()));
162     CFDictionaryApplyFunction(HSTSPolicies.get(), filterPreloadHSTSEntry, &hostNames);
163 }
164
165 void NetworkProcess::deleteHSTSCacheForHostNames(WebCore::NetworkStorageSession& session, const Vector<String>& hostNames)
166 {
167     for (auto& hostName : hostNames) {
168         auto url = URL({ }, makeString("https://", hostName));
169         _CFNetworkResetHSTS(url.createCFURL().get(), session.platformSession());
170     }
171 }
172
173 void NetworkProcess::clearHSTSCache(WebCore::NetworkStorageSession& session, WallTime modifiedSince)
174 {
175     NSTimeInterval timeInterval = modifiedSince.secondsSinceEpoch().seconds();
176     NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
177
178     _CFNetworkResetHSTSHostsSinceDate(session.platformSession(), (__bridge CFDateRef)date);
179 }
180
181 void NetworkProcess::clearDiskCache(WallTime modifiedSince, CompletionHandler<void()>&& completionHandler)
182 {
183     if (!m_clearCacheDispatchGroup)
184         m_clearCacheDispatchGroup = dispatch_group_create();
185
186     auto* cache = this->cache();
187     if (!cache) {
188         completionHandler();
189         return;
190     }
191
192     auto group = m_clearCacheDispatchGroup;
193     dispatch_group_async(group, dispatch_get_main_queue(), makeBlockPtr([cache, modifiedSince, completionHandler = WTFMove(completionHandler)] () mutable {
194         cache->clear(modifiedSince, WTFMove(completionHandler));
195     }).get());
196 }
197
198 #if PLATFORM(MAC)
199 void NetworkProcess::setSharedHTTPCookieStorage(const Vector<uint8_t>& identifier)
200 {
201     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
202     [NSHTTPCookieStorage _setSharedHTTPCookieStorage:adoptNS([[NSHTTPCookieStorage alloc] _initWithCFHTTPCookieStorage:cookieStorageFromIdentifyingData(identifier).get()]).get()];
203 }
204 #endif
205
206 void NetworkProcess::setStorageAccessAPIEnabled(bool enabled)
207 {
208     WebCore::NetworkStorageSession::setStorageAccessAPIEnabled(enabled);
209 }
210
211 void NetworkProcess::syncAllCookies()
212 {
213     platformSyncAllCookies([this] {
214         didSyncAllCookies();
215     });
216 }
217
218 #if HAVE(FOUNDATION_WITH_SAVE_COOKIES_WITH_COMPLETION_HANDLER)
219 static void saveCookies(NSHTTPCookieStorage *cookieStorage, CompletionHandler<void()>&& completionHandler)
220 {
221     ASSERT(RunLoop::isMain());
222     [cookieStorage _saveCookies:makeBlockPtr([completionHandler = WTFMove(completionHandler)]() mutable {
223         // CFNetwork may call the completion block on a background queue, so we need to redispatch to the main thread.
224         RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)]() mutable {
225             completionHandler();
226         });
227     }).get()];
228 }
229 #endif
230
231 void NetworkProcess::platformSyncAllCookies(CompletionHandler<void()>&& completionHander) {
232     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
233     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
234
235 #if HAVE(FOUNDATION_WITH_SAVE_COOKIES_WITH_COMPLETION_HANDLER)
236     RefPtr<CallbackAggregator> callbackAggregator = CallbackAggregator::create(WTFMove(completionHander));
237     forEachNetworkStorageSession([&] (auto& networkStorageSession) {
238         saveCookies(networkStorageSession.nsCookieStorage(), [callbackAggregator] { });
239     });
240 #else
241     _CFHTTPCookieStorageFlushCookieStores();
242     completionHander();
243 #endif
244
245     ALLOW_DEPRECATED_DECLARATIONS_END
246 }
247
248 void NetworkProcess::platformPrepareToSuspend(CompletionHandler<void()>&& completionHandler)
249 {
250 #if ENABLE(PROXIMITY_NETWORKING)
251     proximityManager().suspend(SuspensionReason::ProcessSuspending, WTFMove(completionHandler));
252 #else
253     completionHandler();
254 #endif
255 }
256
257 void NetworkProcess::platformProcessDidResume()
258 {
259 #if ENABLE(PROXIMITY_NETWORKING)
260     proximityManager().resume(ResumptionReason::ProcessResuming);
261 #endif
262 }
263
264 void NetworkProcess::platformProcessDidTransitionToBackground()
265 {
266 #if ENABLE(PROXIMITY_NETWORKING)
267     proximityManager().suspend(SuspensionReason::ProcessBackgrounding, [] { });
268 #endif
269 }
270
271 void NetworkProcess::platformProcessDidTransitionToForeground()
272 {
273 #if ENABLE(PROXIMITY_NETWORKING)
274     proximityManager().resume(ResumptionReason::ProcessForegrounding);
275 #endif
276 }
277
278 } // namespace WebKit