32cb6cf48e254a0dbb666e52241815b48fb5261a
[WebKit.git] / Source / WebKit2 / NetworkProcess / cocoa / NetworkDataTaskCocoa.mm
1 /*
2  * Copyright (C) 2016 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/CFNetworkSPI.h>
41 #import <WebCore/FileSystem.h>
42 #import <WebCore/NetworkStorageSession.h>
43 #import <WebCore/NotImplemented.h>
44 #import <WebCore/ResourceRequest.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::StoredCredentials storedCredentials, WebCore::ContentSniffingPolicy shouldContentSniff, bool shouldClearReferrerOnHTTPSToHTTPRedirect)
78     : NetworkDataTask(session, client, requestWithCredentials, storedCredentials, shouldClearReferrerOnHTTPSToHTTPRedirect)
79 {
80     if (m_scheduledFailureType != NoFailure)
81         return;
82
83     auto request = requestWithCredentials;
84     auto url = request.url();
85     if (storedCredentials == WebCore::AllowStoredCredentials && 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 (storedCredentials == WebCore::AllowStoredCredentials) {
115         m_task = [cocoaSession.m_sessionWithCredentialStorage dataTaskWithRequest:nsRequest];
116         ASSERT(!cocoaSession.m_dataTaskMapWithCredentials.contains([m_task taskIdentifier]));
117         cocoaSession.m_dataTaskMapWithCredentials.add([m_task taskIdentifier], this);
118     } else {
119         m_task = [cocoaSession.m_sessionWithoutCredentialStorage dataTaskWithRequest:nsRequest];
120         ASSERT(!cocoaSession.m_dataTaskMapWithoutCredentials.contains([m_task taskIdentifier]));
121         cocoaSession.m_dataTaskMapWithoutCredentials.add([m_task taskIdentifier], this);
122     }
123     LOG(NetworkSession, "%llu Creating NetworkDataTask with URL %s", [m_task taskIdentifier], nsRequest.URL.absoluteString.UTF8String);
124
125 #if HAVE(CFNETWORK_STORAGE_PARTITIONING)
126     String storagePartition = WebCore::cookieStoragePartition(request);
127     if (!storagePartition.isEmpty())
128         m_task.get()._storagePartitionIdentifier = storagePartition;
129 #endif
130
131     if (WebCore::ResourceRequest::resourcePrioritiesEnabled())
132         m_task.get().priority = toNSURLSessionTaskPriority(request.priority());
133 }
134
135 NetworkDataTaskCocoa::~NetworkDataTaskCocoa()
136 {
137     if (!m_task)
138         return;
139
140     auto& cocoaSession = static_cast<NetworkSessionCocoa&>(m_session.get());
141     if (m_storedCredentials == WebCore::StoredCredentials::AllowStoredCredentials) {
142         ASSERT(cocoaSession.m_dataTaskMapWithCredentials.get([m_task taskIdentifier]) == this);
143         cocoaSession.m_dataTaskMapWithCredentials.remove([m_task taskIdentifier]);
144     } else {
145         ASSERT(cocoaSession.m_dataTaskMapWithoutCredentials.get([m_task taskIdentifier]) == this);
146         cocoaSession.m_dataTaskMapWithoutCredentials.remove([m_task taskIdentifier]);
147     }
148 }
149
150 void NetworkDataTaskCocoa::didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend)
151 {
152     if (m_client)
153         m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
154 }
155
156 void NetworkDataTaskCocoa::didReceiveChallenge(const WebCore::AuthenticationChallenge& challenge, ChallengeCompletionHandler&& completionHandler)
157 {
158     // Proxy authentication is handled by CFNetwork internally. We can get here if the user cancels
159     // CFNetwork authentication dialog, and we shouldn't ask the client to display another one in that case.
160     if (challenge.protectionSpace().isProxy()) {
161         completionHandler(AuthenticationChallengeDisposition::UseCredential, { });
162         return;
163     }
164
165     if (tryPasswordBasedAuthentication(challenge, completionHandler))
166         return;
167
168     if (m_client)
169         m_client->didReceiveChallenge(challenge, WTFMove(completionHandler));
170     else {
171         ASSERT_NOT_REACHED();
172         completionHandler(AuthenticationChallengeDisposition::PerformDefaultHandling, { });
173     }
174 }
175
176 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& error, const WebCore::NetworkLoadMetrics& networkLoadMetrics)
177 {
178     if (m_client)
179         m_client->didCompleteWithError(error, networkLoadMetrics);
180 }
181
182 void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
183 {
184     if (m_client)
185         m_client->didReceiveData(WTFMove(data));
186 }
187
188 void NetworkDataTaskCocoa::willPerformHTTPRedirection(WebCore::ResourceResponse&& redirectResponse, WebCore::ResourceRequest&& request, RedirectCompletionHandler&& completionHandler)
189 {
190     if (redirectResponse.httpStatusCode() == 307 || redirectResponse.httpStatusCode() == 308) {
191         ASSERT(m_lastHTTPMethod == request.httpMethod());
192         WebCore::FormData* body = m_firstRequest.httpBody();
193         if (body && !body->isEmpty() && !equalLettersIgnoringASCIICase(m_lastHTTPMethod, "get"))
194             request.setHTTPBody(body);
195         
196         String originalContentType = m_firstRequest.httpContentType();
197         if (!originalContentType.isEmpty())
198             request.setHTTPHeaderField(WebCore::HTTPHeaderName::ContentType, originalContentType);
199     }
200     
201     // Should not set Referer after a redirect from a secure resource to non-secure one.
202     if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && WebCore::protocolIs(request.httpReferrer(), "https"))
203         request.clearHTTPReferrer();
204     
205     const auto& url = request.url();
206     m_user = url.user();
207     m_password = url.pass();
208     m_lastHTTPMethod = request.httpMethod();
209     request.removeCredentials();
210     
211     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
212         // The network layer might carry over some headers from the original request that
213         // we want to strip here because the redirect is cross-origin.
214         request.clearHTTPAuthorization();
215         request.clearHTTPOrigin();
216 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
217     } else {
218         // Only consider applying authentication credentials if this is actually a redirect and the redirect
219         // URL didn't include credentials of its own.
220         if (m_user.isEmpty() && m_password.isEmpty() && !redirectResponse.isNull()) {
221             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
222             if (!credential.isEmpty()) {
223                 m_initialCredential = credential;
224
225                 // FIXME: Support Digest authentication, and Proxy-Authorization.
226                 applyBasicAuthorizationHeader(request, m_initialCredential);
227             }
228         }
229 #endif
230     }
231     
232     if (m_client)
233         m_client->willPerformHTTPRedirection(WTFMove(redirectResponse), WTFMove(request), WTFMove(completionHandler));
234     else {
235         ASSERT_NOT_REACHED();
236         completionHandler({ });
237     }
238 }
239
240 void NetworkDataTaskCocoa::setPendingDownloadLocation(const WTF::String& filename, const SandboxExtension::Handle& sandboxExtensionHandle, bool allowOverwrite)
241 {
242     NetworkDataTask::setPendingDownloadLocation(filename, sandboxExtensionHandle, allowOverwrite);
243
244     ASSERT(!m_sandboxExtension);
245     m_sandboxExtension = SandboxExtension::create(sandboxExtensionHandle);
246     if (m_sandboxExtension)
247         m_sandboxExtension->consume();
248
249     m_task.get()._pathToDownloadTaskFile = m_pendingDownloadLocation;
250
251     if (allowOverwrite && WebCore::fileExists(m_pendingDownloadLocation))
252         WebCore::deleteFile(filename);
253 }
254
255 bool NetworkDataTaskCocoa::tryPasswordBasedAuthentication(const WebCore::AuthenticationChallenge& challenge, const ChallengeCompletionHandler& completionHandler)
256 {
257     if (!challenge.protectionSpace().isPasswordBased())
258         return false;
259     
260     if (!m_user.isNull() && !m_password.isNull()) {
261         auto persistence = m_storedCredentials == WebCore::StoredCredentials::AllowStoredCredentials ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
262         completionHandler(AuthenticationChallengeDisposition::UseCredential, WebCore::Credential(m_user, m_password, persistence));
263         m_user = String();
264         m_password = String();
265         return true;
266     }
267
268 #if USE(CREDENTIAL_STORAGE_WITH_NETWORK_SESSION)
269     if (m_storedCredentials == WebCore::AllowStoredCredentials) {
270         if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
271             // The stored credential wasn't accepted, stop using it.
272             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
273             // but the observable effect should be very minor, if any.
274             m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
275         }
276
277         if (!challenge.previousFailureCount()) {
278             auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
279             if (!credential.isEmpty() && credential != m_initialCredential) {
280                 ASSERT(credential.persistence() == WebCore::CredentialPersistenceNone);
281                 if (challenge.failureResponse().httpStatusCode() == 401) {
282                     // Store the credential back, possibly adding it as a default for this directory.
283                     m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
284                 }
285                 completionHandler(AuthenticationChallengeDisposition::UseCredential, credential);
286                 return true;
287             }
288         }
289     }
290 #endif
291
292     if (!challenge.proposedCredential().isEmpty() && !challenge.previousFailureCount()) {
293         completionHandler(AuthenticationChallengeDisposition::UseCredential, challenge.proposedCredential());
294         return true;
295     }
296     
297     return false;
298 }
299
300 void NetworkDataTaskCocoa::transferSandboxExtensionToDownload(Download& download)
301 {
302     download.setSandboxExtension(WTFMove(m_sandboxExtension));
303 }
304
305 #if !USE(CFURLCONNECTION)
306 static bool certificatesMatch(SecTrustRef trust1, SecTrustRef trust2)
307 {
308     if (!trust1 || !trust2)
309         return false;
310
311     CFIndex count1 = SecTrustGetCertificateCount(trust1);
312     CFIndex count2 = SecTrustGetCertificateCount(trust2);
313     if (count1 != count2)
314         return false;
315
316     for (CFIndex i = 0; i < count1; i++) {
317         auto cert1 = SecTrustGetCertificateAtIndex(trust1, i);
318         auto cert2 = SecTrustGetCertificateAtIndex(trust2, i);
319         RELEASE_ASSERT(cert1);
320         RELEASE_ASSERT(cert2);
321         if (!CFEqual(cert1, cert2))
322             return false;
323     }
324
325     return true;
326 }
327 #endif
328
329 bool NetworkDataTaskCocoa::allowsSpecificHTTPSCertificateForHost(const WebCore::AuthenticationChallenge& challenge)
330 {
331     const String& host = challenge.protectionSpace().host();
332     NSArray *certificates = [NSURLRequest allowsSpecificHTTPSCertificateForHost:host];
333     if (!certificates)
334         return false;
335     
336     bool requireServerCertificates = challenge.protectionSpace().authenticationScheme() == WebCore::ProtectionSpaceAuthenticationScheme::ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested;
337     RetainPtr<SecPolicyRef> policy = adoptCF(SecPolicyCreateSSL(requireServerCertificates, host.createCFString().get()));
338     
339     SecTrustRef trustRef = nullptr;
340     if (SecTrustCreateWithCertificates((CFArrayRef)certificates, policy.get(), &trustRef) != noErr)
341         return false;
342     RetainPtr<SecTrustRef> trust = adoptCF(trustRef);
343
344 #if USE(CFURLCONNECTION)
345     notImplemented();
346     return false;
347 #else
348     return certificatesMatch(trust.get(), challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust);
349 #endif
350 }
351
352 String NetworkDataTaskCocoa::suggestedFilename() const
353 {
354     if (!m_suggestedFilename.isEmpty())
355         return m_suggestedFilename;
356     return m_task.get().response.suggestedFilename;
357 }
358
359 void NetworkDataTaskCocoa::cancel()
360 {
361     [m_task cancel];
362 }
363
364 void NetworkDataTaskCocoa::resume()
365 {
366     if (m_scheduledFailureType != NoFailure)
367         m_failureTimer.startOneShot(0);
368     [m_task resume];
369 }
370
371 void NetworkDataTaskCocoa::suspend()
372 {
373     if (m_failureTimer.isActive())
374         m_failureTimer.stop();
375     [m_task suspend];
376 }
377
378 NetworkDataTask::State NetworkDataTaskCocoa::state() const
379 {
380     switch ([m_task state]) {
381     case NSURLSessionTaskStateRunning:
382         return State::Running;
383     case NSURLSessionTaskStateSuspended:
384         return State::Suspended;
385     case NSURLSessionTaskStateCanceling:
386         return State::Canceling;
387     case NSURLSessionTaskStateCompleted:
388         return State::Completed;
389     }
390
391     ASSERT_NOT_REACHED();
392     return State::Completed;
393 }
394
395 WebCore::Credential serverTrustCredential(const WebCore::AuthenticationChallenge& challenge)
396 {
397 #if USE(CFURLCONNECTION)
398     notImplemented();
399     return { };
400 #else
401     return WebCore::Credential([NSURLCredential credentialForTrust:challenge.nsURLAuthenticationChallenge().protectionSpace.serverTrust]);
402 #endif
403 }
404
405 }
406
407 #endif