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