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