Remove unused WebProcessPool::setCanHandleHTTPSServerTrustEvaluation
[WebKit-https.git] / Source / WebKit / NetworkProcess / cocoa / NetworkSessionCocoa.mm
1 /*
2  * Copyright (C) 2015-2019 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 "NetworkSessionCocoa.h"
28
29 #import "AuthenticationChallengeDisposition.h"
30 #import "AuthenticationManager.h"
31 #import "DataReference.h"
32 #import "Download.h"
33 #import "LegacyCustomProtocolManager.h"
34 #import "Logging.h"
35 #import "NetworkLoad.h"
36 #import "NetworkProcess.h"
37 #import "NetworkSessionCreationParameters.h"
38 #import "WebSocketTask.h"
39 #import <Foundation/NSURLSession.h>
40 #import <WebCore/Credential.h>
41 #import <WebCore/FormDataStreamMac.h>
42 #import <WebCore/FrameLoaderTypes.h>
43 #import <WebCore/NetworkStorageSession.h>
44 #import <WebCore/NotImplemented.h>
45 #import <WebCore/ResourceError.h>
46 #import <WebCore/ResourceRequest.h>
47 #import <WebCore/ResourceResponse.h>
48 #import <WebCore/SharedBuffer.h>
49 #import <WebCore/WebCoreURLResponse.h>
50 #import <pal/spi/cf/CFNetworkSPI.h>
51 #import <wtf/MainThread.h>
52 #import <wtf/NeverDestroyed.h>
53 #import <wtf/ObjCRuntimeExtras.h>
54 #import <wtf/ProcessPrivilege.h>
55 #import <wtf/SoftLinking.h>
56 #import <wtf/URL.h>
57 #import <wtf/text/WTFString.h>
58
59 #if USE(APPLE_INTERNAL_SDK)
60 #include <WebKitAdditions/NetworkSessionCocoaAdditions.h>
61 #endif
62
63 #import "DeviceManagementSoftLink.h"
64
65 using namespace WebKit;
66
67 CFStringRef const WebKit2HTTPProxyDefaultsKey = static_cast<CFStringRef>(@"WebKit2HTTPProxy");
68 CFStringRef const WebKit2HTTPSProxyDefaultsKey = static_cast<CFStringRef>(@"WebKit2HTTPSProxy");
69
70 constexpr unsigned maxNumberOfIsolatedSessions { 10 };
71
72 static NSURLSessionResponseDisposition toNSURLSessionResponseDisposition(WebCore::PolicyAction disposition)
73 {
74     switch (disposition) {
75     case WebCore::PolicyAction::StopAllLoads:
76         ASSERT_NOT_REACHED();
77 #if ASSERT_DISABLED
78         FALLTHROUGH;
79 #endif
80     case WebCore::PolicyAction::Ignore:
81         return NSURLSessionResponseCancel;
82     case WebCore::PolicyAction::Use:
83         return NSURLSessionResponseAllow;
84     case WebCore::PolicyAction::Download:
85         return NSURLSessionResponseBecomeDownload;
86     }
87 }
88
89 static NSURLSessionAuthChallengeDisposition toNSURLSessionAuthChallengeDisposition(WebKit::AuthenticationChallengeDisposition disposition)
90 {
91     switch (disposition) {
92     case WebKit::AuthenticationChallengeDisposition::UseCredential:
93         return NSURLSessionAuthChallengeUseCredential;
94     case WebKit::AuthenticationChallengeDisposition::PerformDefaultHandling:
95         return NSURLSessionAuthChallengePerformDefaultHandling;
96     case WebKit::AuthenticationChallengeDisposition::Cancel:
97         return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
98     case WebKit::AuthenticationChallengeDisposition::RejectProtectionSpaceAndContinue:
99         return NSURLSessionAuthChallengeRejectProtectionSpace;
100     }
101 }
102
103 static WebCore::NetworkLoadPriority toNetworkLoadPriority(float priority)
104 {
105     if (priority <= NSURLSessionTaskPriorityLow)
106         return WebCore::NetworkLoadPriority::Low;
107     if (priority >= NSURLSessionTaskPriorityHigh)
108         return WebCore::NetworkLoadPriority::High;
109     return WebCore::NetworkLoadPriority::Medium;
110 }
111
112 #if HAVE(CFNETWORK_NEGOTIATED_SSL_PROTOCOL_CIPHER)
113 static String stringForSSLProtocol(SSLProtocol protocol)
114 {
115     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
116     switch (protocol) {
117     case kDTLSProtocol1:
118         return "DTLS 1.0"_s;
119     case kSSLProtocol2:
120         return "SSL 2.0"_s;
121     case kSSLProtocol3:
122         return "SSL 3.0"_s;
123     case kSSLProtocol3Only:
124         return "SSL 3.0 (Only)"_s;
125     case kTLSProtocol1:
126         return "TLS 1.0"_s;
127     case kTLSProtocol1Only:
128         return "TLS 1.0 (Only)"_s;
129     case kTLSProtocol11:
130         return "TLS 1.1"_s;
131     case kTLSProtocol12:
132         return "TLS 1.2"_s;
133     case kTLSProtocol13:
134         return "TLS 1.3"_s;
135     case kSSLProtocolAll:
136         return "All";
137     case kSSLProtocolUnknown:
138         return "Unknown";
139     case kTLSProtocolMaxSupported:
140     default:
141         ASSERT_NOT_REACHED();
142         return emptyString();
143     }
144     ALLOW_DEPRECATED_DECLARATIONS_END
145 }
146
147 static String stringForSSLCipher(SSLCipherSuite cipher)
148 {
149 #define STRINGIFY_CIPHER(cipher) \
150     case cipher: \
151         return "" #cipher ""_s
152
153     switch (cipher) {
154     STRINGIFY_CIPHER(SSL_RSA_EXPORT_WITH_RC4_40_MD5);
155     STRINGIFY_CIPHER(SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5);
156     STRINGIFY_CIPHER(SSL_RSA_WITH_IDEA_CBC_SHA);
157     STRINGIFY_CIPHER(SSL_RSA_EXPORT_WITH_DES40_CBC_SHA);
158     STRINGIFY_CIPHER(SSL_RSA_WITH_DES_CBC_SHA);
159     STRINGIFY_CIPHER(SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA);
160     STRINGIFY_CIPHER(SSL_DH_DSS_WITH_DES_CBC_SHA);
161     STRINGIFY_CIPHER(SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA);
162     STRINGIFY_CIPHER(SSL_DH_RSA_WITH_DES_CBC_SHA);
163     STRINGIFY_CIPHER(SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA);
164     STRINGIFY_CIPHER(SSL_DHE_DSS_WITH_DES_CBC_SHA);
165     STRINGIFY_CIPHER(SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA);
166     STRINGIFY_CIPHER(SSL_DHE_RSA_WITH_DES_CBC_SHA);
167     STRINGIFY_CIPHER(SSL_DH_anon_EXPORT_WITH_RC4_40_MD5);
168     STRINGIFY_CIPHER(SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA);
169     STRINGIFY_CIPHER(SSL_DH_anon_WITH_DES_CBC_SHA);
170     STRINGIFY_CIPHER(SSL_FORTEZZA_DMS_WITH_NULL_SHA);
171     STRINGIFY_CIPHER(SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA);
172     STRINGIFY_CIPHER(TLS_RSA_WITH_AES_128_CBC_SHA);
173     STRINGIFY_CIPHER(TLS_DH_DSS_WITH_AES_128_CBC_SHA);
174     STRINGIFY_CIPHER(TLS_DH_RSA_WITH_AES_128_CBC_SHA);
175     STRINGIFY_CIPHER(TLS_DHE_DSS_WITH_AES_128_CBC_SHA);
176     STRINGIFY_CIPHER(TLS_DHE_RSA_WITH_AES_128_CBC_SHA);
177     STRINGIFY_CIPHER(TLS_DH_anon_WITH_AES_128_CBC_SHA);
178     STRINGIFY_CIPHER(TLS_RSA_WITH_AES_256_CBC_SHA);
179     STRINGIFY_CIPHER(TLS_DH_DSS_WITH_AES_256_CBC_SHA);
180     STRINGIFY_CIPHER(TLS_DH_RSA_WITH_AES_256_CBC_SHA);
181     STRINGIFY_CIPHER(TLS_DHE_DSS_WITH_AES_256_CBC_SHA);
182     STRINGIFY_CIPHER(TLS_DHE_RSA_WITH_AES_256_CBC_SHA);
183     STRINGIFY_CIPHER(TLS_DH_anon_WITH_AES_256_CBC_SHA);
184     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_NULL_SHA);
185     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_RC4_128_SHA);
186     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA);
187     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA);
188     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA);
189     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_NULL_SHA);
190     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA);
191     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA);
192     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
193     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
194     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_NULL_SHA);
195     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_RC4_128_SHA);
196     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA);
197     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA);
198     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA);
199     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_NULL_SHA);
200     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_RC4_128_SHA);
201     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA);
202     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
203     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
204     STRINGIFY_CIPHER(TLS_ECDH_anon_WITH_NULL_SHA);
205     STRINGIFY_CIPHER(TLS_ECDH_anon_WITH_RC4_128_SHA);
206     STRINGIFY_CIPHER(TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA);
207     STRINGIFY_CIPHER(TLS_ECDH_anon_WITH_AES_128_CBC_SHA);
208     STRINGIFY_CIPHER(TLS_ECDH_anon_WITH_AES_256_CBC_SHA);
209     // STRINGIFY_CIPHER(SSL_NULL_WITH_NULL_NULL);
210     STRINGIFY_CIPHER(TLS_NULL_WITH_NULL_NULL);
211     // STRINGIFY_CIPHER(SSL_RSA_WITH_NULL_MD5);
212     STRINGIFY_CIPHER(TLS_RSA_WITH_NULL_MD5);
213     // STRINGIFY_CIPHER(SSL_RSA_WITH_NULL_SHA);
214     STRINGIFY_CIPHER(TLS_RSA_WITH_NULL_SHA);
215     // STRINGIFY_CIPHER(SSL_RSA_WITH_RC4_128_MD5);
216     STRINGIFY_CIPHER(TLS_RSA_WITH_RC4_128_MD5);
217     // STRINGIFY_CIPHER(SSL_RSA_WITH_RC4_128_SHA);
218     STRINGIFY_CIPHER(TLS_RSA_WITH_RC4_128_SHA);
219     // STRINGIFY_CIPHER(SSL_RSA_WITH_3DES_EDE_CBC_SHA);
220     STRINGIFY_CIPHER(TLS_RSA_WITH_3DES_EDE_CBC_SHA);
221     STRINGIFY_CIPHER(TLS_RSA_WITH_NULL_SHA256);
222     STRINGIFY_CIPHER(TLS_RSA_WITH_AES_128_CBC_SHA256);
223     STRINGIFY_CIPHER(TLS_RSA_WITH_AES_256_CBC_SHA256);
224     // STRINGIFY_CIPHER(SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA);
225     STRINGIFY_CIPHER(TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA);
226     // STRINGIFY_CIPHER(SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA);
227     STRINGIFY_CIPHER(TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA);
228     // STRINGIFY_CIPHER(SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA);
229     STRINGIFY_CIPHER(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA);
230     // STRINGIFY_CIPHER(SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA);
231     STRINGIFY_CIPHER(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA);
232     STRINGIFY_CIPHER(TLS_DH_DSS_WITH_AES_128_CBC_SHA256);
233     STRINGIFY_CIPHER(TLS_DH_RSA_WITH_AES_128_CBC_SHA256);
234     STRINGIFY_CIPHER(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256);
235     STRINGIFY_CIPHER(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256);
236     STRINGIFY_CIPHER(TLS_DH_DSS_WITH_AES_256_CBC_SHA256);
237     STRINGIFY_CIPHER(TLS_DH_RSA_WITH_AES_256_CBC_SHA256);
238     STRINGIFY_CIPHER(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256);
239     STRINGIFY_CIPHER(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256);
240     // STRINGIFY_CIPHER(SSL_DH_anon_WITH_RC4_128_MD5);
241     STRINGIFY_CIPHER(TLS_DH_anon_WITH_RC4_128_MD5);
242     // STRINGIFY_CIPHER(SSL_DH_anon_WITH_3DES_EDE_CBC_SHA);
243     STRINGIFY_CIPHER(TLS_DH_anon_WITH_3DES_EDE_CBC_SHA);
244     STRINGIFY_CIPHER(TLS_DH_anon_WITH_AES_128_CBC_SHA256);
245     STRINGIFY_CIPHER(TLS_DH_anon_WITH_AES_256_CBC_SHA256);
246     STRINGIFY_CIPHER(TLS_PSK_WITH_RC4_128_SHA);
247     STRINGIFY_CIPHER(TLS_PSK_WITH_3DES_EDE_CBC_SHA);
248     STRINGIFY_CIPHER(TLS_PSK_WITH_AES_128_CBC_SHA);
249     STRINGIFY_CIPHER(TLS_PSK_WITH_AES_256_CBC_SHA);
250     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_RC4_128_SHA);
251     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA);
252     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_AES_128_CBC_SHA);
253     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_AES_256_CBC_SHA);
254     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_RC4_128_SHA);
255     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA);
256     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_AES_128_CBC_SHA);
257     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_AES_256_CBC_SHA);
258     STRINGIFY_CIPHER(TLS_PSK_WITH_NULL_SHA);
259     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_NULL_SHA);
260     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_NULL_SHA);
261     STRINGIFY_CIPHER(TLS_RSA_WITH_AES_128_GCM_SHA256);
262     STRINGIFY_CIPHER(TLS_RSA_WITH_AES_256_GCM_SHA384);
263     STRINGIFY_CIPHER(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256);
264     STRINGIFY_CIPHER(TLS_DHE_RSA_WITH_AES_256_GCM_SHA384);
265     STRINGIFY_CIPHER(TLS_DH_RSA_WITH_AES_128_GCM_SHA256);
266     STRINGIFY_CIPHER(TLS_DH_RSA_WITH_AES_256_GCM_SHA384);
267     STRINGIFY_CIPHER(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256);
268     STRINGIFY_CIPHER(TLS_DHE_DSS_WITH_AES_256_GCM_SHA384);
269     STRINGIFY_CIPHER(TLS_DH_DSS_WITH_AES_128_GCM_SHA256);
270     STRINGIFY_CIPHER(TLS_DH_DSS_WITH_AES_256_GCM_SHA384);
271     STRINGIFY_CIPHER(TLS_DH_anon_WITH_AES_128_GCM_SHA256);
272     STRINGIFY_CIPHER(TLS_DH_anon_WITH_AES_256_GCM_SHA384);
273     STRINGIFY_CIPHER(TLS_PSK_WITH_AES_128_GCM_SHA256);
274     STRINGIFY_CIPHER(TLS_PSK_WITH_AES_256_GCM_SHA384);
275     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_AES_128_GCM_SHA256);
276     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_AES_256_GCM_SHA384);
277     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_AES_128_GCM_SHA256);
278     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_AES_256_GCM_SHA384);
279     STRINGIFY_CIPHER(TLS_PSK_WITH_AES_128_CBC_SHA256);
280     STRINGIFY_CIPHER(TLS_PSK_WITH_AES_256_CBC_SHA384);
281     STRINGIFY_CIPHER(TLS_PSK_WITH_NULL_SHA256);
282     STRINGIFY_CIPHER(TLS_PSK_WITH_NULL_SHA384);
283     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_AES_128_CBC_SHA256);
284     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_AES_256_CBC_SHA384);
285     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_NULL_SHA256);
286     STRINGIFY_CIPHER(TLS_DHE_PSK_WITH_NULL_SHA384);
287     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_AES_128_CBC_SHA256);
288     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_AES_256_CBC_SHA384);
289     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_NULL_SHA256);
290     STRINGIFY_CIPHER(TLS_RSA_PSK_WITH_NULL_SHA384);
291     STRINGIFY_CIPHER(TLS_AES_128_GCM_SHA256);
292     STRINGIFY_CIPHER(TLS_AES_256_GCM_SHA384);
293     STRINGIFY_CIPHER(TLS_CHACHA20_POLY1305_SHA256);
294     STRINGIFY_CIPHER(TLS_AES_128_CCM_SHA256);
295     STRINGIFY_CIPHER(TLS_AES_128_CCM_8_SHA256);
296     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
297     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
298     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256);
299     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384);
300     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256);
301     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);
302     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256);
303     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384);
304     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
305     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
306     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256);
307     STRINGIFY_CIPHER(TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384);
308     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
309     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
310     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256);
311     STRINGIFY_CIPHER(TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384);
312     STRINGIFY_CIPHER(TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
313     STRINGIFY_CIPHER(TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
314     STRINGIFY_CIPHER(TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
315     STRINGIFY_CIPHER(SSL_RSA_WITH_RC2_CBC_MD5);
316     STRINGIFY_CIPHER(SSL_RSA_WITH_IDEA_CBC_MD5);
317     STRINGIFY_CIPHER(SSL_RSA_WITH_DES_CBC_MD5);
318     STRINGIFY_CIPHER(SSL_RSA_WITH_3DES_EDE_CBC_MD5);
319     STRINGIFY_CIPHER(SSL_NO_SUCH_CIPHERSUITE);
320     default:
321         ASSERT_NOT_REACHED();
322         return emptyString();
323     }
324
325 #undef STRINGIFY_CIPHER
326 }
327 #endif
328
329 @interface WKNetworkSessionDelegate : NSObject <NSURLSessionDataDelegate
330 #if HAVE(NSURLSESSION_WEBSOCKET)
331     , NSURLSessionWebSocketDelegate
332 #endif
333 > {
334     WeakPtr<WebKit::NetworkSessionCocoa> _session;
335     bool _withCredentials;
336 }
337
338 - (id)initWithNetworkSession:(WebKit::NetworkSessionCocoa&)session withCredentials:(bool)withCredentials;
339 - (void)sessionInvalidated;
340
341 @end
342
343 @implementation WKNetworkSessionDelegate
344
345 - (id)initWithNetworkSession:(WebKit::NetworkSessionCocoa&)session withCredentials:(bool)withCredentials
346 {
347     self = [super init];
348     if (!self)
349         return nil;
350
351     _session = makeWeakPtr(session);
352     _withCredentials = withCredentials;
353
354     return self;
355 }
356
357 - (void)sessionInvalidated
358 {
359     _session = nullptr;
360 }
361
362 - (NetworkDataTaskCocoa*)existingTask:(NSURLSessionTask *)task
363 {
364     if (!_session)
365         return nullptr;
366
367     if (!task)
368         return nullptr;
369
370     auto storedCredentialsPolicy = _withCredentials ? WebCore::StoredCredentialsPolicy::Use : WebCore::StoredCredentialsPolicy::DoNotUse;
371     return _session->dataTaskForIdentifier(task.taskIdentifier, storedCredentialsPolicy);
372 }
373
374 - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error
375 {
376     ASSERT(!_session);
377 }
378
379 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
380 {
381     if (auto* networkDataTask = [self existingTask:task])
382         networkDataTask->didSendData(totalBytesSent, totalBytesExpectedToSend);
383 }
384
385 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
386 {
387     auto* networkDataTask = [self existingTask:task];
388     if (!networkDataTask) {
389         completionHandler(nil);
390         return;
391     }
392
393     auto* body = networkDataTask->firstRequest().httpBody();
394     if (!body) {
395         completionHandler(nil);
396         return;
397     }
398
399     completionHandler(WebCore::createHTTPBodyNSInputStream(*body).get());
400 }
401
402 #if ENABLE(RESOURCE_LOAD_STATISTICS)
403 static NSURLRequest* downgradeRequest(NSURLRequest *request)
404 {
405     NSMutableURLRequest *nsMutableRequest = [[request mutableCopy] autorelease];
406     if ([nsMutableRequest.URL.scheme isEqualToString:@"https"]) {
407         NSURLComponents *components = [NSURLComponents componentsWithURL:nsMutableRequest.URL resolvingAgainstBaseURL:NO];
408         components.scheme = @"http";
409         [nsMutableRequest setURL:components.URL];
410         ASSERT([nsMutableRequest.URL.scheme isEqualToString:@"http"]);
411         return nsMutableRequest;
412     }
413
414     ASSERT_NOT_REACHED();
415     return request;
416 }
417
418 static bool schemeWasUpgradedDueToDynamicHSTS(NSURLRequest *request)
419 {
420     return [request respondsToSelector:@selector(_schemeWasUpgradedDueToDynamicHSTS)]
421         && [request _schemeWasUpgradedDueToDynamicHSTS];
422 }
423 #endif
424
425 static void setIgnoreHSTS(NSMutableURLRequest *request, bool ignoreHSTS)
426 {
427     if ([request respondsToSelector:@selector(_setIgnoreHSTS:)])
428         [request _setIgnoreHSTS:ignoreHSTS];
429 }
430
431 static bool ignoreHSTS(NSURLRequest *request)
432 {
433     return [request respondsToSelector:@selector(_ignoreHSTS)]
434         && [request _ignoreHSTS];
435 }
436
437 static NSURLRequest* updateIgnoreStrictTransportSecuritySettingIfNecessary(NSURLRequest *request, bool shouldIgnoreHSTS)
438 {
439     if ([request.URL.scheme isEqualToString:@"https"] && shouldIgnoreHSTS && ignoreHSTS(request)) {
440         // The request was upgraded for some other reason than HSTS.
441         // Don't ignore HSTS to avoid the risk of another downgrade.
442         NSMutableURLRequest *nsMutableRequest = [[request mutableCopy] autorelease];
443         setIgnoreHSTS(nsMutableRequest, false);
444         return nsMutableRequest;
445     }
446     
447     if ([request.URL.scheme isEqualToString:@"http"] && ignoreHSTS(request) != shouldIgnoreHSTS) {
448         NSMutableURLRequest *nsMutableRequest = [[request mutableCopy] autorelease];
449         setIgnoreHSTS(nsMutableRequest, shouldIgnoreHSTS);
450         return nsMutableRequest;
451     }
452
453     return request;
454 }
455
456 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler
457 {
458     auto taskIdentifier = task.taskIdentifier;
459     LOG(NetworkSession, "%llu willPerformHTTPRedirection from %s to %s", taskIdentifier, response.URL.absoluteString.UTF8String, request.URL.absoluteString.UTF8String);
460
461     if (auto* networkDataTask = [self existingTask:task]) {
462         auto completionHandlerCopy = Block_copy(completionHandler);
463
464         bool shouldIgnoreHSTS = false;
465 #if ENABLE(RESOURCE_LOAD_STATISTICS)
466         shouldIgnoreHSTS = schemeWasUpgradedDueToDynamicHSTS(request) && _session->networkProcess().storageSession(_session->sessionID())->shouldBlockCookies(request, networkDataTask->frameID(), networkDataTask->pageID());
467         if (shouldIgnoreHSTS) {
468             request = downgradeRequest(request);
469             ASSERT([request.URL.scheme isEqualToString:@"http"]);
470             LOG(NetworkSession, "%llu Downgraded %s from https to http", taskIdentifier, request.URL.absoluteString.UTF8String);
471         }
472 #endif
473
474         networkDataTask->willPerformHTTPRedirection(response, request, [completionHandlerCopy, taskIdentifier, shouldIgnoreHSTS](auto&& request) {
475 #if !LOG_DISABLED
476             LOG(NetworkSession, "%llu willPerformHTTPRedirection completionHandler (%s)", taskIdentifier, request.url().string().utf8().data());
477 #else
478             UNUSED_PARAM(taskIdentifier);
479 #endif
480             auto nsRequest = request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::UpdateHTTPBody);
481             nsRequest = updateIgnoreStrictTransportSecuritySettingIfNecessary(nsRequest, shouldIgnoreHSTS);
482             completionHandlerCopy(nsRequest);
483             Block_release(completionHandlerCopy);
484         });
485     } else {
486         LOG(NetworkSession, "%llu willPerformHTTPRedirection completionHandler (nil)", taskIdentifier);
487         completionHandler(nil);
488     }
489 }
490
491 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask*)task _schemeUpgraded:(NSURLRequest*)request completionHandler:(void (^)(NSURLRequest*))completionHandler
492 {
493     auto taskIdentifier = task.taskIdentifier;
494     LOG(NetworkSession, "%llu _schemeUpgraded %s", taskIdentifier, request.URL.absoluteString.UTF8String);
495
496     if (auto* networkDataTask = [self existingTask:task]) {
497         bool shouldIgnoreHSTS = false;
498 #if ENABLE(RESOURCE_LOAD_STATISTICS)
499         shouldIgnoreHSTS = schemeWasUpgradedDueToDynamicHSTS(request) && _session->networkProcess().storageSession(_session->sessionID())->shouldBlockCookies(request, networkDataTask->frameID(), networkDataTask->pageID());
500         if (shouldIgnoreHSTS) {
501             request = downgradeRequest(request);
502             ASSERT([request.URL.scheme isEqualToString:@"http"]);
503             LOG(NetworkSession, "%llu Downgraded %s from https to http", taskIdentifier, request.URL.absoluteString.UTF8String);
504         }
505 #endif
506
507         auto completionHandlerCopy = Block_copy(completionHandler);
508         networkDataTask->willPerformHTTPRedirection(WebCore::synthesizeRedirectResponseIfNecessary([task currentRequest], request, nil), request, [completionHandlerCopy, taskIdentifier, shouldIgnoreHSTS](auto&& request) {
509 #if !LOG_DISABLED
510             LOG(NetworkSession, "%llu _schemeUpgraded completionHandler (%s)", taskIdentifier, request.url().string().utf8().data());
511 #else
512             UNUSED_PARAM(taskIdentifier);
513 #endif
514             auto nsRequest = request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::UpdateHTTPBody);
515             nsRequest = updateIgnoreStrictTransportSecuritySettingIfNecessary(nsRequest, shouldIgnoreHSTS);
516             completionHandlerCopy(nsRequest);
517             Block_release(completionHandlerCopy);
518         });
519     } else {
520         LOG(NetworkSession, "%llu _schemeUpgraded completionHandler (nil)", taskIdentifier);
521         completionHandler(nil);
522     }
523 }
524
525 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
526 {
527     if (!_session) {
528         completionHandler(nil);
529         return;
530     }
531
532     // FIXME: remove if <rdar://problem/20001985> is ever resolved.
533     if ([proposedResponse.response respondsToSelector:@selector(allHeaderFields)]
534         && [[(id)proposedResponse.response allHeaderFields] objectForKey:@"Content-Range"])
535         completionHandler(nil);
536     else
537         completionHandler(proposedResponse);
538 }
539
540 #if HAVE(CFNETWORK_NSURLSESSION_STRICTRUSTEVALUATE)
541 static inline void processServerTrustEvaluation(NetworkSessionCocoa *session, NSURLAuthenticationChallenge *challenge, NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, NetworkDataTaskCocoa* networkDataTask, CompletionHandler<void(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential)>&& completionHandler)
542 {
543     session->continueDidReceiveChallenge(challenge, taskIdentifier, networkDataTask, [completionHandler = WTFMove(completionHandler), secTrust = retainPtr(challenge.protectionSpace.serverTrust)] (WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential) mutable {
544         // FIXME: UIProcess should send us back non nil credentials but the credential IPC encoder currently only serializes ns credentials for username/password.
545         if (disposition == WebKit::AuthenticationChallengeDisposition::UseCredential && !credential.nsCredential()) {
546             completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust: secTrust.get()]);
547             return;
548         }
549         completionHandler(toNSURLSessionAuthChallengeDisposition(disposition), credential.nsCredential());
550     });
551 }
552 #endif
553
554 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
555 {
556     if (!_session || [task state] == NSURLSessionTaskStateCanceling) {
557         completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
558         return;
559     }
560
561     auto taskIdentifier = task.taskIdentifier;
562     LOG(NetworkSession, "%llu didReceiveChallenge", taskIdentifier);
563     
564     // Proxy authentication is handled by CFNetwork internally. We can get here if the user cancels
565     // CFNetwork authentication dialog, and we shouldn't ask the client to display another one in that case.
566     if (challenge.protectionSpace.isProxy) {
567         completionHandler(NSURLSessionAuthChallengeUseCredential, nil);
568         return;
569     }
570
571     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
572         if (NetworkSessionCocoa::allowsSpecificHTTPSCertificateForHost(challenge))
573             return completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
574
575         // Handle server trust evaluation at platform-level if requested, for performance reasons and to use ATS defaults.
576         if (_session->fastServerTrustEvaluationEnabled()) {
577 #if HAVE(CFNETWORK_NSURLSESSION_STRICTRUSTEVALUATE)
578             auto* networkDataTask = [self existingTask:task];
579             ASSERT(networkDataTask);
580             auto decisionHandler = makeBlockPtr([_session = makeWeakPtr(_session.get()), completionHandler = makeBlockPtr(completionHandler), taskIdentifier, networkDataTask = RefPtr<NetworkDataTaskCocoa>(networkDataTask)](NSURLAuthenticationChallenge *challenge, OSStatus trustResult) mutable {
581                 auto task = WTFMove(networkDataTask);
582                 auto* session = _session.get();
583                 if (trustResult == noErr || !session) {
584                     completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
585                     return;
586                 }
587                 processServerTrustEvaluation(session, challenge, taskIdentifier, task.get(), WTFMove(completionHandler));
588             });
589             [NSURLSession _strictTrustEvaluate:challenge queue:[NSOperationQueue mainQueue].underlyingQueue completionHandler:decisionHandler.get()];
590             return;
591 #else
592             return completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil);
593 #endif
594         }
595     }
596     _session->continueDidReceiveChallenge(challenge, taskIdentifier, [self existingTask:task], [completionHandler = makeBlockPtr(completionHandler)] (WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential) mutable {
597         completionHandler(toNSURLSessionAuthChallengeDisposition(disposition), credential.nsCredential());
598     });
599 }
600
601 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
602 {
603     if (!_session)
604         return;
605
606     LOG(NetworkSession, "%llu didCompleteWithError %@", task.taskIdentifier, error);
607
608     if (error) {
609         NSDictionary *oldUserInfo = [error userInfo];
610         NSMutableDictionary *newUserInfo = oldUserInfo ? [NSMutableDictionary dictionaryWithDictionary:oldUserInfo] : [NSMutableDictionary dictionary];
611         newUserInfo[@"networkTaskDescription"] = [task description];
612         error = [NSError errorWithDomain:[error domain] code:[error code] userInfo:newUserInfo];
613     }
614
615     if (auto* networkDataTask = [self existingTask:task])
616         networkDataTask->didCompleteWithError(error, networkDataTask->networkLoadMetrics());
617     else if (error) {
618         auto downloadID = _session->takeDownloadID(task.taskIdentifier);
619         if (downloadID.downloadID()) {
620             if (auto* download = _session->networkProcess().downloadManager().download(downloadID)) {
621                 NSData *resumeData = nil;
622                 if (id userInfo = error.userInfo) {
623                     if ([userInfo isKindOfClass:[NSDictionary class]]) {
624                         resumeData = userInfo[@"NSURLSessionDownloadTaskResumeData"];
625                         if (resumeData && ![resumeData isKindOfClass:[NSData class]]) {
626                             RELEASE_LOG(NetworkSession, "Download task %llu finished with resume data of wrong class: %s", (unsigned long long)task.taskIdentifier, NSStringFromClass([resumeData class]).UTF8String);
627                             ASSERT_NOT_REACHED();
628                             resumeData = nil;
629                         }
630                     }
631                 }
632
633                 auto resumeDataReference = resumeData ? IPC::DataReference { static_cast<const uint8_t*>(resumeData.bytes), resumeData.length } : IPC::DataReference { };
634
635                 if (download->wasCanceled())
636                     download->didCancel(resumeDataReference);
637                 else
638                     download->didFail(error, resumeDataReference);
639             }
640         }
641     }
642 }
643
644 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics
645 {
646     LOG(NetworkSession, "%llu didFinishCollectingMetrics", task.taskIdentifier);
647     if (auto* networkDataTask = [self existingTask:task]) {
648         NSURLSessionTaskTransactionMetrics *m = metrics.transactionMetrics.lastObject;
649         NSDate *fetchStartDate = m.fetchStartDate;
650         NSTimeInterval domainLookupStartInterval = m.domainLookupStartDate ? [m.domainLookupStartDate timeIntervalSinceDate:fetchStartDate] : -1;
651         NSTimeInterval domainLookupEndInterval = m.domainLookupEndDate ? [m.domainLookupEndDate timeIntervalSinceDate:fetchStartDate] : -1;
652         NSTimeInterval connectStartInterval = m.connectStartDate ? [m.connectStartDate timeIntervalSinceDate:fetchStartDate] : -1;
653         NSTimeInterval secureConnectionStartInterval = m.secureConnectionStartDate ? [m.secureConnectionStartDate timeIntervalSinceDate:fetchStartDate] : -1;
654         NSTimeInterval connectEndInterval = m.connectEndDate ? [m.connectEndDate timeIntervalSinceDate:fetchStartDate] : -1;
655         NSTimeInterval requestStartInterval = [m.requestStartDate timeIntervalSinceDate:fetchStartDate];
656         NSTimeInterval responseStartInterval = [m.responseStartDate timeIntervalSinceDate:fetchStartDate];
657         NSTimeInterval responseEndInterval = [m.responseEndDate timeIntervalSinceDate:fetchStartDate];
658
659         auto& networkLoadMetrics = networkDataTask->networkLoadMetrics();
660         networkLoadMetrics.domainLookupStart = Seconds(domainLookupStartInterval);
661         networkLoadMetrics.domainLookupEnd = Seconds(domainLookupEndInterval);
662         networkLoadMetrics.connectStart = Seconds(connectStartInterval);
663         networkLoadMetrics.secureConnectionStart = Seconds(secureConnectionStartInterval);
664         networkLoadMetrics.connectEnd = Seconds(connectEndInterval);
665         networkLoadMetrics.requestStart = Seconds(requestStartInterval);
666         networkLoadMetrics.responseStart = Seconds(responseStartInterval);
667         networkLoadMetrics.responseEnd = Seconds(responseEndInterval);
668         networkLoadMetrics.markComplete();
669         networkLoadMetrics.protocol = String(m.networkProtocolName);
670
671         if (networkDataTask->shouldCaptureExtraNetworkLoadMetrics()) {
672             networkLoadMetrics.priority = toNetworkLoadPriority(task.priority);
673
674             networkLoadMetrics.remoteAddress = String(m._remoteAddressAndPort);
675             networkLoadMetrics.connectionIdentifier = String([m._connectionIdentifier UUIDString]);
676
677 #if HAVE(CFNETWORK_NEGOTIATED_SSL_PROTOCOL_CIPHER)
678             networkLoadMetrics.tlsProtocol = stringForSSLProtocol(m._negotiatedTLSProtocol);
679             networkLoadMetrics.tlsCipher = stringForSSLCipher(m._negotiatedTLSCipher);
680 #endif
681
682             __block WebCore::HTTPHeaderMap requestHeaders;
683             [m.request.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *) {
684                 requestHeaders.set(String(name), String(value));
685             }];
686             networkLoadMetrics.requestHeaders = WTFMove(requestHeaders);
687
688             uint64_t requestHeaderBytesSent = 0;
689             uint64_t responseHeaderBytesReceived = 0;
690             uint64_t responseBodyBytesReceived = 0;
691             uint64_t responseBodyDecodedSize = 0;
692
693             for (NSURLSessionTaskTransactionMetrics *transactionMetrics in metrics.transactionMetrics) {
694                 requestHeaderBytesSent += transactionMetrics._requestHeaderBytesSent;
695                 responseHeaderBytesReceived += transactionMetrics._responseHeaderBytesReceived;
696                 responseBodyBytesReceived += transactionMetrics._responseBodyBytesReceived;
697                 responseBodyDecodedSize += transactionMetrics._responseBodyBytesDecoded ? transactionMetrics._responseBodyBytesDecoded : transactionMetrics._responseBodyBytesReceived;
698             }
699
700             networkLoadMetrics.requestHeaderBytesSent = requestHeaderBytesSent;
701             networkLoadMetrics.requestBodyBytesSent = task.countOfBytesSent;
702             networkLoadMetrics.responseHeaderBytesReceived = responseHeaderBytesReceived;
703             networkLoadMetrics.responseBodyBytesReceived = responseBodyBytesReceived;
704             networkLoadMetrics.responseBodyDecodedSize = responseBodyDecodedSize;
705         }
706     }
707 }
708
709 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
710 {
711     auto taskIdentifier = dataTask.taskIdentifier;
712     LOG(NetworkSession, "%llu didReceiveResponse", taskIdentifier);
713     if (auto* networkDataTask = [self existingTask:dataTask]) {
714         ASSERT(RunLoop::isMain());
715         
716         // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
717         int statusCode = [response isKindOfClass:NSHTTPURLResponse.class] ? [(NSHTTPURLResponse *)response statusCode] : 0;
718         if (statusCode != 304) {
719             bool isMainResourceLoad = networkDataTask->firstRequest().requester() == WebCore::ResourceRequest::Requester::Main;
720             WebCore::adjustMIMETypeIfNecessary(response._CFURLResponse, isMainResourceLoad);
721         }
722
723         WebCore::ResourceResponse resourceResponse(response);
724         // Lazy initialization is not helpful in the WebKit2 case because we always end up initializing
725         // all the fields when sending the response to the WebContent process over IPC.
726         resourceResponse.disableLazyInitialization();
727
728         // FIXME: This cannot be eliminated until other code no longer relies on ResourceResponse's
729         // NetworkLoadMetrics. For example, PerformanceTiming.
730         copyTimingData([dataTask _timingData], resourceResponse.deprecatedNetworkLoadMetrics());
731
732         auto completionHandlerCopy = Block_copy(completionHandler);
733         networkDataTask->didReceiveResponse(WTFMove(resourceResponse), [completionHandlerCopy, taskIdentifier](WebCore::PolicyAction policyAction) {
734 #if !LOG_DISABLED
735             LOG(NetworkSession, "%llu didReceiveResponse completionHandler (%d)", taskIdentifier, policyAction);
736 #else
737             UNUSED_PARAM(taskIdentifier);
738 #endif
739             completionHandlerCopy(toNSURLSessionResponseDisposition(policyAction));
740             Block_release(completionHandlerCopy);
741         });
742     } else {
743         LOG(NetworkSession, "%llu didReceiveResponse completionHandler (cancel)", taskIdentifier);
744         completionHandler(NSURLSessionResponseCancel);
745     }
746 }
747
748 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
749 {
750     if (auto* networkDataTask = [self existingTask:dataTask])
751         networkDataTask->didReceiveData(WebCore::SharedBuffer::create(data));
752 }
753
754 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
755 {
756     if (!_session)
757         return;
758
759     auto downloadID = _session->takeDownloadID([downloadTask taskIdentifier]);
760     if (auto* download = _session->networkProcess().downloadManager().download(downloadID))
761         download->didFinish();
762 }
763
764 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
765 {
766     if (!_session)
767         return;
768
769     ASSERT_WITH_MESSAGE(![self existingTask:downloadTask], "The NetworkDataTask should be destroyed immediately after didBecomeDownloadTask returns");
770
771     auto downloadID = _session->downloadID([downloadTask taskIdentifier]);
772     if (auto* download = _session->networkProcess().downloadManager().download(downloadID))
773         download->didReceiveData(bytesWritten);
774 }
775
776 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
777 {
778     if (!_session)
779         return;
780
781     notImplemented();
782 }
783
784 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
785 {
786     if (auto* networkDataTask = [self existingTask:dataTask]) {
787         Ref<NetworkDataTaskCocoa> protectedNetworkDataTask(*networkDataTask);
788         auto downloadID = networkDataTask->pendingDownloadID();
789         auto& downloadManager = _session->networkProcess().downloadManager();
790         auto download = makeUnique<WebKit::Download>(downloadManager, downloadID, downloadTask, _session->sessionID(), networkDataTask->suggestedFilename());
791         networkDataTask->transferSandboxExtensionToDownload(*download);
792         ASSERT(FileSystem::fileExists(networkDataTask->pendingDownloadLocation()));
793         download->didCreateDestination(networkDataTask->pendingDownloadLocation());
794         downloadManager.dataTaskBecameDownloadTask(downloadID, WTFMove(download));
795
796         _session->addDownloadID([downloadTask taskIdentifier], downloadID);
797     }
798 }
799
800 #if HAVE(NSURLSESSION_WEBSOCKET)
801 - (WebSocketTask*)existingWebSocketTask:(NSURLSessionWebSocketTask *)task
802 {
803     if (!_session)
804         return nullptr;
805
806     if (!task)
807         return nullptr;
808
809     return _session->webSocketDataTaskForIdentifier(task.taskIdentifier);
810 }
811
812
813 - (void)URLSession:(NSURLSession *)session webSocketTask:(NSURLSessionWebSocketTask *)task didOpenWithProtocol:(NSString *) protocol
814 {
815     if (auto* webSocketTask = [self existingWebSocketTask:task])
816         webSocketTask->didConnect(protocol);
817 }
818
819 - (void)URLSession:(NSURLSession *)session webSocketTask:(NSURLSessionWebSocketTask *)task didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode reason:(NSData *)reason
820 {
821     if (auto* webSocketTask = [self existingWebSocketTask:task]) {
822         auto reason = adoptNS([[NSString alloc] initWithData:[task closeReason] encoding:NSUTF8StringEncoding]);
823         webSocketTask->didClose(closeCode, reason.get());
824     }
825 }
826 #endif
827
828 @end
829
830 namespace WebKit {
831
832 #if !ASSERT_DISABLED
833 static bool sessionsCreated = false;
834 #endif
835
836 static NSURLSessionConfiguration *configurationForSessionID(const PAL::SessionID& session)
837 {
838     if (session.isEphemeral()) {
839         NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
840         configuration._shouldSkipPreferredClientCertificateLookup = YES;
841 #if HAVE(ALLOWS_SENSITIVE_LOGGING)
842         configuration._allowsSensitiveLogging = NO;
843 #endif
844         return configuration;
845     }
846     return [NSURLSessionConfiguration defaultSessionConfiguration];
847 }
848
849 const String& NetworkSessionCocoa::boundInterfaceIdentifier() const
850 {
851     return m_boundInterfaceIdentifier;
852 }
853
854 const String& NetworkSessionCocoa::sourceApplicationBundleIdentifier() const
855 {
856     return m_sourceApplicationBundleIdentifier;
857 }
858
859 const String& NetworkSessionCocoa::sourceApplicationSecondaryIdentifier() const
860 {
861     return m_sourceApplicationSecondaryIdentifier;
862 }
863
864 #if PLATFORM(IOS_FAMILY)
865 static String& globalCTDataConnectionServiceType()
866 {
867     static NeverDestroyed<String> ctDataConnectionServiceType;
868     return ctDataConnectionServiceType.get();
869 }
870
871 const String& NetworkSessionCocoa::ctDataConnectionServiceType() const
872 {
873     return globalCTDataConnectionServiceType();
874 }
875
876 void NetworkSessionCocoa::setCTDataConnectionServiceType(const String& type)
877 {
878     ASSERT(!sessionsCreated);
879     globalCTDataConnectionServiceType() = type;
880 }
881 #endif
882
883 std::unique_ptr<NetworkSession> NetworkSessionCocoa::create(NetworkProcess& networkProcess, NetworkSessionCreationParameters&& parameters)
884 {
885     return makeUnique<NetworkSessionCocoa>(networkProcess, WTFMove(parameters));
886 }
887
888 static NSDictionary *proxyDictionary(const URL& httpProxy, const URL& httpsProxy)
889 {
890     if (!httpProxy.isValid() && !httpsProxy.isValid())
891         return nil;
892
893     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
894
895     NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
896     if (httpProxy.isValid()) {
897         [dictionary setObject:httpProxy.host().toString() forKey:(NSString *)kCFStreamPropertyHTTPProxyHost];
898         if (auto port = httpProxy.port())
899             [dictionary setObject:@(*port) forKey:(NSString *)kCFStreamPropertyHTTPProxyPort];
900     }
901     if (httpsProxy.isValid()) {
902         [dictionary setObject:httpsProxy.host().toString() forKey:(NSString *)kCFStreamPropertyHTTPSProxyHost];
903         if (auto port = httpsProxy.port())
904             [dictionary setObject:@(*port) forKey:(NSString *)kCFStreamPropertyHTTPSProxyPort];
905     }
906     return dictionary;
907
908     ALLOW_DEPRECATED_DECLARATIONS_END
909 }
910
911 NetworkSessionCocoa::NetworkSessionCocoa(NetworkProcess& networkProcess, NetworkSessionCreationParameters&& parameters)
912     : NetworkSession(networkProcess, parameters)
913     , m_boundInterfaceIdentifier(parameters.boundInterfaceIdentifier)
914     , m_sourceApplicationBundleIdentifier(parameters.sourceApplicationBundleIdentifier)
915     , m_sourceApplicationSecondaryIdentifier(parameters.sourceApplicationSecondaryIdentifier)
916     , m_proxyConfiguration(parameters.proxyConfiguration)
917     , m_shouldLogCookieInformation(parameters.shouldLogCookieInformation)
918     , m_loadThrottleLatency(parameters.loadThrottleLatency)
919     , m_fastServerTrustEvaluationEnabled(parameters.fastServerTrustEvaluationEnabled)
920 {
921     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
922
923 #if !ASSERT_DISABLED
924     sessionsCreated = true;
925 #endif
926
927     NSURLSessionConfiguration *configuration = configurationForSessionID(m_sessionID);
928
929     if (!parameters.enableLegacyTLS) {
930 #if HAVE(TLS_PROTOCOL_VERSION_T)
931         configuration.TLSMinimumSupportedProtocolVersion = tls_protocol_version_TLSv12;
932 #else
933         configuration.TLSMinimumSupportedProtocol = kTLSProtocol12;
934 #endif
935     }
936
937 #if HAVE(APP_SSO)
938     configuration._preventsAppSSO = true;
939 #endif
940
941     // Without this, CFNetwork would sometimes add a Content-Type header to our requests (rdar://problem/34748470).
942     configuration._suppressedAutoAddedHTTPHeaders = [NSSet setWithObject:@"Content-Type"];
943
944     if (parameters.allowsCellularAccess == AllowsCellularAccess::No)
945         configuration.allowsCellularAccess = NO;
946
947     // The WebKit network cache was already queried.
948     configuration.URLCache = nil;
949
950     if (auto data = networkProcess.sourceApplicationAuditData())
951         configuration._sourceApplicationAuditTokenData = (__bridge NSData *)data.get();
952
953     if (!m_sourceApplicationBundleIdentifier.isEmpty()) {
954         configuration._sourceApplicationBundleIdentifier = m_sourceApplicationBundleIdentifier;
955         configuration._sourceApplicationAuditTokenData = nil;
956     }
957
958     if (!m_sourceApplicationSecondaryIdentifier.isEmpty())
959         configuration._sourceApplicationSecondaryIdentifier = m_sourceApplicationSecondaryIdentifier;
960
961     configuration.connectionProxyDictionary = proxyDictionary(parameters.httpProxy, parameters.httpsProxy);
962
963 #if PLATFORM(IOS_FAMILY)
964     String ctDataConnectionServiceType = parameters.dataConnectionServiceType;
965     if (ctDataConnectionServiceType.isEmpty())
966         ctDataConnectionServiceType = globalCTDataConnectionServiceType();
967     if (!ctDataConnectionServiceType.isEmpty())
968         configuration._CTDataConnectionServiceType = ctDataConnectionServiceType;
969 #endif
970
971 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
972     networkProcess.supplement<LegacyCustomProtocolManager>()->registerProtocolClass(configuration);
973 #endif
974
975 #if HAVE(TIMINGDATAOPTIONS)
976     configuration._timingDataOptions = _TimingDataOptionsEnableW3CNavigationTiming;
977 #else
978     setCollectsTimingData();
979 #endif
980
981 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || PLATFORM(IOS_FAMILY)
982     // FIXME: Replace @"kCFStreamPropertyAutoErrorOnSystemChange" with a constant from the SDK once rdar://problem/40650244 is in a build.
983     if (networkProcess.suppressesConnectionTerminationOnSystemChange())
984         configuration._socketStreamProperties = @{ @"kCFStreamPropertyAutoErrorOnSystemChange" : @NO };
985 #endif
986
987 #if PLATFORM(WATCHOS)
988     configuration._companionProxyPreference = NSURLSessionCompanionProxyPreferencePreferDirectToCloud;
989 #endif
990
991     auto* storageSession = networkProcess.storageSession(parameters.sessionID);
992     RELEASE_ASSERT(storageSession);
993
994     NSHTTPCookieStorage* cookieStorage;
995     if (CFHTTPCookieStorageRef storage = storageSession->cookieStorage().get()) {
996         cookieStorage = [[[NSHTTPCookieStorage alloc] _initWithCFHTTPCookieStorage:storage] autorelease];
997         configuration.HTTPCookieStorage = cookieStorage;
998     } else
999         cookieStorage = storageSession->nsCookieStorage();
1000
1001 #if HAVE(CFNETWORK_OVERRIDE_SESSION_COOKIE_ACCEPT_POLICY)
1002     // We still need to check the selector since CFNetwork updates and WebKit updates are separate
1003     // on older macOS.
1004     if ([cookieStorage respondsToSelector:@selector(_overrideSessionCookieAcceptPolicy)])
1005         cookieStorage._overrideSessionCookieAcceptPolicy = YES;
1006 #endif
1007
1008     m_sessionWithCredentialStorageDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:true]);
1009     m_sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1010     LOG(NetworkSession, "Created NetworkSession with cookieAcceptPolicy %lu", configuration.HTTPCookieStorage.cookieAcceptPolicy);
1011
1012     configuration.URLCredentialStorage = nil;
1013     configuration._shouldSkipPreferredClientCertificateLookup = YES;
1014     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=177394
1015     // configuration.HTTPCookieStorage = nil;
1016     // configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
1017
1018     m_statelessSessionDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:false]);
1019     m_statelessSession = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1020
1021     m_deviceManagementRestrictionsEnabled = parameters.deviceManagementRestrictionsEnabled;
1022     m_allLoadsBlockedByDeviceManagementRestrictionsForTesting = parameters.allLoadsBlockedByDeviceManagementRestrictionsForTesting;
1023
1024 #if ENABLE(RESOURCE_LOAD_STATISTICS)
1025     m_resourceLoadStatisticsDirectory = parameters.resourceLoadStatisticsDirectory;
1026     m_shouldIncludeLocalhostInResourceLoadStatistics = parameters.shouldIncludeLocalhostInResourceLoadStatistics ? ShouldIncludeLocalhost::Yes : ShouldIncludeLocalhost::No;
1027     m_enableResourceLoadStatisticsDebugMode = parameters.enableResourceLoadStatisticsDebugMode ? EnableResourceLoadStatisticsDebugMode::Yes : EnableResourceLoadStatisticsDebugMode::No;
1028     m_resourceLoadStatisticsManualPrevalentResource = parameters.resourceLoadStatisticsManualPrevalentResource;
1029     m_enableResourceLoadStatisticsNSURLSessionSwitching = parameters.enableResourceLoadStatisticsNSURLSessionSwitching ? EnableResourceLoadStatisticsNSURLSessionSwitching::Yes : EnableResourceLoadStatisticsNSURLSessionSwitching::No;
1030     setResourceLoadStatisticsEnabled(parameters.enableResourceLoadStatistics);
1031 #endif
1032
1033 #if HAVE(SESSION_CLEANUP)
1034     activateSessionCleanup(*this);
1035 #endif
1036 }
1037
1038 NetworkSessionCocoa::~NetworkSessionCocoa()
1039 {
1040 }
1041
1042 void NetworkSessionCocoa::initializeEphemeralStatelessCookielessSession()
1043 {
1044     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
1045     NSURLSessionConfiguration *existingConfiguration = m_statelessSession.get().configuration;
1046
1047     configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
1048     configuration.URLCredentialStorage = nil;
1049     configuration.URLCache = nil;
1050     configuration.allowsCellularAccess = existingConfiguration.allowsCellularAccess;
1051     configuration.connectionProxyDictionary = existingConfiguration.connectionProxyDictionary;
1052
1053     configuration._shouldSkipPreferredClientCertificateLookup = YES;
1054     configuration._sourceApplicationAuditTokenData = existingConfiguration._sourceApplicationAuditTokenData;
1055     configuration._sourceApplicationSecondaryIdentifier = existingConfiguration._sourceApplicationSecondaryIdentifier;
1056 #if PLATFORM(IOS_FAMILY)
1057     configuration._CTDataConnectionServiceType = existingConfiguration._CTDataConnectionServiceType;
1058 #endif
1059
1060     m_ephemeralStatelessCookielessSessionDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:false]);
1061     m_ephemeralStatelessCookielessSession = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_ephemeralStatelessCookielessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1062 }
1063
1064 NSURLSession* NetworkSessionCocoa::session(WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
1065 {
1066     switch (storedCredentialsPolicy) {
1067     case WebCore::StoredCredentialsPolicy::Use:
1068         return m_sessionWithCredentialStorage.get();
1069     case WebCore::StoredCredentialsPolicy::DoNotUse:
1070         return m_statelessSession.get();
1071     case WebCore::StoredCredentialsPolicy::EphemeralStatelessCookieless:
1072         if (!m_ephemeralStatelessCookielessSession)
1073             initializeEphemeralStatelessCookielessSession();
1074         return m_ephemeralStatelessCookielessSession.get();
1075     }
1076 }
1077
1078 NSURLSession* NetworkSessionCocoa::isolatedSession(WebCore::StoredCredentialsPolicy storedCredentialsPolicy, const WebCore::RegistrableDomain firstPartyDomain)
1079 {
1080     auto entry = m_isolatedSessions.ensure(firstPartyDomain, [this] {
1081         IsolatedSession newEntry { };
1082         newEntry.sessionWithCredentialStorageDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:true]);
1083         newEntry.sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:m_sessionWithCredentialStorage.get().configuration delegate:static_cast<id>(newEntry.sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1084
1085         newEntry.statelessSessionDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:false]);
1086         newEntry.statelessSession = [NSURLSession sessionWithConfiguration:m_statelessSession.get().configuration delegate:static_cast<id>(newEntry.statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1087
1088         return newEntry;
1089     }).iterator->value;
1090
1091     entry.lastUsed = WallTime::now();
1092
1093     if (m_isolatedSessions.size() > maxNumberOfIsolatedSessions) {
1094         WebCore::RegistrableDomain keyToRemove;
1095         auto oldestTimestamp = WallTime::now();
1096         for (auto& key : m_isolatedSessions.keys()) {
1097             auto timestamp = m_isolatedSessions.get(key).lastUsed;
1098             if (timestamp < oldestTimestamp) {
1099                 oldestTimestamp = timestamp;
1100                 keyToRemove = key;
1101             }
1102         }
1103         LOG(NetworkSession, "About to remove isolated NSURLSession.");
1104         m_isolatedSessions.remove(keyToRemove);
1105     }
1106
1107     RELEASE_ASSERT(m_isolatedSessions.size() <= maxNumberOfIsolatedSessions);
1108
1109     switch (storedCredentialsPolicy) {
1110     case WebCore::StoredCredentialsPolicy::Use:
1111         LOG(NetworkSession, "Using isolated NSURLSession with credential storage.");
1112         return entry.sessionWithCredentialStorage.get();
1113     case WebCore::StoredCredentialsPolicy::DoNotUse:
1114         LOG(NetworkSession, "Using isolated NSURLSession without credential storage.");
1115         return entry.statelessSession.get();
1116     case WebCore::StoredCredentialsPolicy::EphemeralStatelessCookieless:
1117         if (!m_ephemeralStatelessCookielessSession)
1118             initializeEphemeralStatelessCookielessSession();
1119         return m_ephemeralStatelessCookielessSession.get();
1120     }
1121 }
1122
1123 bool NetworkSessionCocoa::hasIsolatedSession(const WebCore::RegistrableDomain domain) const
1124 {
1125     return m_isolatedSessions.contains(domain);
1126 }
1127
1128 void NetworkSessionCocoa::clearIsolatedSessions()
1129 {
1130     m_isolatedSessions.clear();
1131 }
1132
1133 void NetworkSessionCocoa::invalidateAndCancel()
1134 {
1135     NetworkSession::invalidateAndCancel();
1136
1137     [m_sessionWithCredentialStorage invalidateAndCancel];
1138     [m_statelessSession invalidateAndCancel];
1139     [m_ephemeralStatelessCookielessSession invalidateAndCancel];
1140     [m_sessionWithCredentialStorageDelegate sessionInvalidated];
1141     [m_statelessSessionDelegate sessionInvalidated];
1142     [m_ephemeralStatelessCookielessSessionDelegate sessionInvalidated];
1143
1144     for (auto& session : m_isolatedSessions.values()) {
1145         [session.sessionWithCredentialStorage invalidateAndCancel];
1146         [session.sessionWithCredentialStorageDelegate sessionInvalidated];
1147     }
1148     m_isolatedSessions.clear();
1149 }
1150
1151 void NetworkSessionCocoa::clearCredentials()
1152 {
1153 #if !USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
1154     ASSERT(m_dataTaskMapWithCredentials.isEmpty());
1155     ASSERT(m_dataTaskMapWithoutState.isEmpty());
1156     ASSERT(m_downloadMap.isEmpty());
1157     // FIXME: Use resetWithCompletionHandler instead.
1158     m_sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:m_sessionWithCredentialStorage.get().configuration delegate:static_cast<id>(m_sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1159     m_statelessSession = [NSURLSession sessionWithConfiguration:m_statelessSession.get().configuration delegate:static_cast<id>(m_statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1160     for (auto& entry : m_isolatedSessions.values())
1161         entry.session = [NSURLSession sessionWithConfiguration:entry.session.get().configuration delegate:static_cast<id>(entry.delegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1162 #endif
1163 }
1164
1165 NetworkDataTaskCocoa* NetworkSessionCocoa::dataTaskForIdentifier(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
1166 {
1167     ASSERT(RunLoop::isMain());
1168     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use)
1169         return m_dataTaskMapWithCredentials.get(taskIdentifier);
1170     return m_dataTaskMapWithoutState.get(taskIdentifier);
1171 }
1172
1173 NSURLSessionDownloadTask* NetworkSessionCocoa::downloadTaskWithResumeData(NSData* resumeData)
1174 {
1175     return [m_sessionWithCredentialStorage downloadTaskWithResumeData:resumeData];
1176 }
1177
1178 void NetworkSessionCocoa::addDownloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, DownloadID downloadID)
1179 {
1180 #ifndef NDEBUG
1181     ASSERT(!m_downloadMap.contains(taskIdentifier));
1182     for (auto idInMap : m_downloadMap.values())
1183         ASSERT(idInMap != downloadID);
1184 #endif
1185     m_downloadMap.add(taskIdentifier, downloadID);
1186 }
1187
1188 DownloadID NetworkSessionCocoa::downloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier)
1189 {
1190     ASSERT(m_downloadMap.get(taskIdentifier).downloadID());
1191     return m_downloadMap.get(taskIdentifier);
1192 }
1193
1194 DownloadID NetworkSessionCocoa::takeDownloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier)
1195 {
1196     auto downloadID = m_downloadMap.take(taskIdentifier);
1197     return downloadID;
1198 }
1199
1200 static bool certificatesMatch(SecTrustRef trust1, SecTrustRef trust2)
1201 {
1202     if (!trust1 || !trust2)
1203         return false;
1204
1205     CFIndex count1 = SecTrustGetCertificateCount(trust1);
1206     CFIndex count2 = SecTrustGetCertificateCount(trust2);
1207     if (count1 != count2)
1208         return false;
1209
1210     for (CFIndex i = 0; i < count1; i++) {
1211         auto cert1 = SecTrustGetCertificateAtIndex(trust1, i);
1212         auto cert2 = SecTrustGetCertificateAtIndex(trust2, i);
1213         RELEASE_ASSERT(cert1);
1214         RELEASE_ASSERT(cert2);
1215         if (!CFEqual(cert1, cert2))
1216             return false;
1217     }
1218
1219     return true;
1220 }
1221
1222 bool NetworkSessionCocoa::allowsSpecificHTTPSCertificateForHost(const WebCore::AuthenticationChallenge& challenge)
1223 {
1224     const String& host = challenge.protectionSpace().host();
1225     NSArray *certificates = [NSURLRequest allowsSpecificHTTPSCertificateForHost:host];
1226     if (!certificates)
1227         return false;
1228
1229     bool requireServerCertificates = challenge.protectionSpace().authenticationScheme() == WebCore::ProtectionSpaceAuthenticationScheme::ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested;
1230     RetainPtr<SecPolicyRef> policy = adoptCF(SecPolicyCreateSSL(requireServerCertificates, host.createCFString().get()));
1231
1232     SecTrustRef trustRef = nullptr;
1233     if (SecTrustCreateWithCertificates((CFArrayRef)certificates, policy.get(), &trustRef) != noErr)
1234         return false;
1235     RetainPtr<SecTrustRef> trust = adoptCF(trustRef);
1236
1237     return certificatesMatch(trust.get(), challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust);
1238 }
1239
1240 void NetworkSessionCocoa::continueDidReceiveChallenge(const WebCore::AuthenticationChallenge& challenge, NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, NetworkDataTaskCocoa* networkDataTask, CompletionHandler<void(WebKit::AuthenticationChallengeDisposition, const WebCore::Credential&)>&& completionHandler)
1241 {
1242     if (!networkDataTask) {
1243 #if HAVE(NSURLSESSION_WEBSOCKET)
1244         if (auto* webSocketTask = webSocketDataTaskForIdentifier(taskIdentifier)) {
1245             // FIXME: Handle challenges for web socket.
1246             completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
1247             return;
1248         }
1249 #endif
1250
1251         auto downloadID = this->downloadID(taskIdentifier);
1252         if (downloadID.downloadID()) {
1253             if (auto* download = networkProcess().downloadManager().download(downloadID)) {
1254                 WebCore::AuthenticationChallenge authenticationChallenge { challenge };
1255                 // Received an authentication challenge for a download being resumed.
1256                 download->didReceiveChallenge(authenticationChallenge, WTFMove(completionHandler));
1257                 return;
1258             }
1259         }
1260         LOG(NetworkSession, "%llu didReceiveChallenge completionHandler (cancel)", taskIdentifier);
1261         completionHandler(AuthenticationChallengeDisposition::Cancel, { });
1262         return;
1263     }
1264
1265     auto sessionID = this->sessionID();
1266     WebCore::AuthenticationChallenge authenticationChallenge { challenge };
1267     auto challengeCompletionHandler = [completionHandler = WTFMove(completionHandler), networkProcess = makeRef(networkProcess()), sessionID, authenticationChallenge, taskIdentifier, partition = networkDataTask->partition()](WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential) mutable {
1268 #if !LOG_DISABLED
1269         LOG(NetworkSession, "%llu didReceiveChallenge completionHandler %d", taskIdentifier, disposition);
1270 #else
1271         UNUSED_PARAM(taskIdentifier);
1272 #endif
1273 #if !USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
1274         UNUSED_PARAM(sessionID);
1275         UNUSED_PARAM(authenticationChallenge);
1276 #else
1277         if (credential.persistence() == WebCore::CredentialPersistenceForSession && authenticationChallenge.protectionSpace().isPasswordBased()) {
1278             WebCore::Credential nonPersistentCredential(credential.user(), credential.password(), WebCore::CredentialPersistenceNone);
1279             URL urlToStore;
1280             if (authenticationChallenge.failureResponse().httpStatusCode() == 401)
1281                 urlToStore = authenticationChallenge.failureResponse().url();
1282             if (auto storageSession = networkProcess->storageSession(sessionID))
1283                 storageSession->credentialStorage().set(partition, nonPersistentCredential, authenticationChallenge.protectionSpace(), urlToStore);
1284             else
1285                 ASSERT_NOT_REACHED();
1286
1287             completionHandler(disposition, nonPersistentCredential);
1288             return;
1289         }
1290 #endif
1291         completionHandler(disposition, credential);
1292     };
1293     networkDataTask->didReceiveChallenge(WTFMove(authenticationChallenge), WTFMove(challengeCompletionHandler));
1294 }
1295
1296 DMFWebsitePolicyMonitor *NetworkSessionCocoa::deviceManagementPolicyMonitor()
1297 {
1298 #if HAVE(DEVICE_MANAGEMENT)
1299     ASSERT(m_deviceManagementRestrictionsEnabled);
1300     if (!m_deviceManagementPolicyMonitor)
1301         m_deviceManagementPolicyMonitor = adoptNS([allocDMFWebsitePolicyMonitorInstance() initWithPolicyChangeHandler:nil]);
1302     return m_deviceManagementPolicyMonitor.get();
1303 #else
1304     RELEASE_ASSERT_NOT_REACHED();
1305     return nil;
1306 #endif
1307 }
1308
1309 #if HAVE(NSURLSESSION_WEBSOCKET)
1310 std::unique_ptr<WebSocketTask> NetworkSessionCocoa::createWebSocketTask(NetworkSocketChannel& channel, const WebCore::ResourceRequest& request, const String& protocol)
1311 {
1312     // FIXME: Use protocol.
1313     RetainPtr<NSURLSessionWebSocketTask> task = [m_sessionWithCredentialStorage.get() webSocketTaskWithRequest: request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::DoNotUpdateHTTPBody)];
1314     return makeUnique<WebSocketTask>(channel, WTFMove(task));
1315 }
1316
1317 void NetworkSessionCocoa::addWebSocketTask(WebSocketTask& task)
1318 {
1319     ASSERT(!m_webSocketDataTaskMap.contains(task.identifier()));
1320     m_webSocketDataTaskMap.add(task.identifier(), &task);
1321 }
1322
1323 void NetworkSessionCocoa::removeWebSocketTask(WebSocketTask& task)
1324 {
1325     ASSERT(m_webSocketDataTaskMap.contains(task.identifier()));
1326     m_webSocketDataTaskMap.remove(task.identifier());
1327 }
1328
1329 WebSocketTask* NetworkSessionCocoa::webSocketDataTaskForIdentifier(WebSocketTask::TaskIdentifier identifier)
1330 {
1331     return m_webSocketDataTaskMap.get(identifier);
1332 }
1333
1334 #endif
1335 }