Drop legacy WebCore::toRegistrableDomain() utility function
[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 "AuthenticationChallengeDisposition.h"
30 #import "AuthenticationManager.h"
31 #import "Download.h"
32 #import "DownloadProxyMessages.h"
33 #import "Logging.h"
34 #import "NetworkProcess.h"
35 #import "NetworkProximityManager.h"
36 #import "NetworkSessionCocoa.h"
37 #import "WebCoreArgumentCoders.h"
38 #import <WebCore/AuthenticationChallenge.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/FileSystem.h>
44 #import <wtf/MainThread.h>
45 #import <wtf/ProcessPrivilege.h>
46 #import <wtf/text/Base64.h>
47
48 #if HAVE(NW_ACTIVITY)
49 #import <CFNetwork/CFNSURLConnection.h>
50 #endif
51
52 namespace WebKit {
53
54 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
55 static void applyBasicAuthorizationHeader(WebCore::ResourceRequest& request, const WebCore::Credential& credential)
56 {
57     String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
58     request.setHTTPHeaderField(WebCore::HTTPHeaderName::Authorization, authenticationHeader);
59 }
60 #endif
61
62 static float toNSURLSessionTaskPriority(WebCore::ResourceLoadPriority priority)
63 {
64     switch (priority) {
65     case WebCore::ResourceLoadPriority::VeryLow:
66         return 0;
67     case WebCore::ResourceLoadPriority::Low:
68         return 0.25;
69     case WebCore::ResourceLoadPriority::Medium:
70         return 0.5;
71     case WebCore::ResourceLoadPriority::High:
72         return 0.75;
73     case WebCore::ResourceLoadPriority::VeryHigh:
74         return 1;
75     }
76
77     ASSERT_NOT_REACHED();
78     return NSURLSessionTaskPriorityDefault;
79 }
80
81 void NetworkDataTaskCocoa::applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(__strong NSURLRequest *& nsRequest, bool shouldContentSniff, bool shouldContentEncodingSniff)
82 {
83 #if !USE(CFNETWORK_CONTENT_ENCODING_SNIFFING_OVERRIDE)
84     UNUSED_PARAM(shouldContentEncodingSniff);
85 #endif
86
87     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
88     if (shouldContentSniff
89 #if USE(CFNETWORK_CONTENT_ENCODING_SNIFFING_OVERRIDE)
90         && shouldContentEncodingSniff
91 #endif
92         && cocoaSession.m_boundInterfaceIdentifier.isNull()
93         && !cocoaSession.m_proxyConfiguration)
94         return;
95
96     auto mutableRequest = adoptNS([nsRequest mutableCopy]);
97
98 #if USE(CFNETWORK_CONTENT_ENCODING_SNIFFING_OVERRIDE)
99     if (!shouldContentEncodingSniff)
100         [mutableRequest _setProperty:@(YES) forKey:(NSString *)kCFURLRequestContentDecoderSkipURLCheck];
101 #endif
102
103     if (!shouldContentSniff)
104         [mutableRequest _setProperty:@(NO) forKey:(NSString *)_kCFURLConnectionPropertyShouldSniff];
105
106     if (!cocoaSession.m_boundInterfaceIdentifier.isNull())
107         [mutableRequest setBoundInterfaceIdentifier:cocoaSession.m_boundInterfaceIdentifier];
108
109     if (cocoaSession.m_proxyConfiguration)
110         CFURLRequestSetProxySettings([mutableRequest _CFURLRequest], cocoaSession.m_proxyConfiguration.get());
111
112     nsRequest = mutableRequest.autorelease();
113 }
114
115 #if ENABLE(RESOURCE_LOAD_STATISTICS)
116 NSHTTPCookieStorage *NetworkDataTaskCocoa::statelessCookieStorage()
117 {
118     static NeverDestroyed<RetainPtr<NSHTTPCookieStorage>> statelessCookieStorage;
119     if (!statelessCookieStorage.get()) {
120 #if HAVE(NSHTTPCOOKIESTORAGE__INITWITHIDENTIFIER_WITH_INACCURATE_NULLABILITY)
121         IGNORE_NULL_CHECK_WARNINGS_BEGIN
122 #endif
123         statelessCookieStorage.get() = adoptNS([[NSHTTPCookieStorage alloc] _initWithIdentifier:nil private:YES]);
124 #if HAVE(NSHTTPCOOKIESTORAGE__INITWITHIDENTIFIER_WITH_INACCURATE_NULLABILITY)
125         IGNORE_NULL_CHECK_WARNINGS_END
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 _setExplicitCookieStorage:storage._cookieStorage];
142     m_hasBeenSetToUseStatelessCookieStorage = shouldBlock;
143 }
144 #endif
145
146 bool NetworkDataTaskCocoa::isThirdPartyRequest(const WebCore::ResourceRequest& request)
147 {
148     return !WebCore::areRegistrableDomainsEqual(request.url(), request.firstPartyForCookies());
149 }
150
151 static void updateTaskWithFirstPartyForSameSiteCookies(NSURLSessionDataTask* task, const WebCore::ResourceRequest& request)
152 {
153     if (request.isSameSiteUnspecified())
154         return;
155 #if HAVE(FOUNDATION_WITH_SAME_SITE_COOKIE_SUPPORT)
156     static NSURL *emptyURL = [[NSURL alloc] initWithString:@""];
157     task._siteForCookies = request.isSameSite() ? task.currentRequest.URL : emptyURL;
158     task._isTopLevelNavigation = request.isTopSite();
159 #else
160     UNUSED_PARAM(task);
161 #endif
162 }
163
164 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, Optional<NetworkActivityTracker> networkActivityTracker)
165     : NetworkDataTask(session, client, requestWithCredentials, storedCredentialsPolicy, shouldClearReferrerOnHTTPSToHTTPRedirect, dataTaskIsForMainFrameNavigation)
166     , m_frameID(frameID)
167     , m_pageID(pageID)
168 {
169     if (m_scheduledFailureType != NoFailure)
170         return;
171
172     auto request = requestWithCredentials;
173     auto url = request.url();
174     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use && url.protocolIsInHTTPFamily()) {
175         m_user = url.user();
176         m_password = url.pass();
177         request.removeCredentials();
178         url = request.url();
179     
180 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
181         if (m_user.isEmpty() && m_password.isEmpty())
182             m_initialCredential = m_session->networkStorageSession().credentialStorage().get(m_partition, url);
183         else
184             m_session->networkStorageSession().credentialStorage().set(m_partition, WebCore::Credential(m_user, m_password, WebCore::CredentialPersistenceNone), url);
185 #endif
186     }
187
188 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
189     if (!m_initialCredential.isEmpty()) {
190         // FIXME: Support Digest authentication, and Proxy-Authorization.
191         applyBasicAuthorizationHeader(request, m_initialCredential);
192     }
193 #endif
194
195     bool shouldBlockCookies = false;
196 #if ENABLE(RESOURCE_LOAD_STATISTICS)
197     shouldBlockCookies = session.networkStorageSession().shouldBlockCookies(request, frameID, pageID);
198 #endif
199     restrictRequestReferrerToOriginIfNeeded(request, shouldBlockCookies);
200
201     NSURLRequest *nsRequest = request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::UpdateHTTPBody);
202     applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(nsRequest, shouldContentSniff == WebCore::ContentSniffingPolicy::SniffContent && !url.isLocalFile(), shouldContentEncodingSniff == WebCore::ContentEncodingSniffingPolicy::Sniff);
203 #if ENABLE(PROXIMITY_NETWORKING)
204     m_session->networkProcess().proximityManager().applyProperties(request, *this, nsRequest);
205 #endif
206
207     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
208     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
209         m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
210         ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
211         cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
212         LOG(NetworkSession, "%llu Creating stateful NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
213     } else {
214         m_task = [cocoaSession.m_statelessSession dataTaskWithRequest:nsRequest];
215         ASSERT(!cocoaSession.m_dataTaskMapWithoutState.contains([m_task taskIdentifier]));
216         cocoaSession.m_dataTaskMapWithoutState.add([m_task taskIdentifier], this);
217         LOG(NetworkSession, "%llu Creating stateless NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
218     }
219
220     if (shouldPreconnectOnly == PreconnectOnly::Yes) {
221 #if ENABLE(SERVER_PRECONNECT)
222         m_task.get()._preconnect = true;
223 #else
224         ASSERT_NOT_REACHED();
225 #endif
226     }
227
228 #if ENABLE(RESOURCE_LOAD_STATISTICS)
229     if (shouldBlockCookies) {
230 #if !RELEASE_LOG_DISABLED
231         if (m_session->shouldLogCookieInformation())
232             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);
233 #else
234         LOG(NetworkSession, "%llu Blocking cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
235 #endif
236         applyCookieBlockingPolicy(shouldBlockCookies);
237     }
238 #endif
239
240     if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
241         m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
242
243     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
244
245 #if HAVE(NW_ACTIVITY)
246     if (networkActivityTracker)
247         m_task.get()._nw_activity = networkActivityTracker.value().getPlatformObject();
248 #endif
249 }
250
251 NetworkDataTaskCocoa::~NetworkDataTaskCocoa()
252 {
253     if (!m_task)
254         return;
255
256     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
257     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
258         ASSERT(cocoaSession.m_dataTaskMapWithCredentials.get([m_task taskIdentifier]) == this);
259         cocoaSession.m_dataTaskMapWithCredentials.remove([m_task taskIdentifier]);
260     } else {
261         ASSERT(cocoaSession.m_dataTaskMapWithoutState.get([m_task taskIdentifier]) == this);
262         cocoaSession.m_dataTaskMapWithoutState.remove([m_task taskIdentifier]);
263     }
264 }
265
266 void NetworkDataTaskCocoa::restrictRequestReferrerToOriginIfNeeded(WebCore::ResourceRequest& request, bool shouldBlockCookies)
267 {
268     if (shouldBlockCookies || (m_session->sessionID().isEphemeral() && isThirdPartyRequest(request)))
269         request.setExistingHTTPReferrerToOriginString();
270 }
271
272 void NetworkDataTaskCocoa::didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend)
273 {
274     if (m_client)
275         m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
276 }
277
278 void NetworkDataTaskCocoa::didReceiveChallenge(WebCore::AuthenticationChallenge&& challenge, ChallengeCompletionHandler&& completionHandler)
279 {
280     if (tryPasswordBasedAuthentication(challenge, completionHandler))
281         return;
282
283     if (m_client)
284         m_client->didReceiveChallenge(WTFMove(challenge), WTFMove(completionHandler));
285     else {
286         ASSERT_NOT_REACHED();
287         completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
288     }
289 }
290
291 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics& networkLoadMetrics)
292 {
293     if (m_client)
294         m_client->didCompleteWithError(error, networkLoadMetrics);
295 }
296
297 void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
298 {
299     if (m_client)
300         m_client->didReceiveData(WTFMove(data));
301 }
302
303 void NetworkDataTaskCocoa::willPerformHTTPRedirection(WebCore::ResourceResponse&& redirectResponse, WebCore::ResourceRequest&& request, RedirectCompletionHandler&& completionHandler)
304 {
305     if (redirectResponse.httpStatusCode() == 307 || redirectResponse.httpStatusCode() == 308) {
306         ASSERT(m_lastHTTPMethod == request.httpMethod());
307         WebCore::FormData* body = m_firstRequest.httpBody();
308         if (body && !body->isEmpty() && !equalLettersIgnoringASCIICase(m_lastHTTPMethod, "get"))
309             request.setHTTPBody(body);
310         
311         String originalContentType = m_firstRequest.httpContentType();
312         if (!originalContentType.isEmpty())
313             request.setHTTPHeaderField(WebCore::HTTPHeaderName::ContentType, originalContentType);
314     } else if (redirectResponse.httpStatusCode() == 303 && equalLettersIgnoringASCIICase(m_firstRequest.httpMethod(), "head")) // FIXME: (rdar://problem/13706454).
315         request.setHTTPMethod("HEAD"_s);
316     
317     // Should not set Referer after a redirect from a secure resource to non-secure one.
318     if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && WTF::protocolIs(request.httpReferrer(), "https"))
319         request.clearHTTPReferrer();
320     
321     const auto& url = request.url();
322     m_user = url.user();
323     m_password = url.pass();
324     m_lastHTTPMethod = request.httpMethod();
325     request.removeCredentials();
326     
327     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
328         // The network layer might carry over some headers from the original request that
329         // we want to strip here because the redirect is cross-origin.
330         request.clearHTTPAuthorization();
331         request.clearHTTPOrigin();
332 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
333     } else {
334         // Only consider applying authentication credentials if this is actually a redirect and the redirect
335         // URL didn't include credentials of its own.
336         if (m_user.isEmpty() && m_password.isEmpty() && !redirectResponse.isNull()) {
337             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
338             if (!credential.isEmpty()) {
339                 m_initialCredential = credential;
340
341                 // FIXME: Support Digest authentication, and Proxy-Authorization.
342                 applyBasicAuthorizationHeader(request, m_initialCredential);
343             }
344         }
345 #endif
346     }
347
348     if (isTopLevelNavigation())
349         request.setFirstPartyForCookies(request.url());
350
351 #if ENABLE(RESOURCE_LOAD_STATISTICS)
352     bool shouldBlockCookies = m_session->networkStorageSession().shouldBlockCookies(request, m_frameID, m_pageID);
353 #if !RELEASE_LOG_DISABLED
354     if (m_session->shouldLogCookieInformation())
355         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());
356 #else
357     LOG(NetworkSession, "%llu %s cookies for redirect URL %s", [m_task taskIdentifier], (shouldBlockCookies ? "Blocking" : "Not blocking"), request.url().string().utf8().data());
358 #endif
359 #endif
360
361 #if ENABLE(RESOURCE_LOAD_STATISTICS)
362     // Always apply the policy since blocking may need to be turned on or off in a redirect.
363     applyCookieBlockingPolicy(shouldBlockCookies);
364
365     if (!shouldBlockCookies) {
366 #if !RELEASE_LOG_DISABLED
367         if (m_session->shouldLogCookieInformation())
368             RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), Network, "%p - NetworkDataTaskCocoa::willPerformHTTPRedirection::logCookieInformation: pageID = %llu, frameID = %llu, taskID = %lu: Not partitioning cookies for redirect URL %s", this, m_pageID, m_frameID, (unsigned long)[m_task taskIdentifier], request.url().string().utf8().data());
369 #else
370         LOG(NetworkSession, "%llu Not partitioning cookies for redirect URL %s", [m_task taskIdentifier], request.url().string().utf8().data());
371 #endif
372     }
373 #endif
374
375     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
376
377     if (m_client)
378         m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), [completionHandler = WTFMove(completionHandler), this, weakThis = makeWeakPtr(*this)] (auto&& request) mutable {
379             if (!weakThis)
380                 return completionHandler({ });
381             if (!request.isNull()) {
382 #if ENABLE(RESOURCE_LOAD_STATISTICS)
383                 bool shouldBlockCookies = m_session->networkStorageSession().shouldBlockCookies(request, m_frameID, m_pageID);
384 #else
385                 bool shouldBlockCookies = false;
386 #endif
387                 restrictRequestReferrerToOriginIfNeeded(request, shouldBlockCookies);
388             }
389             completionHandler(WTFMove(request));
390         });
391     else {
392         ASSERT_NOT_REACHED();
393         completionHandler({ });
394     }
395 }
396
397 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
398 {
399     NetworkDataTask::setPendingDownloadLocation(filename, { }, allowOverwrite);
400
401     ASSERT(!m_sandboxExtension);
402     m_sandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
403     if (m_sandboxExtension)
404         m_sandboxExtension->consume();
405
406     m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
407
408     if (allowOverwrite && FileSystem::fileExists(m_pendingDownloadLocation))
409         FileSystem::deleteFile(filename);
410 }
411
412 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler& completionHandler)
413 {
414     if (!challenge.protectionSpace().isPasswordBased())
415         return false;
416     
417     if (!m_user.isNull() && !m_password.isNull()) {
418         auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
419         completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
420         m_user = String();
421         m_password = String();
422         return true;
423     }
424
425 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
426     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
427         if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
428             // The stored credential wasn't accepted, stop using it.
429             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
430             // but the observable effect should be very minor, if any.
431             m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
432         }
433
434         if (!challenge.previousFailureCount()) {
435             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
436             if (!credential.isEmpty() && credential != m_initialCredential) {
437                 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
438                 if (challenge.failureResponse().httpStatusCode() == 401) {
439                     // Store the credential back, possibly adding it as a default for this directory.
440                     m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
441                 }
442                 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
443                 return true;
444             }
445         }
446     }
447 #endif
448
449     if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
450         completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
451         return true;
452     }
453     
454     return false;
455 }
456
457 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
458 {
459     download.setSandboxExtension(WTFMove(m_sandboxExtension));
460 }
461
462 String NetworkDataTaskCocoa::suggestedFilename() const
463 {
464     if (!m_suggestedFilename.isEmpty())
465         return m_suggestedFilename;
466     return m_task.get().response.suggestedFilename;
467 }
468
469 void NetworkDataTaskCocoa::cancel()
470 {
471     [m_task cancel];
472 }
473
474 void NetworkDataTaskCocoa::resume()
475 {
476     if (m_scheduledFailureType != NoFailure)
477         m_failureTimer.startOneShot(0_s);
478     [m_task resume];
479 }
480
481 NetworkDataTask::State NetworkDataTaskCocoa::state() const
482 {
483     switch ([m_task state]) {
484     case NSURLSessionTaskStateRunning:
485         return State::Running;
486     case NSURLSessionTaskStateSuspended:
487         return State::Suspended;
488     case NSURLSessionTaskStateCanceling:
489         return State::Canceling;
490     case NSURLSessionTaskStateCompleted:
491         return State::Completed;
492     }
493
494     ASSERT_NOT_REACHED();
495     return State::Completed;
496 }
497
498 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
499 {
500     return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);
501 }
502
503 bool NetworkDataTaskCocoa::isAlwaysOnLoggingAllowed() const
504 {
505     if (m_session->networkProcess().sessionIsControlledByAutomation(m_session->sessionID()))
506         return true;
507
508     return m_session->sessionID().isAlwaysOnLoggingAllowed();
509 }
510
511 String NetworkDataTaskCocoa::description() const
512 {
513     return String([m_task description]);
514 }
515
516 }