Modernize version checks for same site cookie support
[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 "SessionTracker.h"
38 #import "WebCoreArgumentCoders.h"
39 #import <WebCore/AuthenticationChallenge.h>
40 #import <WebCore/FileSystem.h>
41 #import <WebCore/NetworkStorageSession.h>
42 #import <WebCore/NotImplemented.h>
43 #import <WebCore/ResourceRequest.h>
44 #import <pal/spi/cf/CFNetworkSPI.h>
45 #import <wtf/MainThread.h>
46 #import <wtf/ProcessPrivilege.h>
47 #import <wtf/text/Base64.h>
48
49 #if HAVE(NW_ACTIVITY)
50 #import <CFNetwork/CFNSURLConnection.h>
51 #endif
52
53 namespace WebKit {
54
55 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
56 static void applyBasicAuthorizationHeader(WebCore::ResourceRequest& request, const WebCore::Credential& credential)
57 {
58     String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
59     request.setHTTPHeaderField(WebCore::HTTPHeaderName::Authorization, authenticationHeader);
60 }
61 #endif
62
63 static float toNSURLSessionTaskPriority(WebCore::ResourceLoadPriority priority)
64 {
65     switch (priority) {
66     case WebCore::ResourceLoadPriority::VeryLow:
67         return 0;
68     case WebCore::ResourceLoadPriority::Low:
69         return 0.25;
70     case WebCore::ResourceLoadPriority::Medium:
71         return 0.5;
72     case WebCore::ResourceLoadPriority::High:
73         return 0.75;
74     case WebCore::ResourceLoadPriority::VeryHigh:
75         return 1;
76     }
77
78     ASSERT_NOT_REACHED();
79     return NSURLSessionTaskPriorityDefault;
80 }
81
82 void NetworkDataTaskCocoa::applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(__strong NSURLRequest *& nsRequest, bool shouldContentSniff, bool shouldContentEncodingSniff)
83 {
84 #if !PLATFORM(MAC)
85     UNUSED_PARAM(shouldContentEncodingSniff);
86 #elif __MAC_OS_X_VERSION_MIN_REQUIRED < 101400
87     shouldContentEncodingSniff = true;
88 #endif
89     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
90     if (shouldContentSniff
91         && shouldContentEncodingSniff
92         && cocoaSession.m_boundInterfaceIdentifier.isNull()
93         && !cocoaSession.m_proxyConfiguration)
94         return;
95
96     auto mutableRequest = adoptNS([nsRequest mutableCopy]);
97
98 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
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 (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
121         IGNORE_NULL_CHECK_WARNINGS_BEGIN
122 #endif
123         statelessCookieStorage.get() = adoptNS([[NSHTTPCookieStorage alloc] _initWithIdentifier:nil private:YES]);
124 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
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::registrableDomainsAreEqual(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, std::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     if (shouldBlockCookies || (m_session->sessionID().isEphemeral() && isThirdPartyRequest(request)))
200         request.setExistingHTTPReferrerToOriginString();
201
202     NSURLRequest *nsRequest = request.nsURLRequest(WebCore::HTTPBodyUpdatePolicy::UpdateHTTPBody);
203     applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(nsRequest, shouldContentSniff == WebCore::ContentSniffingPolicy::SniffContent && !url.isLocalFile(), shouldContentEncodingSniff == WebCore::ContentEncodingSniffingPolicy::Sniff);
204 #if ENABLE(PROXIMITY_NETWORKING)
205     NetworkProcess::singleton().proximityManager().applyProperties(request, *this, nsRequest);
206 #endif
207
208     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
209     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
210         m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
211         ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
212         cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
213         LOG(NetworkSession, "%llu Creating stateful NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
214     } else {
215         m_task = [cocoaSession.m_statelessSession dataTaskWithRequest:nsRequest];
216         ASSERT(!cocoaSession.m_dataTaskMapWithoutState.contains([m_task taskIdentifier]));
217         cocoaSession.m_dataTaskMapWithoutState.add([m_task taskIdentifier], this);
218         LOG(NetworkSession, "%llu Creating stateless NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
219     }
220
221     if (shouldPreconnectOnly == PreconnectOnly::Yes) {
222 #if ENABLE(SERVER_PRECONNECT)
223         m_task.get()._preconnect = true;
224 #else
225         ASSERT_NOT_REACHED();
226 #endif
227     }
228
229 #if ENABLE(RESOURCE_LOAD_STATISTICS)
230     if (shouldBlockCookies) {
231 #if !RELEASE_LOG_DISABLED
232         if (NetworkProcess::singleton().shouldLogCookieInformation())
233             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);
234 #else
235         LOG(NetworkSession, "%llu Blocking cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
236 #endif
237         applyCookieBlockingPolicy(shouldBlockCookies);
238     }
239 #endif
240
241     if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
242         m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
243
244     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
245
246 #if HAVE(NW_ACTIVITY)
247     if (networkActivityTracker)
248         m_task.get()._nw_activity = networkActivityTracker.value().getPlatformObject();
249 #endif
250 }
251
252 NetworkDataTaskCocoa::~NetworkDataTaskCocoa()
253 {
254     if (!m_task)
255         return;
256
257     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
258     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
259         ASSERT(cocoaSession.m_dataTaskMapWithCredentials.get([m_task taskIdentifier]) == this);
260         cocoaSession.m_dataTaskMapWithCredentials.remove([m_task taskIdentifier]);
261     } else {
262         ASSERT(cocoaSession.m_dataTaskMapWithoutState.get([m_task taskIdentifier]) == this);
263         cocoaSession.m_dataTaskMapWithoutState.remove([m_task taskIdentifier]);
264     }
265 }
266
267 void NetworkDataTaskCocoa::didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend)
268 {
269     if (m_client)
270         m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
271 }
272
273 void NetworkDataTaskCocoa::didReceiveChallenge(WebCore::AuthenticationChallenge&& challenge, ChallengeCompletionHandler&& completionHandler)
274 {
275     if (tryPasswordBasedAuthentication(challenge, completionHandler))
276         return;
277
278     if (m_client)
279         m_client->didReceiveChallenge(WTFMove(challenge), WTFMove(completionHandler));
280     else {
281         ASSERT_NOT_REACHED();
282         completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
283     }
284 }
285
286 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics& networkLoadMetrics)
287 {
288     if (m_client)
289         m_client->didCompleteWithError(error, networkLoadMetrics);
290 }
291
292 void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
293 {
294     if (m_client)
295         m_client->didReceiveData(WTFMove(data));
296 }
297
298 void NetworkDataTaskCocoa::willPerformHTTPRedirection(WebCore::ResourceResponse&& redirectResponse, WebCore::ResourceRequest&& request, RedirectCompletionHandler&& completionHandler)
299 {
300     if (redirectResponse.httpStatusCode() == 307 || redirectResponse.httpStatusCode() == 308) {
301         ASSERT(m_lastHTTPMethod == request.httpMethod());
302         WebCore::FormData* body = m_firstRequest.httpBody();
303         if (body && !body->isEmpty() && !equalLettersIgnoringASCIICase(m_lastHTTPMethod, "get"))
304             request.setHTTPBody(body);
305         
306         String originalContentType = m_firstRequest.httpContentType();
307         if (!originalContentType.isEmpty())
308             request.setHTTPHeaderField(WebCore::HTTPHeaderName::ContentType, originalContentType);
309     }
310     
311     // Should not set Referer after a redirect from a secure resource to non-secure one.
312     if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && WebCore::protocolIs(request.httpReferrer(), "https"))
313         request.clearHTTPReferrer();
314     
315     const auto& url = request.url();
316     m_user = url.user();
317     m_password = url.pass();
318     m_lastHTTPMethod = request.httpMethod();
319     request.removeCredentials();
320     
321     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
322         // The network layer might carry over some headers from the original request that
323         // we want to strip here because the redirect is cross-origin.
324         request.clearHTTPAuthorization();
325         request.clearHTTPOrigin();
326 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
327     } else {
328         // Only consider applying authentication credentials if this is actually a redirect and the redirect
329         // URL didn't include credentials of its own.
330         if (m_user.isEmpty() && m_password.isEmpty() && !redirectResponse.isNull()) {
331             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
332             if (!credential.isEmpty()) {
333                 m_initialCredential = credential;
334
335                 // FIXME: Support Digest authentication, and Proxy-Authorization.
336                 applyBasicAuthorizationHeader(request, m_initialCredential);
337             }
338         }
339 #endif
340     }
341
342     if (isTopLevelNavigation())
343         request.setFirstPartyForCookies(request.url());
344
345     bool shouldBlockCookies = false;
346 #if ENABLE(RESOURCE_LOAD_STATISTICS)
347     shouldBlockCookies = m_session->networkStorageSession().shouldBlockCookies(request, m_frameID, m_pageID);
348 #if !RELEASE_LOG_DISABLED
349     if (NetworkProcess::singleton().shouldLogCookieInformation())
350         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());
351 #else
352     LOG(NetworkSession, "%llu %s cookies for redirect URL %s", [m_task taskIdentifier], (shouldBlockCookies ? "Blocking" : "Not blocking"), request.url().string().utf8().data());
353 #endif
354 #endif
355
356     if (shouldBlockCookies || (m_session->sessionID().isEphemeral() && isThirdPartyRequest(request)))
357         request.setExistingHTTPReferrerToOriginString();
358
359 #if ENABLE(RESOURCE_LOAD_STATISTICS)
360     // Always apply the policy since blocking may need to be turned on or off in a redirect.
361     applyCookieBlockingPolicy(shouldBlockCookies);
362
363     if (!shouldBlockCookies) {
364 #if !RELEASE_LOG_DISABLED
365         if (NetworkProcess::singleton().shouldLogCookieInformation())
366             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());
367 #else
368         LOG(NetworkSession, "%llu Not partitioning cookies for redirect URL %s", [m_task taskIdentifier], request.url().string().utf8().data());
369 #endif
370     }
371 #endif
372
373     updateTaskWithFirstPartyForSameSiteCookies(m_task.get(), request);
374
375     if (m_client)
376         m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), WTFMove(completionHandler));
377     else {
378         ASSERT_NOT_REACHED();
379         completionHandler({ });
380     }
381 }
382
383 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
384 {
385     NetworkDataTask::setPendingDownloadLocation(filename, { }, allowOverwrite);
386
387     ASSERT(!m_sandboxExtension);
388     m_sandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
389     if (m_sandboxExtension)
390         m_sandboxExtension->consume();
391
392     m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
393
394     if (allowOverwrite && WebCore::FileSystem::fileExists(m_pendingDownloadLocation))
395         WebCore::FileSystem::deleteFile(filename);
396 }
397
398 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler& completionHandler)
399 {
400     if (!challenge.protectionSpace().isPasswordBased())
401         return false;
402     
403     if (!m_user.isNull() && !m_password.isNull()) {
404         auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
405         completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
406         m_user = String();
407         m_password = String();
408         return true;
409     }
410
411 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
412     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
413         if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
414             // The stored credential wasn't accepted, stop using it.
415             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
416             // but the observable effect should be very minor, if any.
417             m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
418         }
419
420         if (!challenge.previousFailureCount()) {
421             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
422             if (!credential.isEmpty() && credential != m_initialCredential) {
423                 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
424                 if (challenge.failureResponse().httpStatusCode() == 401) {
425                     // Store the credential back, possibly adding it as a default for this directory.
426                     m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
427                 }
428                 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
429                 return true;
430             }
431         }
432     }
433 #endif
434
435     if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
436         completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
437         return true;
438     }
439     
440     return false;
441 }
442
443 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
444 {
445     download.setSandboxExtension(WTFMove(m_sandboxExtension));
446 }
447
448 String NetworkDataTaskCocoa::suggestedFilename() const
449 {
450     if (!m_suggestedFilename.isEmpty())
451         return m_suggestedFilename;
452     return m_task.get().response.suggestedFilename;
453 }
454
455 void NetworkDataTaskCocoa::cancel()
456 {
457     [m_task cancel];
458 }
459
460 void NetworkDataTaskCocoa::resume()
461 {
462     if (m_scheduledFailureType != NoFailure)
463         m_failureTimer.startOneShot(0_s);
464     [m_task resume];
465 }
466
467 void NetworkDataTaskCocoa::suspend()
468 {
469     if (m_failureTimer.isActive())
470         m_failureTimer.stop();
471     [m_task suspend];
472 }
473
474 NetworkDataTask::State NetworkDataTaskCocoa::state() const
475 {
476     switch ([m_task state]) {
477     case NSURLSessionTaskStateRunning:
478         return State::Running;
479     case NSURLSessionTaskStateSuspended:
480         return State::Suspended;
481     case NSURLSessionTaskStateCanceling:
482         return State::Canceling;
483     case NSURLSessionTaskStateCompleted:
484         return State::Completed;
485     }
486
487     ASSERT_NOT_REACHED();
488     return State::Completed;
489 }
490
491 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
492 {
493     return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);
494 }
495
496 bool NetworkDataTaskCocoa::isAlwaysOnLoggingAllowed() const
497 {
498     if (NetworkProcess::singleton().sessionIsControlledByAutomation(m_session->sessionID()))
499         return true;
500
501     return m_session->sessionID().isAlwaysOnLoggingAllowed();
502 }
503
504 String NetworkDataTaskCocoa::description() const
505 {
506     return String([m_task description]);
507 }
508
509 }