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