09ff28d29698e907f9e45c291570918982fd57b3
[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 NetworkDataTaskCocoa::NetworkDataTaskCocoa(NetworkSession& session, NetworkDataTaskClient& client, const WebCore::ResourceRequest& requestWithCredentials, WebCore::StoredCredentialsPolicy storedCredentialsPolicy, WebCore::ContentSniffingPolicy shouldContentSniff, bool shouldClearReferrerOnHTTPSToHTTPRedirect, PreconnectOnly shouldPreconnectOnly)
78     : NetworkDataTask(session, client, requestWithCredentials, storedCredentialsPolicy, shouldClearReferrerOnHTTPSToHTTPRedirect)
79 {
80     if (m_scheduledFailureType != NoFailure)
81         return;
82
83     auto request = requestWithCredentials;
84     auto url = request.url();
85     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use && url.protocolIsInHTTPFamily()) {
86         m_user = url.user();
87         m_password = url.pass();
88         request.removeCredentials();
89         url = request.url();
90     
91 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
92         if (m_user.isEmpty() && m_password.isEmpty())
93             m_initialCredential = m_session->networkStorageSession().credentialStorage().get(m_partition, url);
94         else
95             m_session->networkStorageSession().credentialStorage().set(m_partition, WebCore::Credential(m_user, m_password, WebCore::CredentialPersistenceNone), url);
96 #endif
97     }
98
99 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
100     if (!m_initialCredential.isEmpty()) {
101         // FIXME: Support Digest authentication, and Proxy-Authorization.
102         applyBasicAuthorizationHeader(request, m_initialCredential);
103     }
104 #endif
105     
106     NSURLRequest *nsRequest = request.nsURLRequest(WebCore::UpdateHTTPBody);
107     if (shouldContentSniff == WebCore::DoNotSniffContent || url.protocolIs("file")) {
108         NSMutableURLRequest *mutableRequest = [[nsRequest mutableCopy] autorelease];
109         [mutableRequest _setProperty:@(NO) forKey:(NSString *)_kCFURLConnectionPropertyShouldSniff];
110         nsRequest = mutableRequest;
111     }
112
113     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
114     if (session.networkStorageSession().shouldBlockCookies(request)) {
115         storedCredentialsPolicy = WebCore::StoredCredentialsPolicy::DoNotUse;
116         m_storedCredentialsPolicy = WebCore::StoredCredentialsPolicy::DoNotUse;
117     }
118
119     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
120         m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
121         ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
122         cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
123         LOG(NetworkSession, "%llu Creating stateless NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
124     } else {
125         m_task = [cocoaSession.m_statelessSession dataTaskWithRequest:nsRequest];
126         ASSERT(!cocoaSession.m_dataTaskMapWithoutState.contains([m_task taskIdentifier]));
127         cocoaSession.m_dataTaskMapWithoutState.add([m_task taskIdentifier], this);
128         LOG(NetworkSession, "%llu Creating NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
129     }
130
131     if (shouldPreconnectOnly == PreconnectOnly::Yes) {
132 #if ENABLE(SERVER_PRECONNECT)
133         m_task.get()._preconnect = true;
134 #else
135         ASSERT_NOT_REACHED();
136 #endif
137     }
138
139 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
140     if (storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
141         String storagePartition = session.networkStorageSession().cookieStoragePartition(request);
142         if (!storagePartition.isEmpty()) {
143             LOG(NetworkSession, "%llu Partitioning cookies for URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
144             m_task.get()._storagePartitionIdentifier = storagePartition;
145         }
146     }
147 #endif
148
149     if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
150         m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
151 }
152
153 NetworkDataTaskCocoa::~NetworkDataTaskCocoa()
154 {
155     if (!m_task)
156         return;
157
158     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
159     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
160         ASSERT(cocoaSession.m_dataTaskMapWithCredentials.get([m_task taskIdentifier]) == this);
161         cocoaSession.m_dataTaskMapWithCredentials.remove([m_task taskIdentifier]);
162     } else {
163         ASSERT(cocoaSession.m_dataTaskMapWithoutState.get([m_task taskIdentifier]) == this);
164         cocoaSession.m_dataTaskMapWithoutState.remove([m_task taskIdentifier]);
165     }
166 }
167
168 void NetworkDataTaskCocoa::didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend)
169 {
170     if (m_client)
171         m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
172 }
173
174 void NetworkDataTaskCocoa::didReceiveChallenge(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler&& completionHandler)
175 {
176     if (tryPasswordBasedAuthentication(challenge, completionHandler))
177         return;
178
179     if (m_client)
180         m_client->didReceiveChallenge(challenge, WTFMove(completionHandler));
181     else {
182         ASSERT_NOT_REACHED();
183         completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
184     }
185 }
186
187 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics& networkLoadMetrics)
188 {
189     if (m_client)
190         m_client->didCompleteWithError(error, networkLoadMetrics);
191 }
192
193 void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
194 {
195     if (m_client)
196         m_client->didReceiveData(WTFMove(data));
197 }
198
199 void NetworkDataTaskCocoa::willPerformHTTPRedirection(WebCore::ResourceResponse&& redirectResponse, WebCore::ResourceRequest&& request, RedirectCompletionHandler&& completionHandler)
200 {
201     if (redirectResponse.httpStatusCode() == 307 || redirectResponse.httpStatusCode() == 308) {
202         ASSERT(m_lastHTTPMethod == request.httpMethod());
203         WebCore::FormData* body = m_firstRequest.httpBody();
204         if (body && !body->isEmpty() && !equalLettersIgnoringASCIICase(m_lastHTTPMethod, "get"))
205             request.setHTTPBody(body);
206         
207         String originalContentType = m_firstRequest.httpContentType();
208         if (!originalContentType.isEmpty())
209             request.setHTTPHeaderField(WebCore::HTTPHeaderName::ContentType, originalContentType);
210     }
211     
212     // Should not set Referer after a redirect from a secure resource to non-secure one.
213     if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && WebCore::protocolIs(request.httpReferrer(), "https"))
214         request.clearHTTPReferrer();
215     
216     const auto& url = request.url();
217     m_user = url.user();
218     m_password = url.pass();
219     m_lastHTTPMethod = request.httpMethod();
220     request.removeCredentials();
221     
222     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
223         // The network layer might carry over some headers from the original request that
224         // we want to strip here because the redirect is cross-origin.
225         request.clearHTTPAuthorization();
226         request.clearHTTPOrigin();
227 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
228     } else {
229         // Only consider applying authentication credentials if this is actually a redirect and the redirect
230         // URL didn't include credentials of its own.
231         if (m_user.isEmpty() && m_password.isEmpty() && !redirectResponse.isNull()) {
232             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
233             if (!credential.isEmpty()) {
234                 m_initialCredential = credential;
235
236                 // FIXME: Support Digest authentication, and Proxy-Authorization.
237                 applyBasicAuthorizationHeader(request, m_initialCredential);
238             }
239         }
240 #endif
241     }
242     
243     if (m_client)
244         m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), WTFMove(completionHandler));
245     else {
246         ASSERT_NOT_REACHED();
247         completionHandler({ });
248     }
249 }
250
251 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, const SandboxExtension::Handle& sandboxExtensionHandle, bool allowOverwrite)
252 {
253     NetworkDataTask::setPendingDownloadLocation(filename, sandboxExtensionHandle, allowOverwrite);
254
255     ASSERT(!m_sandboxExtension);
256     m_sandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
257     if (m_sandboxExtension)
258         m_sandboxExtension->consume();
259
260     m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
261
262     if (allowOverwrite && WebCore::fileExists(m_pendingDownloadLocation))
263         WebCore::deleteFile(filename);
264 }
265
266 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler& completionHandler)
267 {
268     if (!challenge.protectionSpace().isPasswordBased())
269         return false;
270     
271     if (!m_user.isNull() && !m_password.isNull()) {
272         auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
273         completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
274         m_user = String();
275         m_password = String();
276         return true;
277     }
278
279 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
280     if (m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use) {
281         if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
282             // The stored credential wasn't accepted, stop using it.
283             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
284             // but the observable effect should be very minor, if any.
285             m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
286         }
287
288         if (!challenge.previousFailureCount()) {
289             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
290             if (!credential.isEmpty() && credential != m_initialCredential) {
291                 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
292                 if (challenge.failureResponse().httpStatusCode() == 401) {
293                     // Store the credential back, possibly adding it as a default for this directory.
294                     m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
295                 }
296                 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
297                 return true;
298             }
299         }
300     }
301 #endif
302
303     if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
304         completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
305         return true;
306     }
307     
308     return false;
309 }
310
311 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
312 {
313     download.setSandboxExtension(WTFMove(m_sandboxExtension));
314 }
315
316 String NetworkDataTaskCocoa::suggestedFilename() const
317 {
318     if (!m_suggestedFilename.isEmpty())
319         return m_suggestedFilename;
320     return m_task.get().response.suggestedFilename;
321 }
322
323 void NetworkDataTaskCocoa::cancel()
324 {
325     [m_task cancel];
326 }
327
328 void NetworkDataTaskCocoa::resume()
329 {
330     if (m_scheduledFailureType != NoFailure)
331         m_failureTimer.startOneShot(0_s);
332     [m_task resume];
333 }
334
335 void NetworkDataTaskCocoa::suspend()
336 {
337     if (m_failureTimer.isActive())
338         m_failureTimer.stop();
339     [m_task suspend];
340 }
341
342 NetworkDataTask::State NetworkDataTaskCocoa::state() const
343 {
344     switch ([m_task state]) {
345     case NSURLSessionTaskStateRunning:
346         return State::Running;
347     case NSURLSessionTaskStateSuspended:
348         return State::Suspended;
349     case NSURLSessionTaskStateCanceling:
350         return State::Canceling;
351     case NSURLSessionTaskStateCompleted:
352         return State::Completed;
353     }
354
355     ASSERT_NOT_REACHED();
356     return State::Completed;
357 }
358
359 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
360 {
361 #if USE(CFURLCONNECTION)
362     notImplemented();
363     return { };
364 #else
365     return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);
366 #endif
367 }
368
369 }
370
371 #endif