[Cocoa] Adapt more WebKit code to be ARC-compatible
[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 "NetworkProximityManager.h"
35 #import "NetworkSessionCocoa.h"
36 #import "SessionTracker.h"
37 #import "WebCoreArgumentCoders.h"
38 #import <WebCore/AuthenticationChallenge.h>
39 #import <WebCore/FileSystem.h>
40 #import <WebCore/NetworkStorageSession.h>
41 #import <WebCore/NotImplemented.h>
42 #import <WebCore/ResourceRequest.h>
43 #import <pal/spi/cf/CFNetworkSPI.h>
44 #import <wtf/MainThread.h>
45 #import <wtf/ProcessPrivilege.h>
46 #import <wtf/text/Base64.h>
47
48 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 120000)
49 @interface NSURLSessionTask (Staging)
50 @property (readwrite, retain) NSURL *_siteForCookies;
51 @property (readwrite) BOOL _isTopLevelNavigation;
52 @end
53 #endif
54
55 #if HAVE(NW_ACTIVITY)
56 #import <CFNetwork/CFNSURLConnection.h>
57 #endif
58
59 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
60
61 // FIXME: Move to CFNetworkSPI.h?
62 @interface NSURLSessionTask ()
63 - (void)_setExplicitCookieStorage:(CFHTTPCookieStorageRef)storage;
64 @end
65
66 #endif
67
68 namespace WebKit {
69
70 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
71 static void applyBasicAuthorizationHeader(WebCore::ResourceRequest& request, const WebCore::Credential& credential)
72 {
73     String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
74     request.setHTTPHeaderField(WebCore::HTTPHeaderName::Authorization, authenticationHeader);
75 }
76 #endif
77
78 static float toNSURLSessionTaskPriority(WebCore::ResourceLoadPriority priority)
79 {
80     switch (priority) {
81     case WebCore::ResourceLoadPriority::VeryLow:
82         return 0;
83     case WebCore::ResourceLoadPriority::Low:
84         return 0.25;
85     case WebCore::ResourceLoadPriority::Medium:
86         return 0.5;
87     case WebCore::ResourceLoadPriority::High:
88         return 0.75;
89     case WebCore::ResourceLoadPriority::VeryHigh:
90         return 1;
91     }
92
93     ASSERT_NOT_REACHED();
94     return NSURLSessionTaskPriorityDefault;
95 }
96
97 void NetworkDataTaskCocoa::applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(__strong NSURLRequest *& nsRequest, bool shouldContentSniff, bool shouldContentEncodingSniff)
98 {
99 #if !PLATFORM(MAC)
100     UNUSED_PARAM(shouldContentEncodingSniff);
101 #elif __MAC_OS_X_VERSION_MIN_REQUIRED < 101302
102     shouldContentEncodingSniff = true;
103 #endif
104     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
105     if (shouldContentSniff
106         && shouldContentEncodingSniff
107         && cocoaSession.m_boundInterfaceIdentifier.isNull()
108         && !cocoaSession.m_proxyConfiguration)
109         return;
110
111     auto mutableRequest = adoptNS([nsRequest mutableCopy]);
112
113 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101302
114     if (!shouldContentEncodingSniff)
115         [mutableRequest _setProperty:@(YES) forKey:(NSString *)kCFURLRequestContentDecoderSkipURLCheck];
116 #endif
117
118     if (!shouldContentSniff)
119         [mutableRequest _setProperty:@(NO) forKey:(NSString *)_kCFURLConnectionPropertyShouldSniff];
120
121     if (!cocoaSession.m_boundInterfaceIdentifier.isNull())
122         [mutableRequest setBoundInterfaceIdentifier:cocoaSession.m_boundInterfaceIdentifier];
123
124     if (cocoaSession.m_proxyConfiguration)
125         CFURLRequestSetProxySettings([mutableRequest _CFURLRequest], cocoaSession.m_proxyConfiguration.get());
126
127     nsRequest = mutableRequest.autorelease();
128 }
129
130 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
131
132 NSHTTPCookieStorage *NetworkDataTaskCocoa::statelessCookieStorage()
133 {
134     static NeverDestroyed<RetainPtr<NSHTTPCookieStorage>> statelessCookieStorage;
135     if (!statelessCookieStorage.get()) {
136 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
137 #pragma clang diagnostic push
138 #pragma clang diagnostic ignored "-Wnonnull"
139 #endif
140         statelessCookieStorage.get() = adoptNS([[NSHTTPCookieStorage alloc] _initWithIdentifier:nil private:YES]);
141 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
142 #pragma clang diagnostic pop
143 #endif
144         statelessCookieStorage.get().get().cookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
145     }
146     ASSERT(statelessCookieStorage.get().get().cookies.count == 0);
147     return statelessCookieStorage.get().get();
148 }
149
150 void NetworkDataTaskCocoa::applyCookieBlockingPolicy(bool shouldBlock)
151 {
152     ASSERT(hasProcessPrivilege(ProcessPrivilege::CanAccessRawCookies));
153
154     if (shouldBlock == m_hasBeenSetToUseStatelessCookieStorage)
155         return;
156
157     NSHTTPCookieStorage *storage = shouldBlock ? statelessCookieStorage() : m_session->networkStorageSession().nsCookieStorage();
158     [m_task _setExplicitCookieStorage:storage._cookieStorage];
159     m_hasBeenSetToUseStatelessCookieStorage = shouldBlock;
160 }
161
162 #endif
163
164 bool NetworkDataTaskCocoa::isThirdPartyRequest(const WebCore::ResourceRequest& request)
165 {
166     return !WebCore::registrableDomainsAreEqual(request.url(), request.firstPartyForCookies());
167 }
168
169 static void updateTaskWithFirstPartyForSameSiteCookies(NSURLSessionDataTask* task, const WebCore::ResourceRequest& request)
170 {
171     if (request.isSameSiteUnspecified())
172         return;
173 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 120000)
174     static NSURL *emptyURL = [[NSURL alloc] initWithString:@""];
175     if ([task respondsToSelector:@selector(set_siteForCookies:)])
176         task._siteForCookies = request.isSameSite() ? task.currentRequest.URL : emptyURL;
177     if ([task respondsToSelector:@selector(set_isTopLevelNavigation:)])
178         task._isTopLevelNavigation = request.isTopSite();
179 #else
180     UNUSED_PARAM(task);
181 #endif
182 }
183
184 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)
185     : NetworkDataTask(session, client, requestWithCredentials, storedCredentialsPolicy, shouldClearReferrerOnHTTPSToHTTPRedirect, dataTaskIsForMainFrameNavigation)
186     , m_frameID(frameID)
187     , m_pageID(pageID)
188 {
189     if (m_scheduledFailureType != NoFailure)
190         return;
191
192     auto request = requestWithCredentials;
193     auto url = request.url();
194     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use && url.protocolIsInHTTPFamily()) {
195         m_user = url.user();
196         m_password = url.pass();
197         request.removeCredentials();
198         url = request.url();
199     
200 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
201         if (m_user.isEmpty() && m_password.isEmpty())
202             m_initialCredential = m_session->networkStorageSession().credentialStorage().get(m_partition, url);
203         else
204             m_session->networkStorageSession().credentialStorage().set(m_partition, WebCore::Credential(m_user, m_password, WebCore::CredentialPersistenceNone), url);
205 #endif
206     }
207
208 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
209     if (!m_initialCredential.isEmpty()) {
210         // FIXME: Support Digest authentication, and Proxy-Authorization.
211         applyBasicAuthorizationHeader(request, m_initialCredential);
212     }
213 #endif
214
215     bool shouldBlockCookies = false;
216 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
217     shouldBlockCookies = session.networkStorageSession().shouldBlockCookies(request, frameID, pageID);
218 #endif
219     if (shouldBlockCookies || (m_session->sessionID().isEphemeral() && isThirdPartyRequest(request)))
220         request.setExistingHTTPReferrerToOriginString();
221
222     NSURLRequest *nsRequest = request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::UpdateHTTPBody);
223     applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(nsRequest, shouldContentSniff == WebCore::ContentSniffingPolicy::SniffContent && !url.isLocalFile(), shouldContentEncodingSniff == WebCore::ContentEncodingSniffingPolicy::Sniff);
224 #if ENABLE(PROXIMITY_NETWORKING)
225     NetworkProcess::singleton().proximityManager().applyProperties(request, *this, nsRequest);
226 #endif
227
228     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
229     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
230         m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
231         ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
232         cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
233         LOG(NetworkSession, "%llu Creating stateful NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
234     } else {
235         m_task = [cocoaSession.m_statelessSession dataTaskWithRequest:nsRequest];
236         ASSERT(!cocoaSession.m_dataTaskMapWithoutState.contains([m_task taskIdentifier]));
237         cocoaSession.m_dataTaskMapWithoutState.add([m_task taskIdentifier], this);
238         LOG(NetworkSession, "%llu Creating stateless NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
239     }
240
241     if (shouldPreconnectOnly == PreconnectOnly::Yes) {
242 #if ENABLE(SERVER_PRECONNECT)
243         m_task.get()._preconnect = true;
244 #else
245         ASSERT_NOT_REACHED();
246 #endif
247     }
248
249 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
250     if (shouldBlockCookies) {
251 #if !RELEASE_LOG_DISABLED
252         if (NetworkProcess::singleton().shouldLogCookieInformation())
253             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);
254 #else
255         LOG(NetworkSession, "%llu Blocking cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
256 #endif
257         applyCookieBlockingPolicy(shouldBlockCookies);
258     }
259 #endif
260
261     if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
262         m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
263
264     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
265
266 #if HAVE(NW_ACTIVITY)
267     if (networkActivityTracker)
268         m_task.get()._nw_activity = networkActivityTracker.value().getPlatformObject();
269 #endif
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(WebCore::AuthenticationChallenge&& challenge, ChallengeCompletionHandler&& completionHandler)
294 {
295     if (tryPasswordBasedAuthentication(challenge, completionHandler))
296         return;
297
298     if (m_client)
299         m_client->didReceiveChallenge(WTFMove(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, m_frameID, m_pageID);
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 #if !RELEASE_LOG_DISABLED
385         if (NetworkProcess::singleton().shouldLogCookieInformation())
386             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());
387 #else
388         LOG(NetworkSession, "%llu Not partitioning cookies for redirect URL %s", [m_task taskIdentifier], request.url().string().utf8().data());
389 #endif
390     }
391 #endif
392
393     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
394
395     if (m_client)
396         m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), WTFMove(completionHandler));
397     else {
398         ASSERT_NOT_REACHED();
399         completionHandler({ });
400     }
401 }
402
403 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
404 {
405     NetworkDataTask::setPendingDownloadLocation(filename, { }, allowOverwrite);
406
407     ASSERT(!m_sandboxExtension);
408     m_sandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
409     if (m_sandboxExtension)
410         m_sandboxExtension->consume();
411
412     m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
413
414     if (allowOverwrite && WebCore::FileSystem::fileExists(m_pendingDownloadLocation))
415         WebCore::FileSystem::deleteFile(filename);
416 }
417
418 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler& completionHandler)
419 {
420     if (!challenge.protectionSpace().isPasswordBased())
421         return false;
422     
423     if (!m_user.isNull() && !m_password.isNull()) {
424         auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
425         completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
426         m_user = String();
427         m_password = String();
428         return true;
429     }
430
431 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
432     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
433         if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
434             // The stored credential wasn't accepted, stop using it.
435             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
436             // but the observable effect should be very minor, if any.
437             m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
438         }
439
440         if (!challenge.previousFailureCount()) {
441             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
442             if (!credential.isEmpty() && credential != m_initialCredential) {
443                 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
444                 if (challenge.failureResponse().httpStatusCode() == 401) {
445                     // Store the credential back, possibly adding it as a default for this directory.
446                     m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
447                 }
448                 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
449                 return true;
450             }
451         }
452     }
453 #endif
454
455     if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
456         completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
457         return true;
458     }
459     
460     return false;
461 }
462
463 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
464 {
465     download.setSandboxExtension(WTFMove(m_sandboxExtension));
466 }
467
468 String NetworkDataTaskCocoa::suggestedFilename() const
469 {
470     if (!m_suggestedFilename.isEmpty())
471         return m_suggestedFilename;
472     return m_task.get().response.suggestedFilename;
473 }
474
475 void NetworkDataTaskCocoa::cancel()
476 {
477     [m_task cancel];
478 }
479
480 void NetworkDataTaskCocoa::resume()
481 {
482     if (m_scheduledFailureType != NoFailure)
483         m_failureTimer.startOneShot(0_s);
484     [m_task resume];
485 }
486
487 void NetworkDataTaskCocoa::suspend()
488 {
489     if (m_failureTimer.isActive())
490         m_failureTimer.stop();
491     [m_task suspend];
492 }
493
494 NetworkDataTask::State NetworkDataTaskCocoa::state() const
495 {
496     switch ([m_task state]) {
497     case NSURLSessionTaskStateRunning:
498         return State::Running;
499     case NSURLSessionTaskStateSuspended:
500         return State::Suspended;
501     case NSURLSessionTaskStateCanceling:
502         return State::Canceling;
503     case NSURLSessionTaskStateCompleted:
504         return State::Completed;
505     }
506
507     ASSERT_NOT_REACHED();
508     return State::Completed;
509 }
510
511 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
512 {
513     return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);
514 }
515
516 bool NetworkDataTaskCocoa::isAlwaysOnLoggingAllowed() const
517 {
518     if (NetworkProcess::singleton().sessionIsControlledByAutomation(m_session->sessionID()))
519         return true;
520
521     return m_session->sessionID().isAlwaysOnLoggingAllowed();
522 }
523
524 String NetworkDataTaskCocoa::description() const
525 {
526     return String([m_task description]);
527 }
528
529 }