Add a FileSystem namespace to FileSystem.cpp
[WebKit-https.git] / Source / WebKit / NetworkProcess / cocoa / NetworkDataTaskCocoa.mm
1 /*
2  * Copyright (C) 2016-2017 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 #if USE(NETWORK_SESSION)
30
31 #import "AuthenticationManager.h"
32 #import "Download.h"
33 #import "DownloadProxyMessages.h"
34 #import "Logging.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>
47
48 namespace WebKit {
49
50 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
51 static void applyBasicAuthorizationHeader(WebCore::ResourceRequest& request, const WebCore::Credential& credential)
52 {
53     String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
54     request.setHTTPHeaderField(WebCore::HTTPHeaderName::Authorization, authenticationHeader);
55 }
56 #endif
57
58 static float toNSURLSessionTaskPriority(WebCore::ResourceLoadPriority priority)
59 {
60     switch (priority) {
61     case WebCore::ResourceLoadPriority::VeryLow:
62         return 0;
63     case WebCore::ResourceLoadPriority::Low:
64         return 0.25;
65     case WebCore::ResourceLoadPriority::Medium:
66         return 0.5;
67     case WebCore::ResourceLoadPriority::High:
68         return 0.75;
69     case WebCore::ResourceLoadPriority::VeryHigh:
70         return 1;
71     }
72
73     ASSERT_NOT_REACHED();
74     return NSURLSessionTaskPriorityDefault;
75 }
76
77 void NetworkDataTaskCocoa::applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(NSURLRequest*& nsRequest, bool shouldContentSniff, bool shouldContentEncodingSniff)
78 {
79 #if !PLATFORM(MAC)
80     UNUSED_PARAM(shouldContentEncodingSniff);
81 #elif __MAC_OS_X_VERSION_MIN_REQUIRED < 101302
82     shouldContentEncodingSniff = true;
83 #endif
84     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
85     if (shouldContentSniff && shouldContentEncodingSniff && cocoaSession.m_boundInterfaceIdentifier.isNull())
86         return;
87
88     auto mutableRequest = adoptNS([nsRequest mutableCopy]);
89
90 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101302
91     if (!shouldContentEncodingSniff)
92         [mutableRequest _setProperty:@(YES) forKey:(NSString *)kCFURLRequestContentDecoderSkipURLCheck];
93 #endif
94
95     if (!shouldContentSniff)
96         [mutableRequest _setProperty:@(NO) forKey:(NSString *)_kCFURLConnectionPropertyShouldSniff];
97
98     if (!cocoaSession.m_boundInterfaceIdentifier.isNull())
99         [mutableRequest setBoundInterfaceIdentifier:cocoaSession.m_boundInterfaceIdentifier];
100
101     nsRequest = mutableRequest.autorelease();
102 }
103
104 NetworkDataTaskCocoa::NetworkDataTaskCocoa(NetworkSession& session, NetworkDataTaskClient& client, const WebCore::ResourceRequest& requestWithCredentials, WebCore::StoredCredentialsPolicy storedCredentialsPolicy, WebCore::ContentSniffingPolicy shouldContentSniff, WebCore::ContentEncodingSniffingPolicy shouldContentEncodingSniff, bool shouldClearReferrerOnHTTPSToHTTPRedirect, PreconnectOnly shouldPreconnectOnly)
105     : NetworkDataTask(session, client, requestWithCredentials, storedCredentialsPolicy, shouldClearReferrerOnHTTPSToHTTPRedirect)
106 {
107     if (m_scheduledFailureType != NoFailure)
108         return;
109
110     auto request = requestWithCredentials;
111     auto url = request.url();
112     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use && url.protocolIsInHTTPFamily()) {
113         m_user = url.user();
114         m_password = url.pass();
115         request.removeCredentials();
116         url = request.url();
117     
118 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
119         if (m_user.isEmpty() && m_password.isEmpty())
120             m_initialCredential = m_session->networkStorageSession().credentialStorage().get(m_partition, url);
121         else
122             m_session->networkStorageSession().credentialStorage().set(m_partition, WebCore::Credential(m_user, m_password, WebCore::CredentialPersistenceNone), url);
123 #endif
124     }
125
126 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
127     if (!m_initialCredential.isEmpty()) {
128         // FIXME: Support Digest authentication, and Proxy-Authorization.
129         applyBasicAuthorizationHeader(request, m_initialCredential);
130     }
131 #endif
132     
133     NSURLRequest *nsRequest = request.nsURLRequest(WebCore::UpdateHTTPBody);
134     applySniffingPoliciesAndBindRequestToInferfaceIfNeeded(nsRequest, shouldContentSniff == WebCore::SniffContent && !url.isLocalFile(), shouldContentEncodingSniff == WebCore::ContentEncodingSniffingPolicy::Sniff);
135
136     if (session.networkStorageSession().shouldBlockCookies(request)) {
137         storedCredentialsPolicy = WebCore::StoredCredentialsPolicy::DoNotUse;
138         m_storedCredentialsPolicy = WebCore::StoredCredentialsPolicy::DoNotUse;
139     }
140
141     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
142     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
143         m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
144         ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
145         cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
146         LOG(NetworkSession, "%llu Creating stateless NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
147     } else {
148         m_task = [cocoaSession.m_statelessSession dataTaskWithRequest:nsRequest];
149         ASSERT(!cocoaSession.m_dataTaskMapWithoutState.contains([m_task taskIdentifier]));
150         cocoaSession.m_dataTaskMapWithoutState.add([m_task taskIdentifier], this);
151         LOG(NetworkSession, "%llu Creating NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
152     }
153
154     if (shouldPreconnectOnly == PreconnectOnly::Yes) {
155 #if ENABLE(SERVER_PRECONNECT)
156         m_task.get()._preconnect = true;
157 #else
158         ASSERT_NOT_REACHED();
159 #endif
160     }
161
162 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
163     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
164         String storagePartition = session.networkStorageSession().cookieStoragePartition(request);
165         if (!storagePartition.isEmpty()) {
166             LOG(NetworkSession, "%llu Partitioning cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
167             m_task.get()._storagePartitionIdentifier = storagePartition;
168         }
169     }
170 #endif
171
172     if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
173         m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
174 }
175
176 NetworkDataTaskCocoa::~NetworkDataTaskCocoa()
177 {
178     if (!m_task)
179         return;
180
181     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
182     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
183         ASSERT(cocoaSession.m_dataTaskMapWithCredentials.get([m_task taskIdentifier]) == this);
184         cocoaSession.m_dataTaskMapWithCredentials.remove([m_task taskIdentifier]);
185     } else {
186         ASSERT(cocoaSession.m_dataTaskMapWithoutState.get([m_task taskIdentifier]) == this);
187         cocoaSession.m_dataTaskMapWithoutState.remove([m_task taskIdentifier]);
188     }
189 }
190
191 void NetworkDataTaskCocoa::didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend)
192 {
193     if (m_client)
194         m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
195 }
196
197 void NetworkDataTaskCocoa::didReceiveChallenge(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler&& completionHandler)
198 {
199     if (tryPasswordBasedAuthentication(challenge, completionHandler))
200         return;
201
202     if (m_client)
203         m_client->didReceiveChallenge(challenge, WTFMove(completionHandler));
204     else {
205         ASSERT_NOT_REACHED();
206         completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
207     }
208 }
209
210 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics& networkLoadMetrics)
211 {
212     if (m_client)
213         m_client->didCompleteWithError(error, networkLoadMetrics);
214 }
215
216 void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
217 {
218     if (m_client)
219         m_client->didReceiveData(WTFMove(data));
220 }
221
222 static bool shouldChangePartition(const String& requiredStoragePartition, const String& currentStoragePartition)
223 {
224     // The need for a partion change is according to the following:
225     //      currentStoragePartition:  null  ""    abc
226     // requiredStoragePartition: ""   false false true
227     //                           abc  true  true  false
228     //                           xyz  true  true  true
229     return !((requiredStoragePartition.isEmpty() && currentStoragePartition.isEmpty()) || currentStoragePartition == requiredStoragePartition);
230 }
231
232 void NetworkDataTaskCocoa::willPerformHTTPRedirection(WebCore::ResourceResponse&& redirectResponse, WebCore::ResourceRequest&& request, RedirectCompletionHandler&& completionHandler)
233 {
234     if (redirectResponse.httpStatusCode() == 307 || redirectResponse.httpStatusCode() == 308) {
235         ASSERT(m_lastHTTPMethod == request.httpMethod());
236         WebCore::FormData* body = m_firstRequest.httpBody();
237         if (body && !body->isEmpty() && !equalLettersIgnoringASCIICase(m_lastHTTPMethod, "get"))
238             request.setHTTPBody(body);
239         
240         String originalContentType = m_firstRequest.httpContentType();
241         if (!originalContentType.isEmpty())
242             request.setHTTPHeaderField(WebCore::HTTPHeaderName::ContentType, originalContentType);
243     }
244     
245     // Should not set Referer after a redirect from a secure resource to non-secure one.
246     if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && WebCore::protocolIs(request.httpReferrer(), "https"))
247         request.clearHTTPReferrer();
248     
249     const auto& url = request.url();
250     m_user = url.user();
251     m_password = url.pass();
252     m_lastHTTPMethod = request.httpMethod();
253     request.removeCredentials();
254     
255     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
256         // The network layer might carry over some headers from the original request that
257         // we want to strip here because the redirect is cross-origin.
258         request.clearHTTPAuthorization();
259         request.clearHTTPOrigin();
260 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
261     } else {
262         // Only consider applying authentication credentials if this is actually a redirect and the redirect
263         // URL didn't include credentials of its own.
264         if (m_user.isEmpty() && m_password.isEmpty() && !redirectResponse.isNull()) {
265             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
266             if (!credential.isEmpty()) {
267                 m_initialCredential = credential;
268
269                 // FIXME: Support Digest authentication, and Proxy-Authorization.
270                 applyBasicAuthorizationHeader(request, m_initialCredential);
271             }
272         }
273 #endif
274     }
275     
276 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
277     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
278         String requiredStoragePartition = m_session->networkStorageSession().cookieStoragePartition(request);
279         if (shouldChangePartition(requiredStoragePartition, m_task.get()._storagePartitionIdentifier)) {
280             LOG(NetworkSession, "%llu %s cookies for redirected URL %s", [m_task taskIdentifier], (requiredStoragePartition.isEmpty() ? "Not partitioning" : "Partitioning"), request.url().string().utf8().data());
281             m_task.get()._storagePartitionIdentifier = requiredStoragePartition;
282         }
283     }
284 #endif
285
286     if (m_client)
287         m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), WTFMove(completionHandler));
288     else {
289         ASSERT_NOT_REACHED();
290         completionHandler({ });
291     }
292 }
293
294 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, const SandboxExtension::Handle& sandboxExtensionHandle, bool allowOverwrite)
295 {
296     NetworkDataTask::setPendingDownloadLocation(filename, sandboxExtensionHandle, allowOverwrite);
297
298     ASSERT(!m_sandboxExtension);
299     m_sandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
300     if (m_sandboxExtension)
301         m_sandboxExtension->consume();
302
303     m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
304
305     if (allowOverwrite && WebCore::FileSystem::fileExists(m_pendingDownloadLocation))
306         WebCore::FileSystem::deleteFile(filename);
307 }
308
309 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler& completionHandler)
310 {
311     if (!challenge.protectionSpace().isPasswordBased())
312         return false;
313     
314     if (!m_user.isNull() && !m_password.isNull()) {
315         auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
316         completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
317         m_user = String();
318         m_password = String();
319         return true;
320     }
321
322 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
323     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
324         if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
325             // The stored credential wasn't accepted, stop using it.
326             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
327             // but the observable effect should be very minor, if any.
328             m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
329         }
330
331         if (!challenge.previousFailureCount()) {
332             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
333             if (!credential.isEmpty() && credential != m_initialCredential) {
334                 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
335                 if (challenge.failureResponse().httpStatusCode() == 401) {
336                     // Store the credential back, possibly adding it as a default for this directory.
337                     m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
338                 }
339                 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
340                 return true;
341             }
342         }
343     }
344 #endif
345
346     if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
347         completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
348         return true;
349     }
350     
351     return false;
352 }
353
354 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
355 {
356     download.setSandboxExtension(WTFMove(m_sandboxExtension));
357 }
358
359 String NetworkDataTaskCocoa::suggestedFilename() const
360 {
361     if (!m_suggestedFilename.isEmpty())
362         return m_suggestedFilename;
363     return m_task.get().response.suggestedFilename;
364 }
365
366 void NetworkDataTaskCocoa::cancel()
367 {
368     [m_task cancel];
369 }
370
371 void NetworkDataTaskCocoa::resume()
372 {
373     if (m_scheduledFailureType != NoFailure)
374         m_failureTimer.startOneShot(0_s);
375     [m_task resume];
376 }
377
378 void NetworkDataTaskCocoa::suspend()
379 {
380     if (m_failureTimer.isActive())
381         m_failureTimer.stop();
382     [m_task suspend];
383 }
384
385 NetworkDataTask::State NetworkDataTaskCocoa::state() const
386 {
387     switch ([m_task state]) {
388     case NSURLSessionTaskStateRunning:
389         return State::Running;
390     case NSURLSessionTaskStateSuspended:
391         return State::Suspended;
392     case NSURLSessionTaskStateCanceling:
393         return State::Canceling;
394     case NSURLSessionTaskStateCompleted:
395         return State::Completed;
396     }
397
398     ASSERT_NOT_REACHED();
399     return State::Completed;
400 }
401
402 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
403 {
404 #if USE(CFURLCONNECTION)
405     notImplemented();
406     return { };
407 #else
408     return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);
409 #endif
410 }
411
412 }
413
414 #endif