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