2 * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #import "NetworkDataTaskCocoa.h"
29 #if USE(NETWORK_SESSION)
31 #import "AuthenticationManager.h"
33 #import "DownloadProxyMessages.h"
35 #import "NetworkProcess.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/text/Base64.h>
50 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
51 static void applyBasicAuthorizationHeader(WebCore::ResourceRequest& request, const WebCore::Credential& credential)
53 String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
54 request.setHTTPHeaderField(WebCore::HTTPHeaderName::Authorization, authenticationHeader);
58 static float toNSURLSessionTaskPriority(WebCore::ResourceLoadPriority priority)
61 case WebCore::ResourceLoadPriority::VeryLow:
63 case WebCore::ResourceLoadPriority::Low:
65 case WebCore::ResourceLoadPriority::Medium:
67 case WebCore::ResourceLoadPriority::High:
69 case WebCore::ResourceLoadPriority::VeryHigh:
74 return NSURLSessionTaskPriorityDefault;
77 void NetworkDataTaskCocoa::applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(NSURLRequest*& nsRequest, bool shouldContentSniff, bool shouldContentEncodingSniff)
80 UNUSED_PARAM(shouldContentEncodingSniff);
81 #elif __MAC_OS_X_VERSION_MIN_REQUIRED < 101302
82 shouldContentEncodingSniff = true;
84 auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
85 if (shouldContentSniff && shouldContentEncodingSniff && cocoaSession.m_boundInterfaceIdentifier.isNull())
88 auto mutableRequest = adoptNS([nsRequest mutableCopy]);
90 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101302
91 if (!shouldContentEncodingSniff)
92 [mutableRequest _setProperty:@(YES) forKey:(NSString *)kCFURLRequestContentDecoderSkipURLCheck];
95 if (!shouldContentSniff)
96 [mutableRequest _setProperty:@(NO) forKey:(NSString *)_kCFURLConnectionPropertyShouldSniff];
98 if (!cocoaSession.m_boundInterfaceIdentifier.isNull())
99 [mutableRequest setBoundInterfaceIdentifier:cocoaSession.m_boundInterfaceIdentifier];
101 nsRequest = mutableRequest.autorelease();
104 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
105 NSHTTPCookieStorage *NetworkDataTaskCocoa::statelessCookieStorage()
107 static NeverDestroyed<RetainPtr<NSHTTPCookieStorage>> statelessCookieStorage;
108 if (!statelessCookieStorage.get()) {
109 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
110 #pragma clang diagnostic push
111 #pragma clang diagnostic ignored "-Wnonnull"
113 statelessCookieStorage.get() = adoptNS([[NSHTTPCookieStorage alloc] _initWithIdentifier:nil private:YES]);
114 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101300)
115 #pragma clang diagnostic pop
117 statelessCookieStorage.get().get().cookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever;
119 ASSERT(statelessCookieStorage.get().get().cookies.count == 0);
120 return statelessCookieStorage.get().get();
123 void NetworkDataTaskCocoa::applyCookieBlockingPolicy(bool shouldBlock)
125 if (shouldBlock == m_hasBeenSetToUseStatelessCookieStorage)
128 NSHTTPCookieStorage *storage = shouldBlock ? statelessCookieStorage(): m_session->networkStorageSession().nsCookieStorage();
129 [m_task performSelector:NSSelectorFromString(@"_setExplicitCookieStorage:") withObject:(NSObject*)storage._cookieStorage];
130 m_hasBeenSetToUseStatelessCookieStorage = shouldBlock;
133 void NetworkDataTaskCocoa::applyCookiePartitioningPolicy(const String& requiredStoragePartition, const String& currentStoragePartition)
135 // The need for a partion change is according to the following:
136 // currentStoragePartition: null "" abc
137 // requiredStoragePartition: "" false false true
138 // abc true true false
139 // xyz true true true
140 auto shouldChangePartition = !((requiredStoragePartition.isEmpty() && currentStoragePartition.isEmpty()) || currentStoragePartition == requiredStoragePartition);
141 if (shouldChangePartition)
142 m_task.get()._storagePartitionIdentifier = requiredStoragePartition;
146 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)
147 : NetworkDataTask(session, client, requestWithCredentials, storedCredentialsPolicy, shouldClearReferrerOnHTTPSToHTTPRedirect)
151 if (m_scheduledFailureType != NoFailure)
154 auto request = requestWithCredentials;
155 auto url = request.url();
156 if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use && url.protocolIsInHTTPFamily()) {
158 m_password = url.pass();
159 request.removeCredentials();
162 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
163 if (m_user.isEmpty() && m_password.isEmpty())
164 m_initialCredential = m_session->networkStorageSession().credentialStorage().get(m_partition, url);
166 m_session->networkStorageSession().credentialStorage().set(m_partition, WebCore::Credential(m_user, m_password, WebCore::CredentialPersistenceNone), url);
170 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
171 if (!m_initialCredential.isEmpty()) {
172 // FIXME: Support Digest authentication, and Proxy-Authorization.
173 applyBasicAuthorizationHeader(request, m_initialCredential);
177 NSURLRequest *nsRequest = request.nsURLRequest(WebCore::UpdateHTTPBody);
178 applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(nsRequest, shouldContentSniff == WebCore::SniffContent && !url.isLocalFile(), shouldContentEncodingSniff == WebCore::ContentEncodingSniffingPolicy::Sniff);
180 auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
181 if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
182 m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
183 ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
184 cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
185 LOG(NetworkSession, "%llu Creating stateless NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
187 m_task = [cocoaSession.m_statelessSession dataTaskWithRequest:nsRequest];
188 ASSERT(!cocoaSession.m_dataTaskMapWithoutState.contains([m_task taskIdentifier]));
189 cocoaSession.m_dataTaskMapWithoutState.add([m_task taskIdentifier], this);
190 LOG(NetworkSession, "%llu Creating NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
193 if (shouldPreconnectOnly == PreconnectOnly::Yes) {
194 #if ENABLE(SERVER_PRECONNECT)
195 m_task.get()._preconnect = true;
197 ASSERT_NOT_REACHED();
201 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
202 if (auto shouldBlockCookies = session.networkStorageSession().shouldBlockCookies(request)) {
203 LOG(NetworkSession, "%llu Blocking cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
204 applyCookieBlockingPolicy(shouldBlockCookies);
206 auto storagePartition = session.networkStorageSession().cookieStoragePartition(request, m_frameID, m_pageID);
207 if (!storagePartition.isEmpty()) {
208 LOG(NetworkSession, "%llu Partitioning cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
209 applyCookiePartitioningPolicy(storagePartition, emptyString());
214 if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
215 m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
218 NetworkDataTaskCocoa::~NetworkDataTaskCocoa()
223 auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
224 if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
225 ASSERT(cocoaSession.m_dataTaskMapWithCredentials.get([m_task taskIdentifier]) == this);
226 cocoaSession.m_dataTaskMapWithCredentials.remove([m_task taskIdentifier]);
228 ASSERT(cocoaSession.m_dataTaskMapWithoutState.get([m_task taskIdentifier]) == this);
229 cocoaSession.m_dataTaskMapWithoutState.remove([m_task taskIdentifier]);
233 void NetworkDataTaskCocoa::didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend)
236 m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
239 void NetworkDataTaskCocoa::didReceiveChallenge(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler&& completionHandler)
241 if (tryPasswordBasedAuthentication(challenge, completionHandler))
245 m_client->didReceiveChallenge(challenge, WTFMove(completionHandler));
247 ASSERT_NOT_REACHED();
248 completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
252 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics& networkLoadMetrics)
255 m_client->didCompleteWithError(error, networkLoadMetrics);
258 void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
261 m_client->didReceiveData(WTFMove(data));
264 void NetworkDataTaskCocoa::willPerformHTTPRedirection(WebCore::ResourceResponse&& redirectResponse, WebCore::ResourceRequest&& request, RedirectCompletionHandler&& completionHandler)
266 if (redirectResponse.httpStatusCode() == 307 || redirectResponse.httpStatusCode() == 308) {
267 ASSERT(m_lastHTTPMethod == request.httpMethod());
268 WebCore::FormData* body = m_firstRequest.httpBody();
269 if (body && !body->isEmpty() && !equalLettersIgnoringASCIICase(m_lastHTTPMethod, "get"))
270 request.setHTTPBody(body);
272 String originalContentType = m_firstRequest.httpContentType();
273 if (!originalContentType.isEmpty())
274 request.setHTTPHeaderField(WebCore::HTTPHeaderName::ContentType, originalContentType);
277 // Should not set Referer after a redirect from a secure resource to non-secure one.
278 if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && WebCore::protocolIs(request.httpReferrer(), "https"))
279 request.clearHTTPReferrer();
281 const auto& url = request.url();
283 m_password = url.pass();
284 m_lastHTTPMethod = request.httpMethod();
285 request.removeCredentials();
287 if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
288 // The network layer might carry over some headers from the original request that
289 // we want to strip here because the redirect is cross-origin.
290 request.clearHTTPAuthorization();
291 request.clearHTTPOrigin();
292 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
294 // Only consider applying authentication credentials if this is actually a redirect and the redirect
295 // URL didn't include credentials of its own.
296 if (m_user.isEmpty() && m_password.isEmpty() && !redirectResponse.isNull()) {
297 auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
298 if (!credential.isEmpty()) {
299 m_initialCredential = credential;
301 // FIXME: Support Digest authentication, and Proxy-Authorization.
302 applyBasicAuthorizationHeader(request, m_initialCredential);
308 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
309 auto shouldBlockCookies = m_session->networkStorageSession().shouldBlockCookies(request);
310 LOG(NetworkSession, "%llu %s cookies for redirect URL %s", [m_task taskIdentifier], (shouldBlockCookies ? "Blocking" : "Not blocking"), request.url().string().utf8().data());
311 applyCookieBlockingPolicy(shouldBlockCookies);
313 if (!shouldBlockCookies) {
314 auto requiredStoragePartition = m_session->networkStorageSession().cookieStoragePartition(request, m_frameID, m_pageID);
315 LOG(NetworkSession, "%llu %s cookies for redirect URL %s", [m_task taskIdentifier], (requiredStoragePartition.isEmpty() ? "Not partitioning" : "Partitioning"), request.url().string().utf8().data());
316 applyCookiePartitioningPolicy(requiredStoragePartition, m_task.get()._storagePartitionIdentifier);
321 m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), WTFMove(completionHandler));
323 ASSERT_NOT_REACHED();
324 completionHandler({ });
328 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, SandboxExtension::Handle&& sandboxExtensionHandle, bool allowOverwrite)
330 NetworkDataTask::setPendingDownloadLocation(filename, { }, allowOverwrite);
332 ASSERT(!m_sandboxExtension);
333 m_sandboxExtension = SandboxExtension::create(WTFMove(sandboxExtensionHandle));
334 if (m_sandboxExtension)
335 m_sandboxExtension->consume();
337 m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
339 if (allowOverwrite && WebCore::FileSystem::fileExists(m_pendingDownloadLocation))
340 WebCore::FileSystem::deleteFile(filename);
343 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler& completionHandler)
345 if (!challenge.protectionSpace().isPasswordBased())
348 if (!m_user.isNull() && !m_password.isNull()) {
349 auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
350 completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
352 m_password = String();
356 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
357 if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
358 if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
359 // The stored credential wasn't accepted, stop using it.
360 // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
361 // but the observable effect should be very minor, if any.
362 m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
365 if (!challenge.previousFailureCount()) {
366 auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
367 if (!credential.isEmpty() && credential != m_initialCredential) {
368 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
369 if (challenge.failureResponse().httpStatusCode() == 401) {
370 // Store the credential back, possibly adding it as a default for this directory.
371 m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
373 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
380 if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
381 completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
388 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
390 download.setSandboxExtension(WTFMove(m_sandboxExtension));
393 String NetworkDataTaskCocoa::suggestedFilename() const
395 if (!m_suggestedFilename.isEmpty())
396 return m_suggestedFilename;
397 return m_task.get().response.suggestedFilename;
400 void NetworkDataTaskCocoa::cancel()
405 void NetworkDataTaskCocoa::resume()
407 if (m_scheduledFailureType != NoFailure)
408 m_failureTimer.startOneShot(0_s);
412 void NetworkDataTaskCocoa::suspend()
414 if (m_failureTimer.isActive())
415 m_failureTimer.stop();
419 NetworkDataTask::State NetworkDataTaskCocoa::state() const
421 switch ([m_task state]) {
422 case NSURLSessionTaskStateRunning:
423 return State::Running;
424 case NSURLSessionTaskStateSuspended:
425 return State::Suspended;
426 case NSURLSessionTaskStateCanceling:
427 return State::Canceling;
428 case NSURLSessionTaskStateCompleted:
429 return State::Completed;
432 ASSERT_NOT_REACHED();
433 return State::Completed;
436 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
438 return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);