05c86848e2544c18356f1bfa5605afc1104562f2
[WebKit-https.git] / Source / WebKit / NetworkProcess / cocoa / NetworkSessionCocoa.mm
1 /*
2  * Copyright (C) 2015-2017 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 #if USE(NETWORK_SESSION)
30
31 #import "AuthenticationManager.h"
32 #import "DataReference.h"
33 #import "Download.h"
34 #import "LegacyCustomProtocolManager.h"
35 #import "Logging.h"
36 #import "NetworkLoad.h"
37 #import "NetworkProcess.h"
38 #import "NetworkSessionCreationParameters.h"
39 #import "SessionTracker.h"
40 #import <Foundation/NSURLSession.h>
41 #import <WebCore/Credential.h>
42 #import <WebCore/FormDataStreamMac.h>
43 #import <WebCore/FrameLoaderTypes.h>
44 #import <WebCore/NetworkStorageSession.h>
45 #import <WebCore/NotImplemented.h>
46 #import <WebCore/ResourceError.h>
47 #import <WebCore/ResourceRequest.h>
48 #import <WebCore/ResourceResponse.h>
49 #import <WebCore/SharedBuffer.h>
50 #import <WebCore/URL.h>
51 #import <WebCore/WebCoreURLResponse.h>
52 #import <pal/spi/cf/CFNetworkSPI.h>
53 #import <wtf/MainThread.h>
54 #import <wtf/NeverDestroyed.h>
55
56 using namespace WebKit;
57
58 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
59 @interface NSURLSessionConfiguration (WKStaging)
60 @property (nullable, copy) NSSet *_suppressedAutoAddedHTTPHeaders;
61 @end
62 #endif
63
64 static NSURLSessionResponseDisposition toNSURLSessionResponseDisposition(WebCore::PolicyAction disposition)
65 {
66     switch (disposition) {
67     case WebCore::PolicyAction::Ignore:
68         return NSURLSessionResponseCancel;
69     case WebCore::PolicyAction::Use:
70         return NSURLSessionResponseAllow;
71     case WebCore::PolicyAction::Download:
72         return NSURLSessionResponseBecomeDownload;
73     }
74 }
75
76 static NSURLSessionAuthChallengeDisposition toNSURLSessionAuthChallengeDisposition(WebKit::AuthenticationChallengeDisposition disposition)
77 {
78     switch (disposition) {
79     case WebKit::AuthenticationChallengeDisposition::UseCredential:
80         return NSURLSessionAuthChallengeUseCredential;
81     case WebKit::AuthenticationChallengeDisposition::PerformDefaultHandling:
82         return NSURLSessionAuthChallengePerformDefaultHandling;
83     case WebKit::AuthenticationChallengeDisposition::Cancel:
84         return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
85     case WebKit::AuthenticationChallengeDisposition::RejectProtectionSpace:
86         return NSURLSessionAuthChallengeRejectProtectionSpace;
87     }
88 }
89
90 static WebCore::NetworkLoadPriority toNetworkLoadPriority(float priority)
91 {
92     if (priority <= NSURLSessionTaskPriorityLow)
93         return WebCore::NetworkLoadPriority::Low;
94     if (priority >= NSURLSessionTaskPriorityHigh)
95         return WebCore::NetworkLoadPriority::High;
96     return WebCore::NetworkLoadPriority::Medium;
97 }
98
99 @interface WKNetworkSessionDelegate : NSObject <NSURLSessionDataDelegate> {
100     RefPtr<WebKit::NetworkSessionCocoa> _session;
101     bool _withCredentials;
102 }
103
104 - (id)initWithNetworkSession:(WebKit::NetworkSessionCocoa&)session withCredentials:(bool)withCredentials;
105 - (void)sessionInvalidated;
106
107 @end
108
109 @implementation WKNetworkSessionDelegate
110
111 - (id)initWithNetworkSession:(WebKit::NetworkSessionCocoa&)session withCredentials:(bool)withCredentials
112 {
113     self = [super init];
114     if (!self)
115         return nil;
116
117     _session = &session;
118     _withCredentials = withCredentials;
119
120     return self;
121 }
122
123 - (void)sessionInvalidated
124 {
125     _session = nullptr;
126 }
127
128 - (NetworkDataTaskCocoa*)existingTask:(NSURLSessionTask *)task
129 {
130     if (!_session)
131         return nullptr;
132
133     if (!task)
134         return nullptr;
135
136     auto storedCredentialsPolicy = _withCredentials ? WebCore::StoredCredentialsPolicy::Use : WebCore::StoredCredentialsPolicy::DoNotUse;
137     return _session->dataTaskForIdentifier(task.taskIdentifier, storedCredentialsPolicy);
138 }
139
140 - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
141 {
142     ASSERT(!_session);
143 }
144
145 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
146 {
147     if (auto* networkDataTask = [self existingTask:task])
148         networkDataTask->didSendData(totalBytesSent, totalBytesExpectedToSend);
149 }
150
151 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
152 {
153     auto* networkDataTask = [self existingTask:task];
154     if (!networkDataTask) {
155         completionHandler(nil);
156         return;
157     }
158
159     auto* body = networkDataTask->firstRequest().httpBody();
160     if (!body) {
161         completionHandler(nil);
162         return;
163     }
164
165     completionHandler(WebCore::createHTTPBodyNSInputStream(*body).get());
166 }
167
168 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler
169 {
170     auto taskIdentifier = task.taskIdentifier;
171     LOG(NetworkSession, "%llu willPerformHTTPRedirection from %s to %s", taskIdentifier, response.URL.absoluteString.UTF8String, request.URL.absoluteString.UTF8String);
172
173     if (auto* networkDataTask = [self existingTask:task]) {
174         auto completionHandlerCopy = Block_copy(completionHandler);
175         networkDataTask->willPerformHTTPRedirection(response, request, [completionHandlerCopy, taskIdentifier](auto& request) {
176 #if !LOG_DISABLED
177             LOG(NetworkSession, "%llu willPerformHTTPRedirection completionHandler (%s)", taskIdentifier, request.url().string().utf8().data());
178 #else
179             UNUSED_PARAM(taskIdentifier);
180 #endif
181             completionHandlerCopy(request.nsURLRequest(WebCore::UpdateHTTPBody));
182             Block_release(completionHandlerCopy);
183         });
184     } else {
185         LOG(NetworkSession, "%llu willPerformHTTPRedirection completionHandler (nil)", taskIdentifier);
186         completionHandler(nil);
187     }
188 }
189
190 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask*)task _schemeUpgraded:(NSURLRequest*)request completionHandler:(void (^)(NSURLRequest*))completionHandler
191 {
192     auto taskIdentifier = task.taskIdentifier;
193     LOG(NetworkSession, "%llu _schemeUpgraded %s", taskIdentifier, request.URL.absoluteString.UTF8String);
194     
195     if (auto* networkDataTask = [self existingTask:task]) {
196         auto completionHandlerCopy = Block_copy(completionHandler);
197         networkDataTask->willPerformHTTPRedirection(WebCore::synthesizeRedirectResponseIfNecessary([task currentRequest], request, nil), request, [completionHandlerCopy, taskIdentifier](auto& request) {
198 #if !LOG_DISABLED
199             LOG(NetworkSession, "%llu _schemeUpgraded completionHandler (%s)", taskIdentifier, request.url().string().utf8().data());
200 #else
201             UNUSED_PARAM(taskIdentifier);
202 #endif
203             completionHandlerCopy(request.nsURLRequest(WebCore::UpdateHTTPBody));
204             Block_release(completionHandlerCopy);
205         });
206     } else {
207         LOG(NetworkSession, "%llu _schemeUpgraded completionHandler (nil)", taskIdentifier);
208         completionHandler(nil);
209     }
210 }
211
212 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse * _Nullable cachedResponse))completionHandler
213 {
214     if (!_session) {
215         completionHandler(nil);
216         return;
217     }
218
219     // FIXME: remove if <rdar://problem/20001985> is ever resolved.
220     if ([proposedResponse.response respondsToSelector:@selector(allHeaderFields)]
221         && [[(id)proposedResponse.response allHeaderFields] objectForKey:@"Content-Range"])
222         completionHandler(nil);
223     else
224         completionHandler(proposedResponse);
225 }
226
227 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
228 {
229     auto taskIdentifier = task.taskIdentifier;
230     LOG(NetworkSession, "%llu didReceiveChallenge", taskIdentifier);
231     
232     // Proxy authentication is handled by CFNetwork internally. We can get here if the user cancels
233     // CFNetwork authentication dialog, and we shouldn't ask the client to display another one in that case.
234     if (challenge.protectionSpace.isProxy) {
235         completionHandler(NSURLSessionAuthChallengeUseCredential, nil);
236         return;
237     }
238
239     // Handle server trust evaluation at platform-level if requested, for performance reasons.
240     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust] && !NetworkProcess::singleton().canHandleHTTPSServerTrustEvaluation()) {
241         if (NetworkSessionCocoa::allowsSpecificHTTPSCertificateForHost(challenge))
242             completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
243         else
244             completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil);
245         return;
246     }
247
248     if (auto* networkDataTask = [self existingTask:task]) {
249         WebCore::AuthenticationChallenge authenticationChallenge(challenge);
250         auto completionHandlerCopy = Block_copy(completionHandler);
251         auto sessionID = _session->sessionID();
252         auto challengeCompletionHandler = [completionHandlerCopy, sessionID, authenticationChallenge, taskIdentifier, partition = networkDataTask->partition()](WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential)
253         {
254 #if !LOG_DISABLED
255             LOG(NetworkSession, "%llu didReceiveChallenge completionHandler %d", taskIdentifier, disposition);
256 #else
257             UNUSED_PARAM(taskIdentifier);
258 #endif
259 #if !USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
260             UNUSED_PARAM(sessionID);
261             UNUSED_PARAM(authenticationChallenge);
262 #else
263             if (credential.persistence() == WebCore::CredentialPersistenceForSession && authenticationChallenge.protectionSpace().isPasswordBased()) {
264
265                 WebCore::Credential nonPersistentCredential(credential.user(), credential.password(), WebCore::CredentialPersistenceNone);
266                 WebCore::URL urlToStore;
267                 if (authenticationChallenge.failureResponse().httpStatusCode() == 401)
268                     urlToStore = authenticationChallenge.failureResponse().url();
269                 if (auto storageSession = WebCore::NetworkStorageSession::storageSession(sessionID))
270                     storageSession->credentialStorage().set(partition, nonPersistentCredential, authenticationChallenge.protectionSpace(), urlToStore);
271                 else
272                     ASSERT_NOT_REACHED();
273
274                 completionHandlerCopy(toNSURLSessionAuthChallengeDisposition(disposition), nonPersistentCredential.nsCredential());
275             } else
276 #endif
277                 completionHandlerCopy(toNSURLSessionAuthChallengeDisposition(disposition), credential.nsCredential());
278             Block_release(completionHandlerCopy);
279         };
280         networkDataTask->didReceiveChallenge(challenge, WTFMove(challengeCompletionHandler));
281     } else {
282         auto downloadID = _session->downloadID(task.taskIdentifier);
283         if (downloadID.downloadID()) {
284             if (auto* download = WebKit::NetworkProcess::singleton().downloadManager().download(downloadID)) {
285                 // Received an authentication challenge for a download being resumed.
286                 WebCore::AuthenticationChallenge authenticationChallenge { challenge };
287                 auto completionHandlerCopy = Block_copy(completionHandler);
288                 auto challengeCompletionHandler = [completionHandlerCopy, authenticationChallenge](WebKit::AuthenticationChallengeDisposition disposition, const WebCore::Credential& credential) {
289                     completionHandlerCopy(toNSURLSessionAuthChallengeDisposition(disposition), credential.nsCredential());
290                     Block_release(completionHandlerCopy);
291                 };
292                 download->didReceiveChallenge(challenge, WTFMove(challengeCompletionHandler));
293                 return;
294             }
295         }
296         LOG(NetworkSession, "%llu didReceiveChallenge completionHandler (cancel)", taskIdentifier);
297         completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
298     }
299 }
300
301 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
302 {
303     if (!_session)
304         return;
305
306     LOG(NetworkSession, "%llu didCompleteWithError %@", task.taskIdentifier, error);
307     if (auto* networkDataTask = [self existingTask:task])
308         networkDataTask->didCompleteWithError(error, networkDataTask->networkLoadMetrics());
309     else if (error) {
310         auto downloadID = _session->takeDownloadID(task.taskIdentifier);
311         if (downloadID.downloadID()) {
312             if (auto* download = WebKit::NetworkProcess::singleton().downloadManager().download(downloadID)) {
313                 NSData *resumeData = nil;
314                 if (id userInfo = error.userInfo) {
315                     if ([userInfo isKindOfClass:[NSDictionary class]])
316                         resumeData = userInfo[@"NSURLSessionDownloadTaskResumeData"];
317                 }
318                 
319                 if (resumeData && [resumeData isKindOfClass:[NSData class]])
320                     download->didFail(error, { static_cast<const uint8_t*>(resumeData.bytes), resumeData.length });
321                 else
322                     download->didFail(error, { });
323             }
324         }
325     }
326 }
327
328 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics
329 {
330     LOG(NetworkSession, "%llu didFinishCollectingMetrics", task.taskIdentifier);
331     if (auto* networkDataTask = [self existingTask:task]) {
332         NSURLSessionTaskTransactionMetrics *m = metrics.transactionMetrics.lastObject;
333         NSDate *fetchStartDate = m.fetchStartDate;
334         NSTimeInterval domainLookupStartInterval = m.domainLookupStartDate ? [m.domainLookupStartDate timeIntervalSinceDate:fetchStartDate] : -1;
335         NSTimeInterval domainLookupEndInterval = m.domainLookupEndDate ? [m.domainLookupEndDate timeIntervalSinceDate:fetchStartDate] : -1;
336         NSTimeInterval connectStartInterval = m.connectStartDate ? [m.connectStartDate timeIntervalSinceDate:fetchStartDate] : -1;
337         NSTimeInterval secureConnectionStartInterval = m.secureConnectionStartDate ? [m.secureConnectionStartDate timeIntervalSinceDate:fetchStartDate] : -1;
338         NSTimeInterval connectEndInterval = m.connectEndDate ? [m.connectEndDate timeIntervalSinceDate:fetchStartDate] : -1;
339         NSTimeInterval requestStartInterval = [m.requestStartDate timeIntervalSinceDate:fetchStartDate];
340         NSTimeInterval responseStartInterval = [m.responseStartDate timeIntervalSinceDate:fetchStartDate];
341         NSTimeInterval responseEndInterval = [m.responseEndDate timeIntervalSinceDate:fetchStartDate];
342
343         auto& networkLoadMetrics = networkDataTask->networkLoadMetrics();
344         networkLoadMetrics.domainLookupStart = Seconds(domainLookupStartInterval);
345         networkLoadMetrics.domainLookupEnd = Seconds(domainLookupEndInterval);
346         networkLoadMetrics.connectStart = Seconds(connectStartInterval);
347         networkLoadMetrics.secureConnectionStart = Seconds(secureConnectionStartInterval);
348         networkLoadMetrics.connectEnd = Seconds(connectEndInterval);
349         networkLoadMetrics.requestStart = Seconds(requestStartInterval);
350         networkLoadMetrics.responseStart = Seconds(responseStartInterval);
351         networkLoadMetrics.responseEnd = Seconds(responseEndInterval);
352         networkLoadMetrics.markComplete();
353         networkLoadMetrics.protocol = String(m.networkProtocolName);
354
355         if (networkDataTask->shouldCaptureExtraNetworkLoadMetrics()) {
356             networkLoadMetrics.priority = toNetworkLoadPriority(task.priority);
357
358 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
359             networkLoadMetrics.remoteAddress = String(m._remoteAddressAndPort);
360             networkLoadMetrics.connectionIdentifier = String([m._connectionIdentifier UUIDString]);
361 #endif
362
363             __block WebCore::HTTPHeaderMap requestHeaders;
364             [m.request.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSString *value, BOOL *) {
365                 requestHeaders.set(String(name), String(value));
366             }];
367             networkLoadMetrics.requestHeaders = WTFMove(requestHeaders);
368
369 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
370             uint64_t requestHeaderBytesSent = 0;
371             uint64_t responseHeaderBytesReceived = 0;
372             uint64_t responseBodyBytesReceived = 0;
373             uint64_t responseBodyDecodedSize = 0;
374
375             for (NSURLSessionTaskTransactionMetrics *transactionMetrics in metrics.transactionMetrics) {
376                 requestHeaderBytesSent += transactionMetrics._requestHeaderBytesSent;
377                 responseHeaderBytesReceived += transactionMetrics._responseHeaderBytesReceived;
378                 responseBodyBytesReceived += transactionMetrics._responseBodyBytesReceived;
379                 responseBodyDecodedSize += transactionMetrics._responseBodyBytesDecoded ? transactionMetrics._responseBodyBytesDecoded : transactionMetrics._responseBodyBytesReceived;
380             }
381
382             networkLoadMetrics.requestHeaderBytesSent = requestHeaderBytesSent;
383             networkLoadMetrics.requestBodyBytesSent = task.countOfBytesSent;
384             networkLoadMetrics.responseHeaderBytesReceived = responseHeaderBytesReceived;
385             networkLoadMetrics.responseBodyBytesReceived = responseBodyBytesReceived;
386             networkLoadMetrics.responseBodyDecodedSize = responseBodyDecodedSize;
387 #endif
388         }
389     }
390 }
391
392 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
393 {
394     auto taskIdentifier = dataTask.taskIdentifier;
395     LOG(NetworkSession, "%llu didReceiveResponse", taskIdentifier);
396     if (auto* networkDataTask = [self existingTask:dataTask]) {
397         ASSERT(RunLoop::isMain());
398         
399         // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
400         int statusCode = [response respondsToSelector:@selector(statusCode)] ? [(id)response statusCode] : 0;
401         if (statusCode != 304) {
402             bool isMainResourceLoad = networkDataTask->firstRequest().requester() == WebCore::ResourceRequest::Requester::Main;
403             WebCore::adjustMIMETypeIfNecessary(response._CFURLResponse, isMainResourceLoad);
404         }
405
406         WebCore::ResourceResponse resourceResponse(response);
407         // Lazy initialization is not helpful in the WebKit2 case because we always end up initializing
408         // all the fields when sending the response to the WebContent process over IPC.
409         resourceResponse.disableLazyInitialization();
410
411         // FIXME: This cannot be eliminated until other code no longer relies on ResourceResponse's
412         // NetworkLoadMetrics. For example, PerformanceTiming.
413         copyTimingData([dataTask _timingData], resourceResponse.deprecatedNetworkLoadMetrics());
414
415         auto completionHandlerCopy = Block_copy(completionHandler);
416         networkDataTask->didReceiveResponse(WTFMove(resourceResponse), [completionHandlerCopy, taskIdentifier](WebCore::PolicyAction policyAction) {
417 #if !LOG_DISABLED
418             LOG(NetworkSession, "%llu didReceiveResponse completionHandler (%d)", taskIdentifier, policyAction);
419 #else
420             UNUSED_PARAM(taskIdentifier);
421 #endif
422             completionHandlerCopy(toNSURLSessionResponseDisposition(policyAction));
423             Block_release(completionHandlerCopy);
424         });
425     } else {
426         LOG(NetworkSession, "%llu didReceiveResponse completionHandler (cancel)", taskIdentifier);
427         completionHandler(NSURLSessionResponseCancel);
428     }
429 }
430
431 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
432 {
433     if (auto* networkDataTask = [self existingTask:dataTask])
434         networkDataTask->didReceiveData(WebCore::SharedBuffer::create(data));
435 }
436
437 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
438 {
439     if (!_session)
440         return;
441
442     auto downloadID = _session->takeDownloadID([downloadTask taskIdentifier]);
443     if (auto* download = WebKit::NetworkProcess::singleton().downloadManager().download(downloadID))
444         download->didFinish();
445 }
446
447 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
448 {
449     if (!_session)
450         return;
451
452     ASSERT_WITH_MESSAGE(![self existingTask:downloadTask], "The NetworkDataTask should be destroyed immediately after didBecomeDownloadTask returns");
453
454     auto downloadID = _session->downloadID([downloadTask taskIdentifier]);
455     if (auto* download = WebKit::NetworkProcess::singleton().downloadManager().download(downloadID))
456         download->didReceiveData(bytesWritten);
457 }
458
459 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
460 {
461     if (!_session)
462         return;
463
464     notImplemented();
465 }
466
467 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
468 {
469     if (auto* networkDataTask = [self existingTask:dataTask]) {
470         Ref<NetworkDataTaskCocoa> protectedNetworkDataTask(*networkDataTask);
471         auto downloadID = networkDataTask->pendingDownloadID();
472         auto& downloadManager = WebKit::NetworkProcess::singleton().downloadManager();
473         auto download = std::make_unique<WebKit::Download>(downloadManager, downloadID, downloadTask, _session->sessionID(), networkDataTask->suggestedFilename());
474         networkDataTask->transferSandboxExtensionToDownload(*download);
475         ASSERT(WebCore::fileExists(networkDataTask->pendingDownloadLocation()));
476         download->didCreateDestination(networkDataTask->pendingDownloadLocation());
477         downloadManager.dataTaskBecameDownloadTask(downloadID, WTFMove(download));
478
479         _session->addDownloadID([downloadTask taskIdentifier], downloadID);
480     }
481 }
482
483 @end
484
485 namespace WebKit {
486     
487 static bool usesNetworkCache { false };
488
489 #if !ASSERT_DISABLED
490 static bool sessionsCreated = false;
491 #endif
492
493 static NSURLSessionConfiguration *configurationForSessionID(const PAL::SessionID& session)
494 {
495     if (session.isEphemeral()) {
496         NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
497         configuration._shouldSkipPreferredClientCertificateLookup = YES;
498         return configuration;
499     }
500     return [NSURLSessionConfiguration defaultSessionConfiguration];
501 }
502
503 static RetainPtr<CFDataRef>& globalSourceApplicationAuditTokenData()
504 {
505     static NeverDestroyed<RetainPtr<CFDataRef>> sourceApplicationAuditTokenData;
506     return sourceApplicationAuditTokenData.get();
507 }
508
509 static String& globalSourceApplicationBundleIdentifier()
510 {
511     static NeverDestroyed<String> sourceApplicationBundleIdentifier;
512     return sourceApplicationBundleIdentifier.get();
513 }
514
515 static String& globalSourceApplicationSecondaryIdentifier()
516 {
517     static NeverDestroyed<String> sourceApplicationSecondaryIdentifier;
518     return sourceApplicationSecondaryIdentifier.get();
519 }
520
521 #if PLATFORM(IOS)
522 static String& globalCTDataConnectionServiceType()
523 {
524     static NeverDestroyed<String> ctDataConnectionServiceType;
525     return ctDataConnectionServiceType.get();
526 }
527 #endif
528     
529 void NetworkSessionCocoa::setSourceApplicationAuditTokenData(RetainPtr<CFDataRef>&& data)
530 {
531     ASSERT(!sessionsCreated);
532     globalSourceApplicationAuditTokenData() = data;
533 }
534
535 void NetworkSessionCocoa::setSourceApplicationBundleIdentifier(const String& identifier)
536 {
537     ASSERT(!sessionsCreated);
538     globalSourceApplicationBundleIdentifier() = identifier;
539 }
540
541 void NetworkSessionCocoa::setSourceApplicationSecondaryIdentifier(const String& identifier)
542 {
543     ASSERT(!sessionsCreated);
544     globalSourceApplicationSecondaryIdentifier() = identifier;
545 }
546
547 void NetworkSessionCocoa::setUsesNetworkCache(bool value)
548 {
549     usesNetworkCache = value;
550 }
551
552 #if PLATFORM(IOS)
553 void NetworkSessionCocoa::setCTDataConnectionServiceType(const String& type)
554 {
555     ASSERT(!sessionsCreated);
556     globalCTDataConnectionServiceType() = type;
557 }
558 #endif
559
560 Ref<NetworkSession> NetworkSessionCocoa::create(NetworkSessionCreationParameters&& parameters)
561 {
562     return adoptRef(*new NetworkSessionCocoa(WTFMove(parameters)));
563 }
564
565 NetworkSessionCocoa::NetworkSessionCocoa(NetworkSessionCreationParameters&& parameters)
566     : NetworkSession(parameters.sessionID)
567     , m_boundInterfaceIdentifier(parameters.boundInterfaceIdentifier)
568 {
569     relaxAdoptionRequirement();
570
571 #if !ASSERT_DISABLED
572     sessionsCreated = true;
573 #endif
574
575     NSURLSessionConfiguration *configuration = configurationForSessionID(m_sessionID);
576
577 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
578     // Without this, CFNetwork would sometimes add a Content-Type header to our requests (rdar://problem/34748470).
579     if ([configuration respondsToSelector:@selector(_suppressedAutoAddedHTTPHeaders)])
580         configuration._suppressedAutoAddedHTTPHeaders = [NSSet setWithObject:@"Content-Type"];
581 #endif
582
583     if (parameters.allowsCellularAccess == AllowsCellularAccess::No)
584         configuration.allowsCellularAccess = NO;
585
586     if (usesNetworkCache)
587         configuration.URLCache = nil;
588
589     if (auto& data = globalSourceApplicationAuditTokenData())
590         configuration._sourceApplicationAuditTokenData = (NSData *)data.get();
591
592     auto& sourceApplicationBundleIdentifier = globalSourceApplicationBundleIdentifier();
593     if (!sourceApplicationBundleIdentifier.isEmpty()) {
594         configuration._sourceApplicationBundleIdentifier = sourceApplicationBundleIdentifier;
595         configuration._sourceApplicationAuditTokenData = nil;
596     }
597
598     auto& sourceApplicationSecondaryIdentifier = globalSourceApplicationSecondaryIdentifier();
599     if (!sourceApplicationSecondaryIdentifier.isEmpty())
600         configuration._sourceApplicationSecondaryIdentifier = sourceApplicationSecondaryIdentifier;
601
602 #if PLATFORM(IOS)
603     auto& ctDataConnectionServiceType = globalCTDataConnectionServiceType();
604     if (!ctDataConnectionServiceType.isEmpty())
605         configuration._CTDataConnectionServiceType = ctDataConnectionServiceType;
606 #endif
607
608     if (parameters.legacyCustomProtocolManager)
609         parameters.legacyCustomProtocolManager->registerProtocolClass(configuration);
610     
611 #if HAVE(TIMINGDATAOPTIONS)
612     configuration._timingDataOptions = _TimingDataOptionsEnableW3CNavigationTiming;
613 #else
614     setCollectsTimingData();
615 #endif
616
617     auto* storageSession = WebCore::NetworkStorageSession::storageSession(parameters.sessionID);
618     RELEASE_ASSERT(storageSession);
619     if (CFHTTPCookieStorageRef storage = storageSession->cookieStorage().get())
620         configuration.HTTPCookieStorage = [[[NSHTTPCookieStorage alloc] _initWithCFHTTPCookieStorage:storage] autorelease];
621
622     m_sessionWithCredentialStorageDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:true]);
623     m_sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
624     LOG(NetworkSession, "Created NetworkSession with cookieAcceptPolicy %lu", configuration.HTTPCookieStorage.cookieAcceptPolicy);
625
626     configuration.URLCredentialStorage = nil;
627     configuration._shouldSkipPreferredClientCertificateLookup = YES;
628     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=177394
629     // configuration.HTTPCookieStorage = nil;
630     // configuration.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
631
632     m_statelessSessionDelegate = adoptNS([[WKNetworkSessionDelegate alloc] initWithNetworkSession:*this withCredentials:false]);
633     m_statelessSession = [NSURLSession sessionWithConfiguration:configuration delegate:static_cast<id>(m_statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
634 }
635
636 NetworkSessionCocoa::~NetworkSessionCocoa()
637 {
638 }
639
640 void NetworkSessionCocoa::invalidateAndCancel()
641 {
642     NetworkSession::invalidateAndCancel();
643
644     [m_sessionWithCredentialStorage invalidateAndCancel];
645     [m_statelessSession invalidateAndCancel];
646     [m_sessionWithCredentialStorageDelegate sessionInvalidated];
647     [m_statelessSessionDelegate sessionInvalidated];
648 }
649
650 void NetworkSessionCocoa::clearCredentials()
651 {
652 #if !USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
653     ASSERT(m_dataTaskMapWithCredentials.isEmpty());
654     ASSERT(m_dataTaskMapWithoutState.isEmpty());
655     ASSERT(m_downloadMap.isEmpty());
656     // FIXME: Use resetWithCompletionHandler instead.
657     m_sessionWithCredentialStorage = [NSURLSession sessionWithConfiguration:m_sessionWithCredentialStorage.get().configuration delegate:static_cast<id>(m_sessionWithCredentialStorageDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
658     m_statelessSession = [NSURLSession sessionWithConfiguration:m_statelessSession.get().configuration delegate:static_cast<id>(m_statelessSessionDelegate.get()) delegateQueue:[NSOperationQueue mainQueue]];
659 #endif
660 }
661
662 NetworkDataTaskCocoa* NetworkSessionCocoa::dataTaskForIdentifier(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, WebCore::StoredCredentialsPolicy storedCredentialsPolicy)
663 {
664     ASSERT(RunLoop::isMain());
665     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use)
666         return m_dataTaskMapWithCredentials.get(taskIdentifier);
667     return m_dataTaskMapWithoutState.get(taskIdentifier);
668 }
669
670 NSURLSessionDownloadTask* NetworkSessionCocoa::downloadTaskWithResumeData(NSData* resumeData)
671 {
672     return [m_sessionWithCredentialStorage downloadTaskWithResumeData:resumeData];
673 }
674
675 void NetworkSessionCocoa::addDownloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier, DownloadID downloadID)
676 {
677 #ifndef NDEBUG
678     ASSERT(!m_downloadMap.contains(taskIdentifier));
679     for (auto idInMap : m_downloadMap.values())
680         ASSERT(idInMap != downloadID);
681 #endif
682     m_downloadMap.add(taskIdentifier, downloadID);
683 }
684
685 DownloadID NetworkSessionCocoa::downloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier)
686 {
687     ASSERT(m_downloadMap.get(taskIdentifier).downloadID());
688     return m_downloadMap.get(taskIdentifier);
689 }
690
691 DownloadID NetworkSessionCocoa::takeDownloadID(NetworkDataTaskCocoa::TaskIdentifier taskIdentifier)
692 {
693     auto downloadID = m_downloadMap.take(taskIdentifier);
694     return downloadID;
695 }
696
697 static bool certificatesMatch(SecTrustRef trust1, SecTrustRef trust2)
698 {
699     if (!trust1 || !trust2)
700         return false;
701
702     CFIndex count1 = SecTrustGetCertificateCount(trust1);
703     CFIndex count2 = SecTrustGetCertificateCount(trust2);
704     if (count1 != count2)
705         return false;
706
707     for (CFIndex i = 0; i < count1; i++) {
708         auto cert1 = SecTrustGetCertificateAtIndex(trust1, i);
709         auto cert2 = SecTrustGetCertificateAtIndex(trust2, i);
710         RELEASE_ASSERT(cert1);
711         RELEASE_ASSERT(cert2);
712         if (!CFEqual(cert1, cert2))
713             return false;
714     }
715
716     return true;
717 }
718
719 bool NetworkSessionCocoa::allowsSpecificHTTPSCertificateForHost(const WebCore::AuthenticationChallenge& challenge)
720 {
721     const String& host = challenge.protectionSpace().host();
722     NSArray *certificates = [NSURLRequest allowsSpecificHTTPSCertificateForHost:host];
723     if (!certificates)
724         return false;
725
726     bool requireServerCertificates = challenge.protectionSpace().authenticationScheme() == WebCore::ProtectionSpaceAuthenticationScheme::ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested;
727     RetainPtr<SecPolicyRef> policy = adoptCF(SecPolicyCreateSSL(requireServerCertificates, host.createCFString().get()));
728
729     SecTrustRef trustRef = nullptr;
730     if (SecTrustCreateWithCertificates((CFArrayRef)certificates, policy.get(), &trustRef) != noErr)
731         return false;
732     RetainPtr<SecTrustRef> trust = adoptCF(trustRef);
733
734     return certificatesMatch(trust.get(), challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust);
735 }
736
737 }
738
739 #endif