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