Include breadcrumb for tracking resource loading into CFNetwork
[WebKit-https.git] / Source / WebKit / NetworkProcess / cocoa / NetworkDataTaskCocoa.mm
1 /*
2  * Copyright (C) 2016-2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "NetworkDataTaskCocoa.h"
28
29 #import "AuthenticationManager.h"
30 #import "Download.h"
31 #import "DownloadProxyMessages.h"
32 #import "Logging.h"
33 #import "NetworkProcess.h"
34 #import "NetworkSessionCocoa.h"
35 #import "SessionTracker.h"
36 #import "WebCoreArgumentCoders.h"
37 #import <WebCore/AuthenticationChallenge.h>
38 #import <WebCore/FileSystem.h>
39 #import <WebCore/NetworkStorageSession.h>
40 #import <WebCore/NotImplemented.h>
41 #import <WebCore/ResourceRequest.h>
42 #import <pal/spi/cf/CFNetworkSPI.h>
43 #import <wtf/MainThread.h>
44 #import <wtf/ProcessPrivilege.h>
45 #import <wtf/text/Base64.h>
46
47 #if USE(APPLE_INTERNAL_SDK)
48 #import <WebKitAdditions/NetworkDataTaskCocoaAdditions.mm>
49 #endif
50
51 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 120000)
52 @interface NSURLSessionTask (Staging)
53 @property (nullable, readwrite, retain) NSURL *_siteForCookies;
54 @property (readwrite) BOOL _isTopLevelNavigation;
55 @end
56 #endif
57
58 namespace WebKit {
59
60 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
61 static void applyBasicAuthorizationHeader(WebCore::ResourceRequest& request, const WebCore::Credential& credential)
62 {
63     String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
64     request.setHTTPHeaderField(WebCore::HTTPHeaderName::Authorization, authenticationHeader);
65 }
66 #endif
67
68 static float toNSURLSessionTaskPriority(WebCore::ResourceLoadPriority priority)
69 {
70     switch (priority) {
71     case WebCore::ResourceLoadPriority::VeryLow:
72         return 0;
73     case WebCore::ResourceLoadPriority::Low:
74         return 0.25;
75     case WebCore::ResourceLoadPriority::Medium:
76         return 0.5;
77     case WebCore::ResourceLoadPriority::High:
78         return 0.75;
79     case WebCore::ResourceLoadPriority::VeryHigh:
80         return 1;
81     }
82
83     ASSERT_NOT_REACHED();
84     return NSURLSessionTaskPriorityDefault;
85 }
86
87 void NetworkDataTaskCocoa::applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(NSURLRequest*& nsRequest, bool shouldContentSniff, bool shouldContentEncodingSniff)
88 {
89 #if !PLATFORM(MAC)
90     UNUSED_PARAM(shouldContentEncodingSniff);
91 #elif __MAC_OS_X_VERSION_MIN_REQUIRED < 101302
92     shouldContentEncodingSniff = true;
93 #endif
94     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
95     if (shouldContentSniff && shouldContentEncodingSniff && cocoaSession.m_boundInterfaceIdentifier.isNull())
96         return;
97
98     auto mutableRequest = adoptNS([nsRequest mutableCopy]);
99
100 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101302
101     if (!shouldContentEncodingSniff)
102         [mutableRequest _setProperty:@(YES) forKey:(NSString *)kCFURLRequestContentDecoderSkipURLCheck];
103 #endif
104
105     if (!shouldContentSniff)
106         [mutableRequest _setProperty:@(NO) forKey:(NSString *)_kCFURLConnectionPropertyShouldSniff];
107
108     if (!cocoaSession.m_boundInterfaceIdentifier.isNull())
109         [mutableRequest setBoundInterfaceIdentifier:cocoaSession.m_boundInterfaceIdentifier];
110
111     nsRequest = mutableRequest.autorelease();
112 }
113
114 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
115 NSHTTPCookieStorage *NetworkDataTaskCocoa::statelessCookieStorage()
116 {
117     static NeverDestroyed<RetainPtr<NSHTTPCookieStorage>> statelessCookieStorage;
118     if (!statelessCookieStorage.get()) {
119 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
120 #pragma clang diagnostic push
121 #pragma clang diagnostic ignored "-Wnonnull"
122 #endif
123         statelessCookieStorage.get() = adoptNS([[NSHTTPCookieStorage alloc] _initWithIdentifier:nil private:YES]);
124 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
125 #pragma clang diagnostic pop
126 #endif
127         statelessCookieStorage.get().get().cookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
128     }
129     ASSERT(statelessCookieStorage.get().get().cookies.count == 0);
130     return statelessCookieStorage.get().get();
131 }
132
133 void NetworkDataTaskCocoa::applyCookieBlockingPolicy(bool shouldBlock)
134 {
135     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
136
137     if (shouldBlock == m_hasBeenSetToUseStatelessCookieStorage)
138         return;
139
140     NSHTTPCookieStorage *storage = shouldBlock ? statelessCookieStorage(): m_session->networkStorageSession().nsCookieStorage();
141     [m_task performSelector:NSSelectorFromString(@"_setExplicitCookieStorage:") withObject:(NSObject*)storage._cookieStorage];
142     m_hasBeenSetToUseStatelessCookieStorage = shouldBlock;
143 }
144
145 void NetworkDataTaskCocoa::applyCookiePartitioningPolicy(const String& requiredStoragePartition, const String& currentStoragePartition)
146 {
147     // The need for a partion change is according to the following:
148     //      currentStoragePartition:  null  ""    abc
149     // requiredStoragePartition: ""   false false true
150     //                           abc  true  true  false
151     //                           xyz  true  true  true
152     auto shouldChangePartition = !((requiredStoragePartition.isEmpty() && currentStoragePartition.isEmpty()) || currentStoragePartition == requiredStoragePartition);
153     if (shouldChangePartition)
154         m_task.get()._storagePartitionIdentifier = requiredStoragePartition;
155 }
156 #endif
157
158 bool NetworkDataTaskCocoa::isThirdPartyRequest(const WebCore::ResourceRequest& request)
159 {
160     return !WebCore::registrableDomainsAreEqual(request.url(), request.firstPartyForCookies());
161 }
162
163 static void updateTaskWithFirstPartyForSameSiteCookies(NSURLSessionDataTask* task, const WebCore::ResourceRequest& request)
164 {
165     if (request.isSameSiteUnspecified())
166         return;
167 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 120000)
168     static NSURL *emptyURL = [[NSURL alloc] initWithString:@""];
169     if ([task respondsToSelector:@selector(set_siteForCookies:)])
170         task._siteForCookies = request.isSameSite() ? task.currentRequest.URL : emptyURL;
171     if ([task respondsToSelector:@selector(set_isTopLevelNavigation:)])
172         task._isTopLevelNavigation = request.isTopSite();
173 #else
174     UNUSED_PARAM(task);
175 #endif
176 }
177
178 NetworkDataTaskCocoa::NetworkDataTaskCocoa(NetworkSession& session, NetworkDataTaskClient& client, const WebCore::ResourceRequest& requestWithCredentials, uint64_t frameID, uint64_t pageID, WebCore::StoredCredentialsPolicy storedCredentialsPolicy, WebCore::ContentSniffingPolicy shouldContentSniff, WebCore::ContentEncodingSniffingPolicy shouldContentEncodingSniff, bool shouldClearReferrerOnHTTPSToHTTPRedirect, PreconnectOnly shouldPreconnectOnly, bool dataTaskIsForMainFrameNavigation)
179     : NetworkDataTask(session, client, requestWithCredentials, storedCredentialsPolicy, shouldClearReferrerOnHTTPSToHTTPRedirect, dataTaskIsForMainFrameNavigation)
180     , m_frameID(frameID)
181     , m_pageID(pageID)
182 {
183     if (m_scheduledFailureType != NoFailure)
184         return;
185
186     auto request = requestWithCredentials;
187     auto url = request.url();
188     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use && url.protocolIsInHTTPFamily()) {
189         m_user = url.user();
190         m_password = url.pass();
191         request.removeCredentials();
192         url = request.url();
193     
194 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
195         if (m_user.isEmpty() && m_password.isEmpty())
196             m_initialCredential = m_session->networkStorageSession().credentialStorage().get(m_partition, url);
197         else
198             m_session->networkStorageSession().credentialStorage().set(m_partition, WebCore::Credential(m_user, m_password, WebCore::CredentialPersistenceNone), url);
199 #endif
200     }
201
202 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
203     if (!m_initialCredential.isEmpty()) {
204         // FIXME: Support Digest authentication, and Proxy-Authorization.
205         applyBasicAuthorizationHeader(request, m_initialCredential);
206     }
207 #endif
208
209     bool shouldBlockCookies = false;
210 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
211     shouldBlockCookies = session.networkStorageSession().shouldBlockCookies(request);
212 #endif
213     if (shouldBlockCookies || (m_session->sessionID().isEphemeral() && isThirdPartyRequest(request)))
214         request.setExistingHTTPReferrerToOriginString();
215
216     NSURLRequest *nsRequest = request.nsURLRequest(WebCore::UpdateHTTPBody);
217     applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(nsRequest, shouldContentSniff == WebCore::SniffContent && !url.isLocalFile(), shouldContentEncodingSniff == WebCore::ContentEncodingSniffingPolicy::Sniff);
218 #if ENABLE(WIFI_ASSERTIONS)
219     applyAdditionalProperties(request, *this, nsRequest);
220 #endif
221
222     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
223     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
224         m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
225         ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
226         cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
227         LOG(NetworkSession, "%llu Creating stateless NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
228     } else {
229         m_task = [cocoaSession.m_statelessSession dataTaskWithRequest:nsRequest];
230         ASSERT(!cocoaSession.m_dataTaskMapWithoutState.contains([m_task taskIdentifier]));
231         cocoaSession.m_dataTaskMapWithoutState.add([m_task taskIdentifier], this);
232         LOG(NetworkSession, "%llu Creating NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
233     }
234
235     if (shouldPreconnectOnly == PreconnectOnly::Yes) {
236 #if ENABLE(SERVER_PRECONNECT)
237         m_task.get()._preconnect = true;
238 #else
239         ASSERT_NOT_REACHED();
240 #endif
241     }
242
243 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
244     if (shouldBlockCookies) {
245 #if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
246         if (NetworkProcess::singleton().shouldLogCookieInformation())
247             RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkDataTaskCocoa::logCookieInformation: pageID = %llu, frameID = %llu, taskID = %lu: Blocking cookies for URL %s", this, pageID, frameID, (unsigned long)[m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
248 #else
249         LOG(NetworkSession, "%llu Blocking cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
250 #endif
251         applyCookieBlockingPolicy(shouldBlockCookies);
252     } else {
253         auto storagePartition = session.networkStorageSession().cookieStoragePartition(request, m_frameID, m_pageID);
254         if (!storagePartition.isEmpty()) {
255 #if HAVE(CFNETWORK_STORAGE_PARTITIONING) && !RELEASE_LOG_DISABLED
256             if (NetworkProcess::singleton().shouldLogCookieInformation())
257                 RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkDataTaskCocoa::logCookieInformation: pageID = %llu, frameID = %llu, taskID = %lu: Partitioning cookies for URL %s", this, pageID, frameID, (unsigned long)[m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
258 #else
259             LOG(NetworkSession, "%llu Partitioning cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
260 #endif
261             applyCookiePartitioningPolicy(storagePartition, emptyString());
262         }
263     }
264 #endif
265
266     if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
267         m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
268
269     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
270 }
271
272 NetworkDataTaskCocoa::~NetworkDataTaskCocoa()
273 {
274     if (!m_task)
275         return;
276
277     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
278     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
279         ASSERT(cocoaSession.m_dataTaskMapWithCredentials.get([m_task taskIdentifier]) == this);
280         cocoaSession.m_dataTaskMapWithCredentials.remove([m_task taskIdentifier]);
281     } else {
282         ASSERT(cocoaSession.m_dataTaskMapWithoutState.get([m_task taskIdentifier]) == this);
283         cocoaSession.m_dataTaskMapWithoutState.remove([m_task taskIdentifier]);
284     }
285 }
286
287 void NetworkDataTaskCocoa::didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend)
288 {
289     if (m_client)
290         m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
291 }
292
293 void NetworkDataTaskCocoa::didReceiveChallenge(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler&& completionHandler)
294 {
295     if (tryPasswordBasedAuthentication(challenge, completionHandler))
296         return;
297
298     if (m_client)
299         m_client->didReceiveChallenge(challenge, WTFMove(completionHandler));
300     else {
301         ASSERT_NOT_REACHED();
302         completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
303     }
304 }
305
306 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics& networkLoadMetrics)
307 {
308     if (m_client)
309         m_client->didCompleteWithError(error, networkLoadMetrics);
310 }
311
312 void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
313 {
314     if (m_client)
315         m_client->didReceiveData(WTFMove(data));
316 }
317
318 void NetworkDataTaskCocoa::willPerformHTTPRedirection(WebCore::ResourceResponse&& redirectResponse, WebCore::ResourceRequest&& request, RedirectCompletionHandler&& completionHandler)
319 {
320     if (redirectResponse.httpStatusCode() == 307 || redirectResponse.httpStatusCode() == 308) {
321         ASSERT(m_lastHTTPMethod == request.httpMethod());
322         WebCore::FormData* body = m_firstRequest.httpBody();
323         if (body && !body->isEmpty() && !equalLettersIgnoringASCIICase(m_lastHTTPMethod, "get"))
324             request.setHTTPBody(body);
325         
326         String originalContentType = m_firstRequest.httpContentType();
327         if (!originalContentType.isEmpty())
328             request.setHTTPHeaderField(WebCore::HTTPHeaderName::ContentType, originalContentType);
329     }
330     
331     // Should not set Referer after a redirect from a secure resource to non-secure one.
332     if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && WebCore::protocolIs(request.httpReferrer(), "https"))
333         request.clearHTTPReferrer();
334     
335     const auto& url = request.url();
336     m_user = url.user();
337     m_password = url.pass();
338     m_lastHTTPMethod = request.httpMethod();
339     request.removeCredentials();
340     
341     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
342         // The network layer might carry over some headers from the original request that
343         // we want to strip here because the redirect is cross-origin.
344         request.clearHTTPAuthorization();
345         request.clearHTTPOrigin();
346 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
347     } else {
348         // Only consider applying authentication credentials if this is actually a redirect and the redirect
349         // URL didn't include credentials of its own.
350         if (m_user.isEmpty() && m_password.isEmpty() && !redirectResponse.isNull()) {
351             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
352             if (!credential.isEmpty()) {
353                 m_initialCredential = credential;
354
355                 // FIXME: Support Digest authentication, and Proxy-Authorization.
356                 applyBasicAuthorizationHeader(request, m_initialCredential);
357             }
358         }
359 #endif
360     }
361
362     if (isTopLevelNavigation())
363         request.setFirstPartyForCookies(request.url());
364
365     bool shouldBlockCookies = false;
366 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
367     shouldBlockCookies = m_session->networkStorageSession().shouldBlockCookies(request);
368 #if !RELEASE_LOG_DISABLED
369     if (NetworkProcess::singleton().shouldLogCookieInformation())
370         RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkDataTaskCocoa::willPerformHTTPRedirection::logCookieInformation: pageID = %llu, frameID = %llu, taskID = %lu: %s cookies for redirect URL %s", this, m_pageID, m_frameID, (unsigned long)[m_task taskIdentifier], (shouldBlockCookies ? "Blocking" : "Not blocking"), request.url().string().utf8().data());
371 #else
372     LOG(NetworkSession, "%llu %s cookies for redirect URL %s", [m_task taskIdentifier], (shouldBlockCookies ? "Blocking" : "Not blocking"), request.url().string().utf8().data());
373 #endif
374 #endif
375
376     if (shouldBlockCookies || (m_session->sessionID().isEphemeral() && isThirdPartyRequest(request)))
377         request.setExistingHTTPReferrerToOriginString();
378
379 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
380     // Always apply the policy since blocking may need to be turned on or off in a redirect.
381     applyCookieBlockingPolicy(shouldBlockCookies);
382
383     if (!shouldBlockCookies) {
384         auto requiredStoragePartition = m_session->networkStorageSession().cookieStoragePartition(request, m_frameID, m_pageID);
385 #if !RELEASE_LOG_DISABLED
386         if (NetworkProcess::singleton().shouldLogCookieInformation())
387             RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkDataTaskCocoa::willPerformHTTPRedirection::logCookieInformation: pageID = %llu, frameID = %llu, taskID = %lu: %s cookies for redirect URL %s", this, m_pageID, m_frameID, (unsigned long)[m_task taskIdentifier], (requiredStoragePartition.isEmpty() ? "Not partitioning" : "Partitioning"), request.url().string().utf8().data());
388 #else
389         LOG(NetworkSession, "%llu %s cookies for redirect URL %s", [m_task taskIdentifier], (requiredStoragePartition.isEmpty() ? "Not partitioning" : "Partitioning"), request.url().string().utf8().data());
390 #endif
391         applyCookiePartitioningPolicy(requiredStoragePartition, m_task.get()._storagePartitionIdentifier);
392     }
393 #endif
394
395     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
396
397     if (m_client)
398         m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), WTFMove(completionHandler));
399     else {
400         ASSERT_NOT_REACHED();
401         completionHandler({ });
402     }
403 }
404
405 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
406 {
407     NetworkDataTask::setPendingDownloadLocation(filename, { }, allowOverwrite);
408
409     ASSERT(!m_sandboxExtension);
410     m_sandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
411     if (m_sandboxExtension)
412         m_sandboxExtension->consume();
413
414     m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
415
416     if (allowOverwrite && WebCore::FileSystem::fileExists(m_pendingDownloadLocation))
417         WebCore::FileSystem::deleteFile(filename);
418 }
419
420 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler& completionHandler)
421 {
422     if (!challenge.protectionSpace().isPasswordBased())
423         return false;
424     
425     if (!m_user.isNull() && !m_password.isNull()) {
426         auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
427         completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
428         m_user = String();
429         m_password = String();
430         return true;
431     }
432
433 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
434     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
435         if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
436             // The stored credential wasn't accepted, stop using it.
437             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
438             // but the observable effect should be very minor, if any.
439             m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
440         }
441
442         if (!challenge.previousFailureCount()) {
443             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
444             if (!credential.isEmpty() && credential != m_initialCredential) {
445                 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
446                 if (challenge.failureResponse().httpStatusCode() == 401) {
447                     // Store the credential back, possibly adding it as a default for this directory.
448                     m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
449                 }
450                 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
451                 return true;
452             }
453         }
454     }
455 #endif
456
457     if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
458         completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
459         return true;
460     }
461     
462     return false;
463 }
464
465 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
466 {
467     download.setSandboxExtension(WTFMove(m_sandboxExtension));
468 }
469
470 String NetworkDataTaskCocoa::suggestedFilename() const
471 {
472     if (!m_suggestedFilename.isEmpty())
473         return m_suggestedFilename;
474     return m_task.get().response.suggestedFilename;
475 }
476
477 void NetworkDataTaskCocoa::cancel()
478 {
479     [m_task cancel];
480 }
481
482 void NetworkDataTaskCocoa::resume()
483 {
484     if (m_scheduledFailureType != NoFailure)
485         m_failureTimer.startOneShot(0_s);
486     [m_task resume];
487 }
488
489 void NetworkDataTaskCocoa::suspend()
490 {
491     if (m_failureTimer.isActive())
492         m_failureTimer.stop();
493     [m_task suspend];
494 }
495
496 NetworkDataTask::State NetworkDataTaskCocoa::state() const
497 {
498     switch ([m_task state]) {
499     case NSURLSessionTaskStateRunning:
500         return State::Running;
501     case NSURLSessionTaskStateSuspended:
502         return State::Suspended;
503     case NSURLSessionTaskStateCanceling:
504         return State::Canceling;
505     case NSURLSessionTaskStateCompleted:
506         return State::Completed;
507     }
508
509     ASSERT_NOT_REACHED();
510     return State::Completed;
511 }
512
513 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
514 {
515     return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);
516 }
517
518 bool NetworkDataTaskCocoa::isAlwaysOnLoggingAllowed() const
519 {
520     if (NetworkProcess::singleton().sessionIsControlledByAutomation(m_session->sessionID()))
521         return true;
522
523     return m_session->sessionID().isAlwaysOnLoggingAllowed();
524 }
525
526 String NetworkDataTaskCocoa::description() const
527 {
528     return String([m_task description]);
529 }
530
531 }