Resource Load Statistics: Switch NSURLSession on top navigation to prevalent resource...
[WebKit.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 HAVE(CFNETWORK_WITH_IGNORE_HSTS) && 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 #if HAVE(CFNETWORK_WITH_IGNORE_HSTS)
426 static void setIgnoreHSTS(NSMutableURLRequest *request, bool ignoreHSTS)
427 {
428     if ([request respondsToSelector:@selector(_setIgnoreHSTS:)])
429         [request _setIgnoreHSTS:ignoreHSTS];
430 }
431
432 static bool ignoreHSTS(NSURLRequest *request)
433 {
434     return [request respondsToSelector:@selector(_ignoreHSTS)]
435         && [request _ignoreHSTS];
436 }
437 #endif
438
439 static NSURLRequest* updateIgnoreStrictTransportSecuritySettingIfNecessary(NSURLRequest *request, bool shouldIgnoreHSTS)
440 {
441 #if HAVE(CFNETWORK_WITH_IGNORE_HSTS)
442     if ([request.URL.scheme isEqualToString:@"https"] && shouldIgnoreHSTS && ignoreHSTS(request)) {
443         // The request was upgraded for some other reason than HSTS.
444         // Don't ignore HSTS to avoid the risk of another downgrade.
445         NSMutableURLRequest *nsMutableRequest = [[request mutableCopy] autorelease];
446         setIgnoreHSTS(nsMutableRequest, false);
447         return nsMutableRequest;
448     }
449     
450     if ([request.URL.scheme isEqualToString:@"http"] && ignoreHSTS(request) != shouldIgnoreHSTS) {
451         NSMutableURLRequest *nsMutableRequest = [[request mutableCopy] autorelease];
452         setIgnoreHSTS(nsMutableRequest, shouldIgnoreHSTS);
453         return nsMutableRequest;
454     }
455 #else
456     UNUSED_PARAM(shouldIgnoreHSTS);
457 #endif
458
459     return request;
460 }
461
462 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler
463 {
464     auto taskIdentifier = task.taskIdentifier;
465     LOG(NetworkSession, "%llu willPerformHTTPRedirection from %s to %s", taskIdentifier, response.URL.absoluteString.UTF8String, request.URL.absoluteString.UTF8String);
466
467     if (auto* networkDataTask = [self existingTask:task]) {
468         auto completionHandlerCopy = Block_copy(completionHandler);
469
470         bool shouldIgnoreHSTS = false;
471 #if HAVE(CFNETWORK_WITH_IGNORE_HSTS) && ENABLE(RESOURCE_LOAD_STATISTICS)        
472         shouldIgnoreHSTS = schemeWasUpgradedDueToDynamicHSTS(request) && _session->networkProcess().storageSession(_session->sessionID())->shouldBlockCookies(request, networkDataTask->frameID(), networkDataTask->pageID());
473         if (shouldIgnoreHSTS) {
474             request = downgradeRequest(request);
475             ASSERT([request.URL.scheme isEqualToString:@"http"]);
476             LOG(NetworkSession, "%llu Downgraded %s from https to http", taskIdentifier, request.URL.absoluteString.UTF8String);
477         }
478 #endif
479
480         networkDataTask->willPerformHTTPRedirection(response, request, [completionHandlerCopy, taskIdentifier, shouldIgnoreHSTS](auto&& request) {
481 #if !LOG_DISABLED
482             LOG(NetworkSession, "%llu willPerformHTTPRedirection completionHandler (%s)", taskIdentifier, request.url().string().utf8().data());
483 #else
484             UNUSED_PARAM(taskIdentifier);
485 #endif
486             auto nsRequest = request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::UpdateHTTPBody);
487             nsRequest = updateIgnoreStrictTransportSecuritySettingIfNecessary(nsRequest, shouldIgnoreHSTS);
488             completionHandlerCopy(nsRequest);
489             Block_release(completionHandlerCopy);
490         });
491     } else {
492         LOG(NetworkSession, "%llu willPerformHTTPRedirection completionHandler (nil)", taskIdentifier);
493         completionHandler(nil);
494     }
495 }
496
497 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask*)task _schemeUpgraded:(NSURLRequest*)request completionHandler:(void (^)(NSURLRequest*))completionHandler
498 {
499     auto taskIdentifier = task.taskIdentifier;
500     LOG(NetworkSession, "%llu _schemeUpgraded %s", taskIdentifier, request.URL.absoluteString.UTF8String);
501
502     if (auto* networkDataTask = [self existingTask:task]) {
503         bool shouldIgnoreHSTS = false;
504 #if HAVE(CFNETWORK_WITH_IGNORE_HSTS) && ENABLE(RESOURCE_LOAD_STATISTICS)
505         shouldIgnoreHSTS = schemeWasUpgradedDueToDynamicHSTS(request) && _session->networkProcess().storageSession(_session->sessionID())->shouldBlockCookies(request, networkDataTask->frameID(), networkDataTask->pageID());
506         if (shouldIgnoreHSTS) {
507             request = downgradeRequest(request);
508             ASSERT([request.URL.scheme isEqualToString:@"http"]);
509             LOG(NetworkSession, "%llu Downgraded %s from https to http", taskIdentifier, request.URL.absoluteString.UTF8String);
510         }
511 #endif
512
513         auto completionHandlerCopy = Block_copy(completionHandler);
514         networkDataTask->willPerformHTTPRedirection(WebCore::synthesizeRedirectResponseIfNecessary([task currentRequest], request, nil), request, [completionHandlerCopy, taskIdentifier, shouldIgnoreHSTS](auto&& request) {
515 #if !LOG_DISABLED
516             LOG(NetworkSession, "%llu _schemeUpgraded completionHandler (%s)", taskIdentifier, request.url().string().utf8().data());
517 #else
518             UNUSED_PARAM(taskIdentifier);
519 #endif
520             auto nsRequest = request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::UpdateHTTPBody);
521             nsRequest = updateIgnoreStrictTransportSecuritySettingIfNecessary(nsRequest, shouldIgnoreHSTS);
522             completionHandlerCopy(nsRequest);
523             Block_release(completionHandlerCopy);
524         });
525     } else {
526         LOG(NetworkSession, "%llu _schemeUpgraded completionHandler (nil)", taskIdentifier);
527         completionHandler(nil);
528     }
529 }
530
531 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
532 {
533     if (!_session) {
534         completionHandler(nil);
535         return;
536     }
537
538     // FIXME: remove if <rdar://problem/20001985> is ever resolved.
539     if ([proposedResponse.response respondsToSelector:@selector(allHeaderFields)]
540         && [[(id)proposedResponse.response allHeaderFields] objectForKey:@"Content-Range"])
541         completionHandler(nil);
542     else
543         completionHandler(proposedResponse);
544 }
545
546 #if HAVE(CFNETWORK_NSURLSESSION_STRICTRUSTEVALUATE)
547 static bool canNSURLSessionTrustEvaluate()
548 {
549     return [NSURLSession respondsToSelector:@selector(_strictTrustEvaluate: queue: completionHandler:)];
550 }
551
552 static inline void processServerTrustEvaluation(NetworkSessionCocoa *session, NSURLAuthenticationChallenge *challenge, NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, NetworkDataTaskCocoa* networkDataTask, CompletionHandler<void(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential)>&& completionHandler)
553 {
554     session->continueDidReceiveChallenge(challenge, taskIdentifier, networkDataTask, [completionHandler = WTFMove(completionHandler), secTrust = retainPtr(challenge.protectionSpace.serverTrust)] (WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential) mutable {
555         // FIXME: UIProcess should send us back non nil credentials but the credential IPC encoder currently only serializes ns credentials for username/password.
556         if (disposition == WebKit::AuthenticationChallengeDisposition::UseCredential && !credential.nsCredential()) {
557             completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust: secTrust.get()]);
558             return;
559         }
560         completionHandler(toNSURLSessionAuthChallengeDisposition(disposition), credential.nsCredential());
561     });
562 }
563 #endif
564
565 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
566 {
567     if (!_session) {
568         completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
569         return;
570     }
571
572     auto taskIdentifier = task.taskIdentifier;
573     LOG(NetworkSession, "%llu didReceiveChallenge", taskIdentifier);
574     
575     // Proxy authentication is handled by CFNetwork internally. We can get here if the user cancels
576     // CFNetwork authentication dialog, and we shouldn't ask the client to display another one in that case.
577     if (challenge.protectionSpace.isProxy) {
578         completionHandler(NSURLSessionAuthChallengeUseCredential, nil);
579         return;
580     }
581
582     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
583         if (NetworkSessionCocoa::allowsSpecificHTTPSCertificateForHost(challenge))
584             return completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
585
586         // Handle server trust evaluation at platform-level if requested, for performance reasons and to use ATS defaults.
587         if (!_session->networkProcess().canHandleHTTPSServerTrustEvaluation()) {
588 #if HAVE(CFNETWORK_NSURLSESSION_STRICTRUSTEVALUATE)
589             if (canNSURLSessionTrustEvaluate()) {
590                 auto* networkDataTask = [self existingTask:task];
591                 auto decisionHandler = makeBlockPtr([_session = makeWeakPtr(_session.get()), completionHandler = makeBlockPtr(completionHandler), taskIdentifier, networkDataTask = RefPtr<NetworkDataTaskCocoa>(networkDataTask)](NSURLAuthenticationChallenge *challenge, OSStatus trustResult) mutable {
592                     auto task = WTFMove(networkDataTask);
593                     auto* session = _session.get();
594                     if (trustResult == noErr || !session) {
595                         completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
596                         return;
597                     }
598                     processServerTrustEvaluation(session, challenge, taskIdentifier, task.get(), WTFMove(completionHandler));
599                 });
600                 [NSURLSession _strictTrustEvaluate:challenge queue:[NSOperationQueue mainQueue].underlyingQueue completionHandler:decisionHandler.get()];
601                 return;
602             }
603 #endif
604             return completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil);
605         }
606     }
607     _session->continueDidReceiveChallenge(challenge, taskIdentifier, [self existingTask:task], [completionHandler = makeBlockPtr(completionHandler)] (WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential) mutable {
608         completionHandler(toNSURLSessionAuthChallengeDisposition(disposition), credential.nsCredential());
609     });
610 }
611
612 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
613 {
614     if (!_session)
615         return;
616
617     LOG(NetworkSession, "%llu didCompleteWithError %@", task.taskIdentifier, error);
618
619     if (error) {
620         NSDictionary *oldUserInfo = [error userInfo];
621         NSMutableDictionary *newUserInfo = oldUserInfo ? [NSMutableDictionary dictionaryWithDictionary:oldUserInfo] : [NSMutableDictionary dictionary];
622         newUserInfo[@"networkTaskDescription"] = [task description];
623         error = [NSError errorWithDomain:[error domain] code:[error code] userInfo:newUserInfo];
624     }
625
626     if (auto* networkDataTask = [self existingTask:task])
627         networkDataTask->didCompleteWithError(error, networkDataTask->networkLoadMetrics());
628     else if (error) {
629         auto downloadID = _session->takeDownloadID(task.taskIdentifier);
630         if (downloadID.downloadID()) {
631             if (auto* download = _session->networkProcess().downloadManager().download(downloadID)) {
632                 NSData *resumeData = nil;
633                 if (id userInfo = error.userInfo) {
634                     if ([userInfo isKindOfClass:[NSDictionary class]]) {
635                         resumeData = userInfo[@"NSURLSessionDownloadTaskResumeData"];
636                         if (resumeData && ![resumeData isKindOfClass:[NSData class]]) {
637                             RELEASE_LOG(NetworkSession, "Download task %llu finished with resume data of wrong class: %s", (unsigned long long)task.taskIdentifier, NSStringFromClass([resumeData class]).UTF8String);
638                             ASSERT_NOT_REACHED();
639                             resumeData = nil;
640                         }
641                     }
642                 }
643
644                 auto resumeDataReference = resumeData ? IPC::DataReference { static_cast<const uint8_t*>(resumeData.bytes), resumeData.length } : IPC::DataReference { };
645
646                 if (download->wasCanceled())
647                     download->didCancel(resumeDataReference);
648                 else
649                     download->didFail(error, resumeDataReference);
650             }
651         }
652     }
653 }
654
655 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics
656 {
657     LOG(NetworkSession, "%llu didFinishCollectingMetrics", task.taskIdentifier);
658     if (auto* networkDataTask = [self existingTask:task]) {
659         NSURLSessionTaskTransactionMetrics *m = metrics.transactionMetrics.lastObject;
660         NSDate *fetchStartDate = m.fetchStartDate;
661         NSTimeInterval domainLookupStartInterval = m.domainLookupStartDate ? [m.domainLookupStartDate timeIntervalSinceDate:fetchStartDate] : -1;
662         NSTimeInterval domainLookupEndInterval = m.domainLookupEndDate ? [m.domainLookupEndDate timeIntervalSinceDate:fetchStartDate] : -1;
663         NSTimeInterval connectStartInterval = m.connectStartDate ? [m.connectStartDate timeIntervalSinceDate:fetchStartDate] : -1;
664         NSTimeInterval secureConnectionStartInterval = m.secureConnectionStartDate ? [m.secureConnectionStartDate timeIntervalSinceDate:fetchStartDate] : -1;
665         NSTimeInterval connectEndInterval = m.connectEndDate ? [m.connectEndDate timeIntervalSinceDate:fetchStartDate] : -1;
666         NSTimeInterval requestStartInterval = [m.requestStartDate timeIntervalSinceDate:fetchStartDate];
667         NSTimeInterval responseStartInterval = [m.responseStartDate timeIntervalSinceDate:fetchStartDate];
668         NSTimeInterval responseEndInterval = [m.responseEndDate timeIntervalSinceDate:fetchStartDate];
669
670         auto& networkLoadMetrics = networkDataTask->networkLoadMetrics();
671         networkLoadMetrics.domainLookupStart = Seconds(domainLookupStartInterval);
672         networkLoadMetrics.domainLookupEnd = Seconds(domainLookupEndInterval);
673         networkLoadMetrics.connectStart = Seconds(connectStartInterval);
674         networkLoadMetrics.secureConnectionStart = Seconds(secureConnectionStartInterval);
675         networkLoadMetrics.connectEnd = Seconds(connectEndInterval);
676         networkLoadMetrics.requestStart = Seconds(requestStartInterval);
677         networkLoadMetrics.responseStart = Seconds(responseStartInterval);
678         networkLoadMetrics.responseEnd = Seconds(responseEndInterval);
679         networkLoadMetrics.markComplete();
680         networkLoadMetrics.protocol = String(m.networkProtocolName);
681
682         if (networkDataTask->shouldCaptureExtraNetworkLoadMetrics()) {
683             networkLoadMetrics.priority = toNetworkLoadPriority(task.priority);
684
685 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
686             networkLoadMetrics.remoteAddress = String(m._remoteAddressAndPort);
687             networkLoadMetrics.connectionIdentifier = String([m._connectionIdentifier UUIDString]);
688 #endif
689
690 #if HAVE(CFNETWORK_NEGOTIATED_SSL_PROTOCOL_CIPHER)
691             networkLoadMetrics.tlsProtocol = stringForSSLProtocol(m._negotiatedTLSProtocol);
692             networkLoadMetrics.tlsCipher = stringForSSLCipher(m._negotiatedTLSCipher);
693 #endif
694
695             __block WebCore::HTTPHeaderMap requestHeaders;
696             [m.request.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *) {
697                 requestHeaders.set(String(name), String(value));
698             }];
699             networkLoadMetrics.requestHeaders = WTFMove(requestHeaders);
700
701 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
702             uint64_t requestHeaderBytesSent = 0;
703             uint64_t responseHeaderBytesReceived = 0;
704             uint64_t responseBodyBytesReceived = 0;
705             uint64_t responseBodyDecodedSize = 0;
706
707             for (NSURLSessionTaskTransactionMetrics *transactionMetrics in metrics.transactionMetrics) {
708                 requestHeaderBytesSent += transactionMetrics._requestHeaderBytesSent;
709                 responseHeaderBytesReceived += transactionMetrics._responseHeaderBytesReceived;
710                 responseBodyBytesReceived += transactionMetrics._responseBodyBytesReceived;
711                 responseBodyDecodedSize += transactionMetrics._responseBodyBytesDecoded ? transactionMetrics._responseBodyBytesDecoded : transactionMetrics._responseBodyBytesReceived;
712             }
713
714             networkLoadMetrics.requestHeaderBytesSent = requestHeaderBytesSent;
715             networkLoadMetrics.requestBodyBytesSent = task.countOfBytesSent;
716             networkLoadMetrics.responseHeaderBytesReceived = responseHeaderBytesReceived;
717             networkLoadMetrics.responseBodyBytesReceived = responseBodyBytesReceived;
718             networkLoadMetrics.responseBodyDecodedSize = responseBodyDecodedSize;
719 #endif
720         }
721     }
722 }
723
724 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
725 {
726     auto taskIdentifier = dataTask.taskIdentifier;
727     LOG(NetworkSession, "%llu didReceiveResponse", taskIdentifier);
728     if (auto* networkDataTask = [self existingTask:dataTask]) {
729         ASSERT(RunLoop::isMain());
730         
731         // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
732         int statusCode = [response isKindOfClass:NSHTTPURLResponse.class] ? [(NSHTTPURLResponse *)response statusCode] : 0;
733         if (statusCode != 304) {
734             bool isMainResourceLoad = networkDataTask->firstRequest().requester() == WebCore::ResourceRequest::Requester::Main;
735             WebCore::adjustMIMETypeIfNecessary(response._CFURLResponse, isMainResourceLoad);
736         }
737
738         WebCore::ResourceResponse resourceResponse(response);
739         // Lazy initialization is not helpful in the WebKit2 case because we always end up initializing
740         // all the fields when sending the response to the WebContent process over IPC.
741         resourceResponse.disableLazyInitialization();
742
743         // FIXME: This cannot be eliminated until other code no longer relies on ResourceResponse's
744         // NetworkLoadMetrics. For example, PerformanceTiming.
745         copyTimingData([dataTask _timingData], resourceResponse.deprecatedNetworkLoadMetrics());
746
747         auto completionHandlerCopy = Block_copy(completionHandler);
748         networkDataTask->didReceiveResponse(WTFMove(resourceResponse), [completionHandlerCopy, taskIdentifier](WebCore::PolicyAction policyAction) {
749 #if !LOG_DISABLED
750             LOG(NetworkSession, "%llu didReceiveResponse completionHandler (%d)", taskIdentifier, policyAction);
751 #else
752             UNUSED_PARAM(taskIdentifier);
753 #endif
754             completionHandlerCopy(toNSURLSessionResponseDisposition(policyAction));
755             Block_release(completionHandlerCopy);
756         });
757     } else {
758         LOG(NetworkSession, "%llu didReceiveResponse completionHandler (cancel)", taskIdentifier);
759         completionHandler(NSURLSessionResponseCancel);
760     }
761 }
762
763 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
764 {
765     if (auto* networkDataTask = [self existingTask:dataTask])
766         networkDataTask->didReceiveData(WebCore::SharedBuffer::create(data));
767 }
768
769 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
770 {
771     if (!_session)
772         return;
773
774     auto downloadID = _session->takeDownloadID([downloadTask taskIdentifier]);
775     if (auto* download = _session->networkProcess().downloadManager().download(downloadID))
776         download->didFinish();
777 }
778
779 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
780 {
781     if (!_session)
782         return;
783
784     ASSERT_WITH_MESSAGE(![self existingTask:downloadTask], "The NetworkDataTask should be destroyed immediately after didBecomeDownloadTask returns");
785
786     auto downloadID = _session->downloadID([downloadTask taskIdentifier]);
787     if (auto* download = _session->networkProcess().downloadManager().download(downloadID))
788         download->didReceiveData(bytesWritten);
789 }
790
791 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
792 {
793     if (!_session)
794         return;
795
796     notImplemented();
797 }
798
799 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
800 {
801     if (auto* networkDataTask = [self existingTask:dataTask]) {
802         Ref<NetworkDataTaskCocoa> protectedNetworkDataTask(*networkDataTask);
803         auto downloadID = networkDataTask->pendingDownloadID();
804         auto& downloadManager = _session->networkProcess().downloadManager();
805         auto download = std::make_unique<WebKit::Download>(downloadManager, downloadID, downloadTask, _session->sessionID(), networkDataTask->suggestedFilename());
806         networkDataTask->transferSandboxExtensionToDownload(*download);
807         ASSERT(FileSystem::fileExists(networkDataTask->pendingDownloadLocation()));
808         download->didCreateDestination(networkDataTask->pendingDownloadLocation());
809         downloadManager.dataTaskBecameDownloadTask(downloadID, WTFMove(download));
810
811         _session->addDownloadID([downloadTask taskIdentifier], downloadID);
812     }
813 }
814
815 #if HAVE(NSURLSESSION_WEBSOCKET)
816 - (WebSocketTask*)existingWebSocketTask:(NSURLSessionWebSocketTask *)task
817 {
818     if (!_session)
819         return nullptr;
820
821     if (!task)
822         return nullptr;
823
824     return _session->webSocketDataTaskForIdentifier(task.taskIdentifier);
825 }
826
827
828 - (void)URLSession:(NSURLSession *)session webSocketTask:(NSURLSessionWebSocketTask *)task didOpenWithProtocol:(NSString *) protocol
829 {
830     if (auto* webSocketTask = [self existingWebSocketTask:task])
831         webSocketTask->didConnect(protocol);
832 }
833
834 - (void)URLSession:(NSURLSession *)session webSocketTask:(NSURLSessionWebSocketTask *)task didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode reason:(NSData *)reason
835 {
836     if (auto* webSocketTask = [self existingWebSocketTask:task]) {
837         auto reason = adoptNS([[NSString alloc] initWithData:[task closeReason] encoding:NSUTF8StringEncoding]);
838         webSocketTask->didClose(closeCode, reason.get());
839     }
840 }
841 #endif
842
843 @end
844
845 namespace WebKit {
846
847 #if !ASSERT_DISABLED
848 static bool sessionsCreated = false;
849 #endif
850
851 static NSURLSessionConfiguration *configurationForSessionID(const PAL::SessionID& session)
852 {
853     if (session.isEphemeral()) {
854         NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
855         configuration._shouldSkipPreferredClientCertificateLookup = YES;
856 #if HAVE(ALLOWS_SENSITIVE_LOGGING)
857         configuration._allowsSensitiveLogging = NO;
858 #endif
859         return configuration;
860     }
861     return [NSURLSessionConfiguration defaultSessionConfiguration];
862 }
863
864 const String& NetworkSessionCocoa::boundInterfaceIdentifier() const
865 {
866     return m_boundInterfaceIdentifier;
867 }
868
869 const String& NetworkSessionCocoa::sourceApplicationBundleIdentifier() const
870 {
871     return m_sourceApplicationBundleIdentifier;
872 }
873
874 const String& NetworkSessionCocoa::sourceApplicationSecondaryIdentifier() const
875 {
876     return m_sourceApplicationSecondaryIdentifier;
877 }
878
879 #if PLATFORM(IOS_FAMILY)
880 static String& globalCTDataConnectionServiceType()
881 {
882     static NeverDestroyed<String> ctDataConnectionServiceType;
883     return ctDataConnectionServiceType.get();
884 }
885
886 const String& NetworkSessionCocoa::ctDataConnectionServiceType() const
887 {
888     return globalCTDataConnectionServiceType();
889 }
890
891 void NetworkSessionCocoa::setCTDataConnectionServiceType(const String& type)
892 {
893     ASSERT(!sessionsCreated);
894     globalCTDataConnectionServiceType() = type;
895 }
896 #endif
897
898 std::unique_ptr<NetworkSession> NetworkSessionCocoa::create(NetworkProcess& networkProcess, NetworkSessionCreationParameters&& parameters)
899 {
900     return std::make_unique<NetworkSessionCocoa>(networkProcess, WTFMove(parameters));
901 }
902
903 static NSDictionary *proxyDictionary(const URL& httpProxy, const URL& httpsProxy)
904 {
905     if (!httpProxy.isValid() && !httpsProxy.isValid())
906         return nil;
907
908     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
909
910     NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
911     if (httpProxy.isValid()) {
912         [dictionary setObject:httpProxy.host().toString() forKey:(NSString *)kCFStreamPropertyHTTPProxyHost];
913         if (auto port = httpProxy.port())
914             [dictionary setObject:@(*port) forKey:(NSString *)kCFStreamPropertyHTTPProxyPort];
915     }
916     if (httpsProxy.isValid()) {
917         [dictionary setObject:httpsProxy.host().toString() forKey:(NSString *)kCFStreamPropertyHTTPSProxyHost];
918         if (auto port = httpsProxy.port())
919             [dictionary setObject:@(*port) forKey:(NSString *)kCFStreamPropertyHTTPSProxyPort];
920     }
921     return dictionary;
922
923     ALLOW_DEPRECATED_DECLARATIONS_END
924 }
925
926 NetworkSessionCocoa::NetworkSessionCocoa(NetworkProcess& networkProcess, NetworkSessionCreationParameters&& parameters)
927     : NetworkSession(networkProcess, parameters)
928     , m_boundInterfaceIdentifier(parameters.boundInterfaceIdentifier)
929     , m_sourceApplicationBundleIdentifier(parameters.sourceApplicationBundleIdentifier)
930     , m_sourceApplicationSecondaryIdentifier(parameters.sourceApplicationSecondaryIdentifier)
931     , m_proxyConfiguration(parameters.proxyConfiguration)
932     , m_shouldLogCookieInformation(parameters.shouldLogCookieInformation)
933     , m_loadThrottleLatency(parameters.loadThrottleLatency)
934 {
935     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
936
937 #if !ASSERT_DISABLED
938     sessionsCreated = true;
939 #endif
940
941     NSURLSessionConfiguration *configuration = configurationForSessionID(m_sessionID);
942
943 #if HAVE(APP_SSO)
944     configuration._preventsAppSSO = true;
945 #endif
946
947 #if USE(CFNETWORK_AUTO_ADDED_HTTP_HEADER_SUPPRESSION)
948     // Without this, CFNetwork would sometimes add a Content-Type header to our requests (rdar://problem/34748470).
949     configuration._suppressedAutoAddedHTTPHeaders = [NSSet setWithObject:@"Content-Type"];
950 #endif
951
952     if (parameters.allowsCellularAccess == AllowsCellularAccess::No)
953         configuration.allowsCellularAccess = NO;
954
955     // The WebKit network cache was already queried.
956     configuration.URLCache = nil;
957
958     if (auto data = networkProcess.sourceApplicationAuditData())
959         configuration._sourceApplicationAuditTokenData = (__bridge NSData *)data.get();
960
961     if (!m_sourceApplicationBundleIdentifier.isEmpty()) {
962         configuration._sourceApplicationBundleIdentifier = m_sourceApplicationBundleIdentifier;
963         configuration._sourceApplicationAuditTokenData = nil;
964     }
965
966     if (!m_sourceApplicationSecondaryIdentifier.isEmpty())
967         configuration._sourceApplicationSecondaryIdentifier = m_sourceApplicationSecondaryIdentifier;
968
969     configuration.connectionProxyDictionary = proxyDictionary(parameters.httpProxy, parameters.httpsProxy);
970
971 #if PLATFORM(IOS_FAMILY)
972     auto& ctDataConnectionServiceType = globalCTDataConnectionServiceType();
973     if (!ctDataConnectionServiceType.isEmpty())
974         configuration._CTDataConnectionServiceType = ctDataConnectionServiceType;
975 #endif
976
977 #if ENABLE(LEGACY_CUSTOM_PROTOCOL_MANAGER)
978     networkProcess.supplement<LegacyCustomProtocolManager>()->registerProtocolClass(configuration);
979 #endif
980
981 #if HAVE(TIMINGDATAOPTIONS)
982     configuration._timingDataOptions = _TimingDataOptionsEnableW3CNavigationTiming;
983 #else
984     setCollectsTimingData();
985 #endif
986
987 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || (PLATFORM(IOS_FAMILY) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 120000)
988     // FIXME: Replace @"kCFStreamPropertyAutoErrorOnSystemChange" with a constant from the SDK once rdar://problem/40650244 is in a build.
989     if (networkProcess.suppressesConnectionTerminationOnSystemChange())
990         configuration._socketStreamProperties = @{ @"kCFStreamPropertyAutoErrorOnSystemChange" : @NO };
991 #endif
992
993 #if PLATFORM(WATCHOS) && __WATCH_OS_VERSION_MIN_REQUIRED >= 60000
994     configuration._companionProxyPreference = NSURLSessionCompanionProxyPreferencePreferDirectToCloud;
995 #endif
996
997     static SEL allowsTLSFallbackSetter = NSSelectorFromString(@"set_allowsTLSFallback:");
998     if (parameters.allowsTLSFallback == AllowsTLSFallback::No && [configuration respondsToSelector:allowsTLSFallbackSetter])
999         wtfObjCMsgSend<void>(configuration, allowsTLSFallbackSetter, NO);
1000
1001     auto* storageSession = networkProcess.storageSession(parameters.sessionID);
1002     RELEASE_ASSERT(storageSession);
1003
1004     NSHTTPCookieStorage* cookieStorage;
1005     if (CFHTTPCookieStorageRef storage = storageSession->cookieStorage().get()) {
1006         cookieStorage = [[[NSHTTPCookieStorage alloc] _initWithCFHTTPCookieStorage:storage] autorelease];
1007         configuration.HTTPCookieStorage = cookieStorage;
1008     } else
1009         cookieStorage = storageSession->nsCookieStorage();
1010
1011 #if HAVE(CFNETWORK_OVERRIDE_SESSION_COOKIE_ACCEPT_POLICY)
1012     // We still need to check the selector since CFNetwork updates and WebKit updates are separate
1013     // on older macOS.
1014     if ([cookieStorage respondsToSelector:@selector(_overrideSessionCookieAcceptPolicy)])
1015         cookieStorage._overrideSessionCookieAcceptPolicy = YES;
1016 #endif
1017
1018     m_sessionWithCredentialStorageDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:true]);
1019     m_sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1020     LOG(NetworkSession, "Created NetworkSession with cookieAcceptPolicy %lu", configuration.HTTPCookieStorage.cookieAcceptPolicy);
1021
1022     configuration.URLCredentialStorage = nil;
1023     configuration._shouldSkipPreferredClientCertificateLookup = YES;
1024     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=177394
1025     // configuration.HTTPCookieStorage = nil;
1026     // configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
1027
1028     m_statelessSessionDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:false]);
1029     m_statelessSession = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1030
1031     m_deviceManagementRestrictionsEnabled = parameters.deviceManagementRestrictionsEnabled;
1032     m_allLoadsBlockedByDeviceManagementRestrictionsForTesting = parameters.allLoadsBlockedByDeviceManagementRestrictionsForTesting;
1033
1034 #if ENABLE(RESOURCE_LOAD_STATISTICS)
1035     m_resourceLoadStatisticsDirectory = parameters.resourceLoadStatisticsDirectory;
1036     m_shouldIncludeLocalhostInResourceLoadStatistics = parameters.shouldIncludeLocalhostInResourceLoadStatistics ? ShouldIncludeLocalhost::Yes : ShouldIncludeLocalhost::No;
1037     m_enableResourceLoadStatisticsDebugMode = parameters.enableResourceLoadStatisticsDebugMode ? EnableResourceLoadStatisticsDebugMode::Yes : EnableResourceLoadStatisticsDebugMode::No;
1038     m_resourceLoadStatisticsManualPrevalentResource = parameters.resourceLoadStatisticsManualPrevalentResource;
1039     m_enableResourceLoadStatisticsNSURLSessionSwitching = parameters.enableResourceLoadStatisticsNSURLSessionSwitching ? EnableResourceLoadStatisticsNSURLSessionSwitching::Yes : EnableResourceLoadStatisticsNSURLSessionSwitching::No;
1040     setResourceLoadStatisticsEnabled(parameters.enableResourceLoadStatistics);
1041 #endif
1042
1043 #if HAVE(SESSION_CLEANUP)
1044     activateSessionCleanup(*this);
1045 #endif
1046 }
1047
1048 NetworkSessionCocoa::~NetworkSessionCocoa()
1049 {
1050 }
1051
1052 void NetworkSessionCocoa::initializeEphemeralStatelessCookielessSession()
1053 {
1054     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
1055     NSURLSessionConfiguration *existingConfiguration = m_statelessSession.get().configuration;
1056
1057     configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
1058     configuration.URLCredentialStorage = nil;
1059     configuration.URLCache = nil;
1060     configuration.allowsCellularAccess = existingConfiguration.allowsCellularAccess;
1061     configuration.connectionProxyDictionary = existingConfiguration.connectionProxyDictionary;
1062
1063     configuration._shouldSkipPreferredClientCertificateLookup = YES;
1064     configuration._sourceApplicationAuditTokenData = existingConfiguration._sourceApplicationAuditTokenData;
1065     configuration._sourceApplicationSecondaryIdentifier = existingConfiguration._sourceApplicationSecondaryIdentifier;
1066 #if PLATFORM(IOS_FAMILY)
1067     configuration._CTDataConnectionServiceType = existingConfiguration._CTDataConnectionServiceType;
1068 #endif
1069
1070     m_ephemeralStatelessCookielessSessionDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:false]);
1071     m_ephemeralStatelessCookielessSession = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_ephemeralStatelessCookielessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1072 }
1073
1074 NSURLSession* NetworkSessionCocoa::session(WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
1075 {
1076     switch (storedCredentialsPolicy) {
1077     case WebCore::StoredCredentialsPolicy::Use:
1078         return m_sessionWithCredentialStorage.get();
1079     case WebCore::StoredCredentialsPolicy::DoNotUse:
1080         return m_statelessSession.get();
1081     case WebCore::StoredCredentialsPolicy::EphemeralStatelessCookieless:
1082         if (!m_ephemeralStatelessCookielessSession)
1083             initializeEphemeralStatelessCookielessSession();
1084         return m_ephemeralStatelessCookielessSession.get();
1085     }
1086 }
1087
1088 NSURLSession* NetworkSessionCocoa::isolatedSession(WebCore::StoredCredentialsPolicy storedCredentialsPolicy, const WebCore::RegistrableDomain firstPartyDomain)
1089 {
1090     auto entry = m_isolatedSessions.ensure(firstPartyDomain, [this] {
1091         IsolatedSession newEntry { };
1092         newEntry.sessionWithCredentialStorageDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:true]);
1093         newEntry.sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:m_sessionWithCredentialStorage.get().configuration delegate:static_cast<id>(newEntry.sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1094
1095         newEntry.statelessSessionDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:false]);
1096         newEntry.statelessSession = [NSURLSession sessionWithConfiguration:m_statelessSession.get().configuration delegate:static_cast<id>(newEntry.statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1097
1098         return newEntry;
1099     }).iterator->value;
1100
1101     entry.lastUsed = WallTime::now();
1102
1103     if (m_isolatedSessions.size() > maxNumberOfIsolatedSessions) {
1104         WebCore::RegistrableDomain keyToRemove;
1105         auto oldestTimestamp = WallTime::now();
1106         for (auto& key : m_isolatedSessions.keys()) {
1107             auto timestamp = m_isolatedSessions.get(key).lastUsed;
1108             if (timestamp < oldestTimestamp) {
1109                 oldestTimestamp = timestamp;
1110                 keyToRemove = key;
1111             }
1112         }
1113         LOG(NetworkSession, "About to remove isolated NSURLSession.");
1114         m_isolatedSessions.remove(keyToRemove);
1115     }
1116
1117     RELEASE_ASSERT(m_isolatedSessions.size() <= maxNumberOfIsolatedSessions);
1118
1119     switch (storedCredentialsPolicy) {
1120     case WebCore::StoredCredentialsPolicy::Use:
1121         LOG(NetworkSession, "Using isolated NSURLSession with credential storage.");
1122         return entry.sessionWithCredentialStorage.get();
1123     case WebCore::StoredCredentialsPolicy::DoNotUse:
1124         LOG(NetworkSession, "Using isolated NSURLSession without credential storage.");
1125         return entry.statelessSession.get();
1126     case WebCore::StoredCredentialsPolicy::EphemeralStatelessCookieless:
1127         if (!m_ephemeralStatelessCookielessSession)
1128             initializeEphemeralStatelessCookielessSession();
1129         return m_ephemeralStatelessCookielessSession.get();
1130     }
1131 }
1132
1133 bool NetworkSessionCocoa::hasIsolatedSession(const WebCore::RegistrableDomain domain) const
1134 {
1135     return m_isolatedSessions.contains(domain);
1136 }
1137
1138 void NetworkSessionCocoa::clearIsolatedSessions()
1139 {
1140     m_isolatedSessions.clear();
1141 }
1142
1143 void NetworkSessionCocoa::invalidateAndCancel()
1144 {
1145     NetworkSession::invalidateAndCancel();
1146
1147     [m_sessionWithCredentialStorage invalidateAndCancel];
1148     [m_statelessSession invalidateAndCancel];
1149     [m_ephemeralStatelessCookielessSession invalidateAndCancel];
1150     [m_sessionWithCredentialStorageDelegate sessionInvalidated];
1151     [m_statelessSessionDelegate sessionInvalidated];
1152     [m_ephemeralStatelessCookielessSessionDelegate sessionInvalidated];
1153
1154     for (auto& session : m_isolatedSessions.values()) {
1155         [session.sessionWithCredentialStorage invalidateAndCancel];
1156         [session.sessionWithCredentialStorageDelegate sessionInvalidated];
1157     }
1158     m_isolatedSessions.clear();
1159 }
1160
1161 void NetworkSessionCocoa::clearCredentials()
1162 {
1163 #if !USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
1164     ASSERT(m_dataTaskMapWithCredentials.isEmpty());
1165     ASSERT(m_dataTaskMapWithoutState.isEmpty());
1166     ASSERT(m_downloadMap.isEmpty());
1167     // FIXME: Use resetWithCompletionHandler instead.
1168     m_sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:m_sessionWithCredentialStorage.get().configuration delegate:static_cast<id>(m_sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1169     m_statelessSession = [NSURLSession sessionWithConfiguration:m_statelessSession.get().configuration delegate:static_cast<id>(m_statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1170     for (auto& entry : m_isolatedSessions.values())
1171         entry.session = [NSURLSession sessionWithConfiguration:entry.session.get().configuration delegate:static_cast<id>(entry.delegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
1172 #endif
1173 }
1174
1175 NetworkDataTaskCocoa* NetworkSessionCocoa::dataTaskForIdentifier(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
1176 {
1177     ASSERT(RunLoop::isMain());
1178     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use)
1179         return m_dataTaskMapWithCredentials.get(taskIdentifier);
1180     return m_dataTaskMapWithoutState.get(taskIdentifier);
1181 }
1182
1183 NSURLSessionDownloadTask* NetworkSessionCocoa::downloadTaskWithResumeData(NSData* resumeData)
1184 {
1185     return [m_sessionWithCredentialStorage downloadTaskWithResumeData:resumeData];
1186 }
1187
1188 void NetworkSessionCocoa::addDownloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, DownloadID downloadID)
1189 {
1190 #ifndef NDEBUG
1191     ASSERT(!m_downloadMap.contains(taskIdentifier));
1192     for (auto idInMap : m_downloadMap.values())
1193         ASSERT(idInMap != downloadID);
1194 #endif
1195     m_downloadMap.add(taskIdentifier, downloadID);
1196 }
1197
1198 DownloadID NetworkSessionCocoa::downloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier)
1199 {
1200     ASSERT(m_downloadMap.get(taskIdentifier).downloadID());
1201     return m_downloadMap.get(taskIdentifier);
1202 }
1203
1204 DownloadID NetworkSessionCocoa::takeDownloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier)
1205 {
1206     auto downloadID = m_downloadMap.take(taskIdentifier);
1207     return downloadID;
1208 }
1209
1210 static bool certificatesMatch(SecTrustRef trust1, SecTrustRef trust2)
1211 {
1212     if (!trust1 || !trust2)
1213         return false;
1214
1215     CFIndex count1 = SecTrustGetCertificateCount(trust1);
1216     CFIndex count2 = SecTrustGetCertificateCount(trust2);
1217     if (count1 != count2)
1218         return false;
1219
1220     for (CFIndex i = 0; i < count1; i++) {
1221         auto cert1 = SecTrustGetCertificateAtIndex(trust1, i);
1222         auto cert2 = SecTrustGetCertificateAtIndex(trust2, i);
1223         RELEASE_ASSERT(cert1);
1224         RELEASE_ASSERT(cert2);
1225         if (!CFEqual(cert1, cert2))
1226             return false;
1227     }
1228
1229     return true;
1230 }
1231
1232 bool NetworkSessionCocoa::allowsSpecificHTTPSCertificateForHost(const WebCore::AuthenticationChallenge& challenge)
1233 {
1234     const String& host = challenge.protectionSpace().host();
1235     NSArray *certificates = [NSURLRequest allowsSpecificHTTPSCertificateForHost:host];
1236     if (!certificates)
1237         return false;
1238
1239     bool requireServerCertificates = challenge.protectionSpace().authenticationScheme() == WebCore::ProtectionSpaceAuthenticationScheme::ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested;
1240     RetainPtr<SecPolicyRef> policy = adoptCF(SecPolicyCreateSSL(requireServerCertificates, host.createCFString().get()));
1241
1242     SecTrustRef trustRef = nullptr;
1243     if (SecTrustCreateWithCertificates((CFArrayRef)certificates, policy.get(), &trustRef) != noErr)
1244         return false;
1245     RetainPtr<SecTrustRef> trust = adoptCF(trustRef);
1246
1247     return certificatesMatch(trust.get(), challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust);
1248 }
1249
1250 void NetworkSessionCocoa::continueDidReceiveChallenge(const WebCore::AuthenticationChallenge& challenge, NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, NetworkDataTaskCocoa* networkDataTask, CompletionHandler<void(WebKit::AuthenticationChallengeDisposition, const WebCore::Credential&)>&& completionHandler)
1251 {
1252     if (!networkDataTask) {
1253 #if HAVE(NSURLSESSION_WEBSOCKET)
1254         if (auto* webSocketTask = webSocketDataTaskForIdentifier(taskIdentifier)) {
1255             // FIXME: Handle challenges for web socket.
1256             completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
1257             return;
1258         }
1259 #endif
1260
1261         auto downloadID = this->downloadID(taskIdentifier);
1262         if (downloadID.downloadID()) {
1263             if (auto* download = networkProcess().downloadManager().download(downloadID)) {
1264                 WebCore::AuthenticationChallenge authenticationChallenge { challenge };
1265                 // Received an authentication challenge for a download being resumed.
1266                 download->didReceiveChallenge(authenticationChallenge, WTFMove(completionHandler));
1267                 return;
1268             }
1269         }
1270         LOG(NetworkSession, "%llu didReceiveChallenge completionHandler (cancel)", taskIdentifier);
1271         completionHandler(AuthenticationChallengeDisposition::Cancel, { });
1272         return;
1273     }
1274
1275     auto sessionID = this->sessionID();
1276     WebCore::AuthenticationChallenge authenticationChallenge { challenge };
1277     auto challengeCompletionHandler = [completionHandler = WTFMove(completionHandler), networkProcess = makeRef(networkProcess()), sessionID, authenticationChallenge, taskIdentifier, partition = networkDataTask->partition()](WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential) mutable {
1278 #if !LOG_DISABLED
1279         LOG(NetworkSession, "%llu didReceiveChallenge completionHandler %d", taskIdentifier, disposition);
1280 #else
1281         UNUSED_PARAM(taskIdentifier);
1282 #endif
1283 #if !USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
1284         UNUSED_PARAM(sessionID);
1285         UNUSED_PARAM(authenticationChallenge);
1286 #else
1287         if (credential.persistence() == WebCore::CredentialPersistenceForSession && authenticationChallenge.protectionSpace().isPasswordBased()) {
1288             WebCore::Credential nonPersistentCredential(credential.user(), credential.password(), WebCore::CredentialPersistenceNone);
1289             URL urlToStore;
1290             if (authenticationChallenge.failureResponse().httpStatusCode() == 401)
1291                 urlToStore = authenticationChallenge.failureResponse().url();
1292             if (auto storageSession = networkProcess->storageSession(sessionID))
1293                 storageSession->credentialStorage().set(partition, nonPersistentCredential, authenticationChallenge.protectionSpace(), urlToStore);
1294             else
1295                 ASSERT_NOT_REACHED();
1296
1297             completionHandler(disposition, nonPersistentCredential);
1298             return;
1299         }
1300 #endif
1301         completionHandler(disposition, credential);
1302     };
1303     networkDataTask->didReceiveChallenge(WTFMove(authenticationChallenge), WTFMove(challengeCompletionHandler));
1304 }
1305
1306 DMFWebsitePolicyMonitor *NetworkSessionCocoa::deviceManagementPolicyMonitor()
1307 {
1308 #if HAVE(DEVICE_MANAGEMENT)
1309     ASSERT(m_deviceManagementRestrictionsEnabled);
1310     if (!m_deviceManagementPolicyMonitor)
1311         m_deviceManagementPolicyMonitor = adoptNS([allocDMFWebsitePolicyMonitorInstance() initWithPolicyChangeHandler:nil]);
1312     return m_deviceManagementPolicyMonitor.get();
1313 #else
1314     RELEASE_ASSERT_NOT_REACHED();
1315     return nil;
1316 #endif
1317 }
1318
1319 #if HAVE(NSURLSESSION_WEBSOCKET)
1320 std::unique_ptr<WebSocketTask> NetworkSessionCocoa::createWebSocketTask(NetworkSocketChannel& channel, const WebCore::ResourceRequest& request, const String& protocol)
1321 {
1322     // FIXME: Use protocol.
1323     RetainPtr<NSURLSessionWebSocketTask> task = [m_sessionWithCredentialStorage.get() webSocketTaskWithRequest: request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::DoNotUpdateHTTPBody)];
1324     return std::make_unique<WebSocketTask>(channel, WTFMove(task));
1325 }
1326
1327 void NetworkSessionCocoa::addWebSocketTask(WebSocketTask& task)
1328 {
1329     ASSERT(!m_webSocketDataTaskMap.contains(task.identifier()));
1330     m_webSocketDataTaskMap.add(task.identifier(), &task);
1331 }
1332
1333 void NetworkSessionCocoa::removeWebSocketTask(WebSocketTask& task)
1334 {
1335     ASSERT(m_webSocketDataTaskMap.contains(task.identifier()));
1336     m_webSocketDataTaskMap.remove(task.identifier());
1337 }
1338
1339 WebSocketTask* NetworkSessionCocoa::webSocketDataTaskForIdentifier(WebSocketTask::TaskIdentifier identifier)
1340 {
1341     return m_webSocketDataTaskMap.get(identifier);
1342 }
1343
1344 #endif
1345 }