c306cce43061c4519e2555bdd4f498262f3a1551
[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.shouldEnableNetworkCacheEfficacyLogging)
116         cacheOptions.add(NetworkCache::Cache::Option::EfficacyLogging);
117     if (parameters.shouldUseTestingNetworkSession)
118         cacheOptions.add(NetworkCache::Cache::Option::TestingMode);
119 #if ENABLE(NETWORK_CACHE_SPECULATIVE_REVALIDATION)
120     if (parameters.shouldEnableNetworkCacheSpeculativeRevalidation)
121         cacheOptions.add(NetworkCache::Cache::Option::SpeculativeRevalidation);
122 #endif
123
124     m_cache = NetworkCache::Cache::open(*this, m_diskCacheDirectory, cacheOptions);
125     if (!m_cache)
126         RELEASE_LOG_ERROR(NetworkCache, "Failed to initialize the WebKit network disk cache");
127
128     // Disable NSURLCache.
129     auto urlCache(adoptNS([[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]));
130     [NSURLCache setSharedURLCache:urlCache.get()];
131 }
132
133 std::unique_ptr<WebCore::NetworkStorageSession> NetworkProcess::platformCreateDefaultStorageSession() const
134 {
135     return std::make_unique<WebCore::NetworkStorageSession>(PAL::SessionID::defaultSessionID());
136 }
137
138 RetainPtr<CFDataRef> NetworkProcess::sourceApplicationAuditData() const
139 {
140 #if USE(SOURCE_APPLICATION_AUDIT_DATA)
141     ASSERT(parentProcessConnection());
142     if (!parentProcessConnection())
143         return nullptr;
144     Optional<audit_token_t> auditToken = parentProcessConnection()->getAuditToken();
145     if (!auditToken)
146         return nullptr;
147     return adoptCF(CFDataCreate(nullptr, (const UInt8*)&*auditToken, sizeof(*auditToken)));
148 #else
149     return nullptr;
150 #endif
151 }
152
153 static void filterPreloadHSTSEntry(const void* key, const void* value, void* context)
154 {
155     HashSet<String>* hostnames = static_cast<HashSet<String>*>(context);
156     auto val = static_cast<CFDictionaryRef>(value);
157     if (CFDictionaryGetValue(val, _kCFNetworkHSTSPreloaded) != kCFBooleanTrue)
158         hostnames->add((CFStringRef)key);
159 }
160
161 void NetworkProcess::getHostNamesWithHSTSCache(WebCore::NetworkStorageSession& session, HashSet<String>& hostNames)
162 {
163     auto HSTSPolicies = adoptCF(_CFNetworkCopyHSTSPolicies(session.platformSession()));
164     CFDictionaryApplyFunction(HSTSPolicies.get(), filterPreloadHSTSEntry, &hostNames);
165 }
166
167 void NetworkProcess::deleteHSTSCacheForHostNames(WebCore::NetworkStorageSession& session, const Vector<String>& hostNames)
168 {
169     for (auto& hostName : hostNames) {
170         auto url = URL({ }, makeString("https://", hostName));
171         _CFNetworkResetHSTS(url.createCFURL().get(), session.platformSession());
172     }
173 }
174
175 void NetworkProcess::clearHSTSCache(WebCore::NetworkStorageSession& session, WallTime modifiedSince)
176 {
177     NSTimeInterval timeInterval = modifiedSince.secondsSinceEpoch().seconds();
178     NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
179
180     _CFNetworkResetHSTSHostsSinceDate(session.platformSession(), (__bridge CFDateRef)date);
181 }
182
183 void NetworkProcess::clearDiskCache(WallTime modifiedSince, CompletionHandler<void()>&& completionHandler)
184 {
185     if (!m_clearCacheDispatchGroup)
186         m_clearCacheDispatchGroup = dispatch_group_create();
187
188     auto* cache = this->cache();
189     if (!cache) {
190         completionHandler();
191         return;
192     }
193
194     auto group = m_clearCacheDispatchGroup;
195     dispatch_group_async(group, dispatch_get_main_queue(), makeBlockPtr([cache, modifiedSince, completionHandler = WTFMove(completionHandler)] () mutable {
196         cache->clear(modifiedSince, WTFMove(completionHandler));
197     }).get());
198 }
199
200 #if PLATFORM(MAC)
201 void NetworkProcess::setSharedHTTPCookieStorage(const Vector<uint8_t>& identifier)
202 {
203     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
204     [NSHTTPCookieStorage _setSharedHTTPCookieStorage:adoptNS([[NSHTTPCookieStorage alloc] _initWithCFHTTPCookieStorage:cookieStorageFromIdentifyingData(identifier).get()]).get()];
205 }
206 #endif
207
208 void NetworkProcess::setStorageAccessAPIEnabled(bool enabled)
209 {
210     WebCore::NetworkStorageSession::setStorageAccessAPIEnabled(enabled);
211 }
212
213 void NetworkProcess::syncAllCookies()
214 {
215     platformSyncAllCookies([this] {
216         didSyncAllCookies();
217     });
218 }
219
220 #if HAVE(FOUNDATION_WITH_SAVE_COOKIES_WITH_COMPLETION_HANDLER)
221 static void saveCookies(NSHTTPCookieStorage *cookieStorage, CompletionHandler<void()>&& completionHandler)
222 {
223     ASSERT(RunLoop::isMain());
224     [cookieStorage _saveCookies:makeBlockPtr([completionHandler = WTFMove(completionHandler)]() mutable {
225         // CFNetwork may call the completion block on a background queue, so we need to redispatch to the main thread.
226         RunLoop::main().dispatch([completionHandler = WTFMove(completionHandler)]() mutable {
227             completionHandler();
228         });
229     }).get()];
230 }
231 #endif
232
233 void NetworkProcess::platformSyncAllCookies(CompletionHandler<void()>&& completionHander) {
234     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
235     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
236
237 #if HAVE(FOUNDATION_WITH_SAVE_COOKIES_WITH_COMPLETION_HANDLER)
238     RefPtr<CallbackAggregator> callbackAggregator = CallbackAggregator::create(WTFMove(completionHander));
239     forEachNetworkStorageSession([&] (auto& networkStorageSession) {
240         saveCookies(networkStorageSession.nsCookieStorage(), [callbackAggregator] { });
241     });
242 #else
243     _CFHTTPCookieStorageFlushCookieStores();
244     completionHander();
245 #endif
246
247     ALLOW_DEPRECATED_DECLARATIONS_END
248 }
249
250 void NetworkProcess::platformPrepareToSuspend(CompletionHandler<void()>&& completionHandler)
251 {
252 #if ENABLE(PROXIMITY_NETWORKING)
253     proximityManager().suspend(SuspensionReason::ProcessSuspending, WTFMove(completionHandler));
254 #else
255     completionHandler();
256 #endif
257 }
258
259 void NetworkProcess::platformProcessDidResume()
260 {
261 #if ENABLE(PROXIMITY_NETWORKING)
262     proximityManager().resume(ResumptionReason::ProcessResuming);
263 #endif
264 }
265
266 void NetworkProcess::platformProcessDidTransitionToBackground()
267 {
268 #if ENABLE(PROXIMITY_NETWORKING)
269     proximityManager().suspend(SuspensionReason::ProcessBackgrounding, [] { });
270 #endif
271 }
272
273 void NetworkProcess::platformProcessDidTransitionToForeground()
274 {
275 #if ENABLE(PROXIMITY_NETWORKING)
276     proximityManager().resume(ResumptionReason::ProcessForegrounding);
277 #endif
278 }
279
280 } // namespace WebKit