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