a3b0da1d14c723f3de88fe21a7cb538ac2a6fc8d
[WebKit-https.git] / Source / WebCore / platform / network / mac / ResourceHandleMac.mm
1 /*
2  * Copyright (C) 2004, 2006, 2007, 2008, 2009, 2010, 2011, 2012 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. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #import "config.h"
27 #import "ResourceHandleInternal.h"
28
29 #import "AuthenticationChallenge.h"
30 #import "AuthenticationMac.h"
31 #import "BlockExceptions.h"
32 #import "CookieStorage.h"
33 #import "CredentialStorage.h"
34 #import "CachedResourceLoader.h"
35 #import "FormDataStreamMac.h"
36 #import "Frame.h"
37 #import "FrameLoader.h"
38 #import "HTTPHeaderNames.h"
39 #import "Logging.h"
40 #import "MIMETypeRegistry.h"
41 #import "NetworkingContext.h"
42 #import "Page.h"
43 #import "ResourceError.h"
44 #import "ResourceResponse.h"
45 #import "Settings.h"
46 #import "SharedBuffer.h"
47 #import "SubresourceLoader.h"
48 #import "WebCoreResourceHandleAsDelegate.h"
49 #import "WebCoreResourceHandleAsOperationQueueDelegate.h"
50 #import "SynchronousLoaderClient.h"
51 #import "WebCoreSystemInterface.h"
52 #import "WebCoreURLResponse.h"
53 #import <wtf/Ref.h>
54 #import <wtf/SchedulePair.h>
55 #import <wtf/text/Base64.h>
56 #import <wtf/text/CString.h>
57
58 #if USE(CFNETWORK)
59 #if __has_include(<CFNetwork/CFURLConnectionPriv.h>)
60 #import <CFNetwork/CFURLConnectionPriv.h>
61 #endif
62 typedef struct _CFURLConnection* CFURLConnectionRef;
63 extern "C" {
64 CFDictionaryRef _CFURLConnectionCopyTimingData(CFURLConnectionRef);
65 }
66 #endif // USE(CFNETWORK)
67
68 #if __has_include(<Foundation/NSURLConnectionPrivate.h>)
69 #import <Foundation/NSURLConnectionPrivate.h>
70 #else
71 @interface NSURLConnection (TimingData)
72 #if !HAVE(TIMINGDATAOPTIONS)
73 + (void)_setCollectsTimingData:(BOOL)collect;
74 #endif
75 - (NSDictionary *)_timingData;
76 @end
77 #endif
78
79 #if PLATFORM(IOS)
80 #import "CFNetworkSPI.h"
81 #import "RuntimeApplicationChecksIOS.h"
82 #import "WebCoreThreadRun.h"
83
84 @interface NSURLRequest (iOSDetails)
85 - (CFURLRequestRef) _CFURLRequest;
86 @end
87 #endif
88
89 #if USE(QUICK_LOOK)
90 #import "QuickLook.h"
91 #endif
92
93 using namespace WebCore;
94
95 @interface NSURLConnection (Details)
96 -(id)_initWithRequest:(NSURLRequest *)request delegate:(id)delegate usesCache:(BOOL)usesCacheFlag maxContentLength:(long long)maxContentLength startImmediately:(BOOL)startImmediately connectionProperties:(NSDictionary *)connectionProperties;
97 @end
98
99 namespace WebCore {
100     
101 #if !USE(CFNETWORK)
102     
103 static void applyBasicAuthorizationHeader(ResourceRequest& request, const Credential& credential)
104 {
105     String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
106
107     request.setHTTPHeaderField(HTTPHeaderName::Authorization, authenticationHeader);
108 }
109
110 static NSOperationQueue *operationQueueForAsyncClients()
111 {
112     static NSOperationQueue *queue;
113     if (!queue) {
114         queue = [[NSOperationQueue alloc] init];
115         // Default concurrent operation count depends on current system workload, but delegate methods are mostly idling in IPC, so we can run as many as needed.
116         [queue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
117     }
118     return queue;
119 }
120
121 ResourceHandleInternal::~ResourceHandleInternal()
122 {
123 }
124
125 ResourceHandle::~ResourceHandle()
126 {
127     releaseDelegate();
128     d->m_currentWebChallenge.setAuthenticationClient(0);
129
130     LOG(Network, "Handle %p destroyed", this);
131 }
132
133 #if PLATFORM(IOS)
134 static bool synchronousWillSendRequestEnabled()
135 {
136     static bool disabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"WebKitDisableSynchronousWillSendRequestPreferenceKey"];
137     return !disabled;
138 }
139 #endif
140
141 #if !PLATFORM(IOS)
142 void ResourceHandle::createNSURLConnection(id delegate, bool shouldUseCredentialStorage, bool shouldContentSniff, SchedulingBehavior schedulingBehavior)
143 #else
144 void ResourceHandle::createNSURLConnection(id delegate, bool shouldUseCredentialStorage, bool shouldContentSniff, SchedulingBehavior schedulingBehavior, NSDictionary *connectionProperties)
145 #endif
146 {
147 #if ENABLE(WEB_TIMING)
148     setCollectsTimingData();
149 #endif
150
151     // Credentials for ftp can only be passed in URL, the connection:didReceiveAuthenticationChallenge: delegate call won't be made.
152     if ((!d->m_user.isEmpty() || !d->m_pass.isEmpty()) && !firstRequest().url().protocolIsInHTTPFamily()) {
153         URL urlWithCredentials(firstRequest().url());
154         urlWithCredentials.setUser(d->m_user);
155         urlWithCredentials.setPass(d->m_pass);
156         firstRequest().setURL(urlWithCredentials);
157     }
158
159     if (shouldUseCredentialStorage && firstRequest().url().protocolIsInHTTPFamily()) {
160         if (d->m_user.isEmpty() && d->m_pass.isEmpty()) {
161             // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
162             // try and reuse the credential preemptively, as allowed by RFC 2617.
163             d->m_initialCredential = d->m_context->storageSession().credentialStorage().get(firstRequest().url());
164         } else {
165             // If there is already a protection space known for the URL, update stored credentials before sending a request.
166             // This makes it possible to implement logout by sending an XMLHttpRequest with known incorrect credentials, and aborting it immediately
167             // (so that an authentication dialog doesn't pop up).
168             d->m_context->storageSession().credentialStorage().set(Credential(d->m_user, d->m_pass, CredentialPersistenceNone), firstRequest().url());
169         }
170     }
171         
172     if (!d->m_initialCredential.isEmpty()) {
173         // FIXME: Support Digest authentication, and Proxy-Authorization.
174         applyBasicAuthorizationHeader(firstRequest(), d->m_initialCredential);
175     }
176
177     NSURLRequest *nsRequest = firstRequest().nsURLRequest(UpdateHTTPBody);
178     if (!shouldContentSniff) {
179         NSMutableURLRequest *mutableRequest = [[nsRequest mutableCopy] autorelease];
180         wkSetNSURLRequestShouldContentSniff(mutableRequest, NO);
181         nsRequest = mutableRequest;
182     }
183
184     if (d->m_storageSession)
185         nsRequest = [wkCopyRequestWithStorageSession(d->m_storageSession.get(), nsRequest) autorelease];
186
187     ASSERT([NSURLConnection instancesRespondToSelector:@selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)]);
188
189 #if PLATFORM(IOS)
190     // FIXME: This code is different from iOS code in ResourceHandleCFNet.cpp in that here we respect stream properties that were present in client properties.
191     NSDictionary *streamPropertiesFromClient = [connectionProperties objectForKey:@"kCFURLConnectionSocketStreamProperties"];
192     NSMutableDictionary *streamProperties = streamPropertiesFromClient ? [[streamPropertiesFromClient mutableCopy] autorelease] : [NSMutableDictionary dictionary];
193 #else
194     NSMutableDictionary *streamProperties = [NSMutableDictionary dictionary];
195 #endif
196
197     if (!shouldUseCredentialStorage) {
198         // Avoid using existing connections, because they may be already authenticated.
199         [streamProperties setObject:@"WebKitPrivateSession" forKey:@"_kCFURLConnectionSessionID"];
200     }
201
202     if (schedulingBehavior == SchedulingBehavior::Synchronous) {
203         // Synchronous requests should not be subject to regular connection count limit to avoid deadlocks.
204         // If we are using all available connections for async requests, and make a sync request, then prior
205         // requests may get stuck waiting for delegate calls while we are in nested run loop, and the sync
206         // request won't start because there are no available connections.
207         // Connections are grouped by their socket stream properties, with each group having a separate count.
208         [streamProperties setObject:@TRUE forKey:@"_WebKitSynchronousRequest"];
209     }
210
211     RetainPtr<CFDataRef> sourceApplicationAuditData = d->m_context->sourceApplicationAuditData();
212     if (sourceApplicationAuditData)
213         [streamProperties setObject:(NSData *)sourceApplicationAuditData.get() forKey:@"kCFStreamPropertySourceApplication"];
214
215 #if PLATFORM(IOS)
216     NSMutableDictionary *propertyDictionary = [NSMutableDictionary dictionaryWithDictionary:connectionProperties];
217     [propertyDictionary setObject:streamProperties forKey:@"kCFURLConnectionSocketStreamProperties"];
218     const bool usesCache = false;
219     if (synchronousWillSendRequestEnabled())
220         CFURLRequestSetShouldStartSynchronously([nsRequest _CFURLRequest], 1);
221 #else
222     NSMutableDictionary *propertyDictionary = [NSMutableDictionary dictionaryWithObject:streamProperties forKey:@"kCFURLConnectionSocketStreamProperties"];
223     const bool usesCache = true;
224 #endif
225 #if HAVE(TIMINGDATAOPTIONS)
226     const int64_t TimingDataOptionsEnableW3CNavigationTiming = (1 << 0);
227     [propertyDictionary setObject:@{@"_kCFURLConnectionPropertyTimingDataOptions": @(TimingDataOptionsEnableW3CNavigationTiming)} forKey:@"kCFURLConnectionURLConnectionProperties"];
228 #endif
229     d->m_connection = adoptNS([[NSURLConnection alloc] _initWithRequest:nsRequest delegate:delegate usesCache:usesCache maxContentLength:0 startImmediately:NO connectionProperties:propertyDictionary]);
230 }
231
232 bool ResourceHandle::start()
233 {
234     if (!d->m_context)
235         return false;
236
237     BEGIN_BLOCK_OBJC_EXCEPTIONS;
238
239     // If NetworkingContext is invalid then we are no longer attached to a Page,
240     // this must be an attempted load from an unload event handler, so let's just block it.
241     if (!d->m_context->isValid())
242         return false;
243
244     d->m_storageSession = d->m_context->storageSession().platformSession();
245
246     // FIXME: Do not use the sync version of shouldUseCredentialStorage when the client returns true from usesAsyncCallbacks.
247     bool shouldUseCredentialStorage = !client() || client()->shouldUseCredentialStorage(this);
248
249     SchedulingBehavior schedulingBehavior = client() && client()->loadingSynchronousXHR() ? SchedulingBehavior::Synchronous : SchedulingBehavior::Asynchronous;
250
251 #if !PLATFORM(IOS)
252     createNSURLConnection(
253         ResourceHandle::makeDelegate(shouldUseCredentialStorage),
254         shouldUseCredentialStorage,
255         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
256         schedulingBehavior);
257 #else
258     createNSURLConnection(
259         ResourceHandle::makeDelegate(shouldUseCredentialStorage),
260         shouldUseCredentialStorage,
261         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
262         schedulingBehavior,
263         (NSDictionary *)client()->connectionProperties(this).get());
264 #endif
265
266     bool scheduled = false;
267     if (SchedulePairHashSet* scheduledPairs = d->m_context->scheduledRunLoopPairs()) {
268         SchedulePairHashSet::iterator end = scheduledPairs->end();
269         for (SchedulePairHashSet::iterator it = scheduledPairs->begin(); it != end; ++it) {
270             if (NSRunLoop *runLoop = (*it)->nsRunLoop()) {
271                 [connection() scheduleInRunLoop:runLoop forMode:(NSString *)(*it)->mode()];
272                 scheduled = true;
273             }
274         }
275     }
276
277     if (d->m_usesAsyncCallbacks) {
278         ASSERT(!scheduled);
279         [connection() setDelegateQueue:operationQueueForAsyncClients()];
280         scheduled = true;
281     }
282 #if PLATFORM(IOS)
283     else {
284         [connection() scheduleInRunLoop:WebThreadNSRunLoop() forMode:NSDefaultRunLoopMode];
285         scheduled = true;
286     }
287 #endif
288
289     // Start the connection if we did schedule with at least one runloop.
290     // We can't start the connection until we have one runloop scheduled.
291     if (scheduled)
292         [connection() start];
293     else
294         d->m_startWhenScheduled = true;
295
296     LOG(Network, "Handle %p starting connection %p for %@", this, connection(), firstRequest().nsURLRequest(DoNotUpdateHTTPBody));
297     
298     if (d->m_connection) {
299         if (d->m_defersLoading)
300             wkSetNSURLConnectionDefersCallbacks(connection(), YES);
301
302         return true;
303     }
304
305     END_BLOCK_OBJC_EXCEPTIONS;
306
307     return false;
308 }
309
310 void ResourceHandle::cancel()
311 {
312     LOG(Network, "Handle %p cancel connection %p", this, d->m_connection.get());
313
314     // Leaks were seen on HTTP tests without this; can be removed once <rdar://problem/6886937> is fixed.
315     if (d->m_currentMacChallenge)
316         [[d->m_currentMacChallenge sender] cancelAuthenticationChallenge:d->m_currentMacChallenge];
317
318     [d->m_connection.get() cancel];
319 }
320
321 void ResourceHandle::platformSetDefersLoading(bool defers)
322 {
323     if (d->m_connection)
324         wkSetNSURLConnectionDefersCallbacks(d->m_connection.get(), defers);
325 }
326
327 #if PLATFORM(MAC)
328
329 void ResourceHandle::schedule(SchedulePair& pair)
330 {
331     NSRunLoop *runLoop = pair.nsRunLoop();
332     if (!runLoop)
333         return;
334     [d->m_connection.get() scheduleInRunLoop:runLoop forMode:(NSString *)pair.mode()];
335     if (d->m_startWhenScheduled) {
336         [d->m_connection.get() start];
337         d->m_startWhenScheduled = false;
338     }
339 }
340
341 void ResourceHandle::unschedule(SchedulePair& pair)
342 {
343     if (NSRunLoop *runLoop = pair.nsRunLoop())
344         [d->m_connection.get() unscheduleFromRunLoop:runLoop forMode:(NSString *)pair.mode()];
345 }
346
347 #endif
348
349 id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage)
350 {
351     ASSERT(!d->m_delegate);
352
353     id <NSURLConnectionDelegate> delegate;
354     if (d->m_usesAsyncCallbacks) {
355         if (shouldUseCredentialStorage)
356             delegate = [[WebCoreResourceHandleAsOperationQueueDelegate alloc] initWithHandle:this];
357         else
358             delegate = [[WebCoreResourceHandleWithCredentialStorageAsOperationQueueDelegate alloc] initWithHandle:this];
359     } else
360         delegate = [[WebCoreResourceHandleAsDelegate alloc] initWithHandle:this];
361
362     d->m_delegate = delegate;
363     [delegate release];
364
365     return d->m_delegate.get();
366 }
367
368 id ResourceHandle::delegate()
369 {
370     if (!d->m_delegate)
371         return makeDelegate(false);
372     return d->m_delegate.get();
373 }
374
375 void ResourceHandle::releaseDelegate()
376 {
377     if (!d->m_delegate)
378         return;
379     [d->m_delegate.get() detachHandle];
380     d->m_delegate = nil;
381 }
382
383 NSURLConnection *ResourceHandle::connection() const
384 {
385     return d->m_connection.get();
386 }
387     
388 CFStringRef ResourceHandle::synchronousLoadRunLoopMode()
389 {
390     return CFSTR("WebCoreSynchronousLoaderRunLoopMode");
391 }
392
393 void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
394 {
395     LOG(Network, "ResourceHandle::platformLoadResourceSynchronously:%@ allowStoredCredentials:%u", request.nsURLRequest(DoNotUpdateHTTPBody), storedCredentials);
396
397     ASSERT(!request.isEmpty());
398     
399     SynchronousLoaderClient client;
400     client.setAllowStoredCredentials(storedCredentials == AllowStoredCredentials);
401
402     RefPtr<ResourceHandle> handle = adoptRef(new ResourceHandle(context, request, &client, false /*defersLoading*/, true /*shouldContentSniff*/));
403
404     handle->d->m_storageSession = context->storageSession().platformSession();
405
406     if (context && handle->d->m_scheduledFailureType != NoFailure) {
407         error = context->blockedError(request);
408         return;
409     }
410
411     bool shouldUseCredentialStorage = storedCredentials == AllowStoredCredentials;
412 #if !PLATFORM(IOS)
413     handle->createNSURLConnection(
414         handle->makeDelegate(shouldUseCredentialStorage),
415         shouldUseCredentialStorage,
416         handle->shouldContentSniff() || context->localFileContentSniffingEnabled(),
417         SchedulingBehavior::Synchronous);
418 #else
419     handle->createNSURLConnection(
420         handle->makeDelegate(shouldUseCredentialStorage), // A synchronous request cannot turn into a download, so there is no need to proxy the delegate.
421         shouldUseCredentialStorage,
422         handle->shouldContentSniff() || (context && context->localFileContentSniffingEnabled()),
423         SchedulingBehavior::Synchronous,
424         (NSDictionary *)handle->client()->connectionProperties(handle.get()).get());
425 #endif
426
427     [handle->connection() scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(NSString *)synchronousLoadRunLoopMode()];
428     [handle->connection() start];
429     
430     while (!client.isDone())
431         [[NSRunLoop currentRunLoop] runMode:(NSString *)synchronousLoadRunLoopMode() beforeDate:[NSDate distantFuture]];
432
433     error = client.error();
434     
435     [handle->connection() cancel];
436
437     if (error.isNull())
438         response = client.response();
439
440     data.swap(client.mutableData());
441 }
442
443 void ResourceHandle::willSendRequest(ResourceRequest& request, const ResourceResponse& redirectResponse)
444 {
445     ASSERT(!redirectResponse.isNull());
446
447     if (redirectResponse.httpStatusCode() == 307) {
448         String lastHTTPMethod = d->m_lastHTTPMethod;
449         if (!equalIgnoringCase(lastHTTPMethod, request.httpMethod())) {
450             request.setHTTPMethod(lastHTTPMethod);
451     
452             FormData* body = d->m_firstRequest.httpBody();
453             if (!equalIgnoringCase(lastHTTPMethod, "GET") && body && !body->isEmpty())
454                 request.setHTTPBody(body);
455
456             String originalContentType = d->m_firstRequest.httpContentType();
457             if (!originalContentType.isEmpty())
458                 request.setHTTPHeaderField(HTTPHeaderName::ContentType, originalContentType);
459         }
460     }
461
462     // Should not set Referer after a redirect from a secure resource to non-secure one.
463     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https") && d->m_context->shouldClearReferrerOnHTTPSToHTTPRedirect())
464         request.clearHTTPReferrer();
465
466     const URL& url = request.url();
467     d->m_user = url.user();
468     d->m_pass = url.pass();
469     d->m_lastHTTPMethod = request.httpMethod();
470     request.removeCredentials();
471
472     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
473         // The network layer might carry over some headers from the original request that
474         // we want to strip here because the redirect is cross-origin.
475         request.clearHTTPAuthorization();
476         request.clearHTTPOrigin();
477     } else {
478         // Only consider applying authentication credentials if this is actually a redirect and the redirect
479         // URL didn't include credentials of its own.
480         if (d->m_user.isEmpty() && d->m_pass.isEmpty() && !redirectResponse.isNull()) {
481             Credential credential = d->m_context->storageSession().credentialStorage().get(request.url());
482             if (!credential.isEmpty()) {
483                 d->m_initialCredential = credential;
484                 
485                 // FIXME: Support Digest authentication, and Proxy-Authorization.
486                 applyBasicAuthorizationHeader(request, d->m_initialCredential);
487             }
488         }
489     }
490
491     if (d->m_usesAsyncCallbacks) {
492         client()->willSendRequestAsync(this, request, redirectResponse);
493     } else {
494         Ref<ResourceHandle> protect(*this);
495         client()->willSendRequest(this, request, redirectResponse);
496
497         // Client call may not preserve the session, especially if the request is sent over IPC.
498         if (!request.isNull())
499             request.setStorageSession(d->m_storageSession.get());
500     }
501 }
502
503 void ResourceHandle::continueWillSendRequest(const ResourceRequest& request)
504 {
505     ASSERT(d->m_usesAsyncCallbacks);
506
507     // Client call may not preserve the session, especially if the request is sent over IPC.
508     ResourceRequest newRequest = request;
509     if (!newRequest.isNull())
510         newRequest.setStorageSession(d->m_storageSession.get());
511     [(id)delegate() continueWillSendRequest:newRequest.nsURLRequest(UpdateHTTPBody)];
512 }
513
514 void ResourceHandle::continueDidReceiveResponse()
515 {
516     ASSERT(d->m_usesAsyncCallbacks);
517
518     [delegate() continueDidReceiveResponse];
519 }
520
521 bool ResourceHandle::shouldUseCredentialStorage()
522 {
523     ASSERT(!d->m_usesAsyncCallbacks);
524     return client() && client()->shouldUseCredentialStorage(this);
525 }
526
527 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
528 {
529     ASSERT(!d->m_currentMacChallenge);
530     ASSERT(d->m_currentWebChallenge.isNull());
531     // Since NSURLConnection networking relies on keeping a reference to the original NSURLAuthenticationChallenge,
532     // we make sure that is actually present
533     ASSERT(challenge.nsURLAuthenticationChallenge());
534
535     // Proxy authentication is handled by CFNetwork internally. We can get here if the user cancels
536     // CFNetwork authentication dialog, and we shouldn't ask the client to display another one in that case.
537     if (challenge.protectionSpace().isProxy()) {
538         // Cannot use receivedRequestToContinueWithoutCredential(), because current challenge is not yet set.
539         [challenge.sender() continueWithoutCredentialForAuthenticationChallenge:challenge.nsURLAuthenticationChallenge()];
540         return;
541     }
542
543     if (tryHandlePasswordBasedAuthentication(challenge))
544         return;
545
546 #if PLATFORM(IOS)
547     // If the challenge is for a proxy protection space, look for default credentials in
548     // the keychain.  CFNetwork used to handle this until WebCore was changed to always
549     // return NO to -connectionShouldUseCredentialStorage: for <rdar://problem/7704943>.
550     if (!challenge.previousFailureCount() && challenge.protectionSpace().isProxy()) {
551         NSURLAuthenticationChallenge *macChallenge = mac(challenge);
552         if (NSURLCredential *credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:[macChallenge protectionSpace]]) {
553             [challenge.sender() useCredential:credential forAuthenticationChallenge:macChallenge];
554             return;
555         }
556     }
557 #endif // PLATFORM(IOS)
558
559     d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
560     d->m_currentWebChallenge = core(d->m_currentMacChallenge);
561     d->m_currentWebChallenge.setAuthenticationClient(this);
562
563     // FIXME: Several concurrent requests can return with the an authentication challenge for the same protection space.
564     // We should avoid making additional client calls for the same protection space when already waiting for the user,
565     // because typing the same credentials several times is annoying.
566     if (client())
567         client()->didReceiveAuthenticationChallenge(this, d->m_currentWebChallenge);
568     else {
569         clearAuthentication();
570         [challenge.sender() performDefaultHandlingForAuthenticationChallenge:challenge.nsURLAuthenticationChallenge()];
571     }
572 }
573
574 bool ResourceHandle::tryHandlePasswordBasedAuthentication(const AuthenticationChallenge& challenge)
575 {
576     if (!challenge.protectionSpace().isPasswordBased())
577         return false;
578
579     if (!d->m_user.isNull() && !d->m_pass.isNull()) {
580         NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:d->m_user
581                                                                    password:d->m_pass
582                                                                 persistence:NSURLCredentialPersistenceForSession];
583         d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
584         d->m_currentWebChallenge = challenge;
585         receivedCredential(challenge, Credential(credential));
586         [credential release];
587         // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly.
588         d->m_user = String();
589         d->m_pass = String();
590         return true;
591     }
592
593     // FIXME: Do not use the sync version of shouldUseCredentialStorage when the client returns true from usesAsyncCallbacks.
594     if (!client() || client()->shouldUseCredentialStorage(this)) {
595         if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
596             // The stored credential wasn't accepted, stop using it.
597             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
598             // but the observable effect should be very minor, if any.
599             d->m_context->storageSession().credentialStorage().remove(challenge.protectionSpace());
600         }
601
602         if (!challenge.previousFailureCount()) {
603             Credential credential = d->m_context->storageSession().credentialStorage().get(challenge.protectionSpace());
604             if (!credential.isEmpty() && credential != d->m_initialCredential) {
605                 ASSERT(credential.persistence() == CredentialPersistenceNone);
606                 if (challenge.failureResponse().httpStatusCode() == 401) {
607                     // Store the credential back, possibly adding it as a default for this directory.
608                     d->m_context->storageSession().credentialStorage().set(credential, challenge.protectionSpace(), challenge.failureResponse().url());
609                 }
610                 [challenge.sender() useCredential:credential.nsCredential() forAuthenticationChallenge:mac(challenge)];
611                 return true;
612             }
613         }
614     }
615
616     return false;
617 }
618
619 void ResourceHandle::didCancelAuthenticationChallenge(const AuthenticationChallenge& challenge)
620 {
621     ASSERT(d->m_currentMacChallenge);
622     ASSERT(d->m_currentMacChallenge == challenge.nsURLAuthenticationChallenge());
623     ASSERT(!d->m_currentWebChallenge.isNull());
624
625     if (client())
626         client()->didCancelAuthenticationChallenge(this, challenge);
627 }
628
629 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
630 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
631 {
632     ResourceHandleClient* client = this->client();
633     if (d->m_usesAsyncCallbacks) {
634         if (client)
635             client->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
636         else
637             continueCanAuthenticateAgainstProtectionSpace(false);
638         return false; // Ignored by caller.
639     }
640
641     return client && client->canAuthenticateAgainstProtectionSpace(this, protectionSpace);
642 }
643
644 void ResourceHandle::continueCanAuthenticateAgainstProtectionSpace(bool result)
645 {
646     ASSERT(d->m_usesAsyncCallbacks);
647
648     [(id)delegate() continueCanAuthenticateAgainstProtectionSpace:result];
649 }
650 #endif
651
652 void ResourceHandle::receivedCredential(const AuthenticationChallenge& challenge, const Credential& credential)
653 {
654     LOG(Network, "Handle %p receivedCredential", this);
655
656     ASSERT(!challenge.isNull());
657     if (challenge != d->m_currentWebChallenge)
658         return;
659
660     // FIXME: Support empty credentials. Currently, an empty credential cannot be stored in WebCore credential storage, as that's empty value for its map.
661     if (credential.isEmpty()) {
662         receivedRequestToContinueWithoutCredential(challenge);
663         return;
664     }
665
666     if (credential.persistence() == CredentialPersistenceForSession && challenge.protectionSpace().authenticationScheme() != ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
667         // Manage per-session credentials internally, because once NSURLCredentialPersistenceForSession is used, there is no way
668         // to ignore it for a particular request (short of removing it altogether).
669         Credential webCredential(credential, CredentialPersistenceNone);
670         URL urlToStore;
671         if (challenge.failureResponse().httpStatusCode() == 401)
672             urlToStore = challenge.failureResponse().url();
673         d->m_context->storageSession().credentialStorage().set(webCredential, ProtectionSpace([d->m_currentMacChallenge protectionSpace]), urlToStore);
674         [[d->m_currentMacChallenge sender] useCredential:webCredential.nsCredential() forAuthenticationChallenge:d->m_currentMacChallenge];
675     } else
676         [[d->m_currentMacChallenge sender] useCredential:credential.nsCredential() forAuthenticationChallenge:d->m_currentMacChallenge];
677
678     clearAuthentication();
679 }
680
681 void ResourceHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& challenge)
682 {
683     LOG(Network, "Handle %p receivedRequestToContinueWithoutCredential", this);
684
685     ASSERT(!challenge.isNull());
686     if (challenge != d->m_currentWebChallenge)
687         return;
688
689     [[d->m_currentMacChallenge sender] continueWithoutCredentialForAuthenticationChallenge:d->m_currentMacChallenge];
690
691     clearAuthentication();
692 }
693
694 void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challenge)
695 {
696     LOG(Network, "Handle %p receivedCancellation", this);
697
698     if (challenge != d->m_currentWebChallenge)
699         return;
700
701     if (client())
702         client()->receivedCancellation(this, challenge);
703 }
704
705 void ResourceHandle::receivedRequestToPerformDefaultHandling(const AuthenticationChallenge& challenge)
706 {
707     LOG(Network, "Handle %p receivedRequestToPerformDefaultHandling", this);
708
709     ASSERT(!challenge.isNull());
710     if (challenge != d->m_currentWebChallenge)
711         return;
712
713     [[d->m_currentMacChallenge sender] performDefaultHandlingForAuthenticationChallenge:d->m_currentMacChallenge];
714
715     clearAuthentication();
716 }
717
718 void ResourceHandle::receivedChallengeRejection(const AuthenticationChallenge& challenge)
719 {
720     LOG(Network, "Handle %p receivedChallengeRejection", this);
721
722     ASSERT(!challenge.isNull());
723     if (challenge != d->m_currentWebChallenge)
724         return;
725
726     [[d->m_currentMacChallenge sender] rejectProtectionSpaceAndContinueWithChallenge:d->m_currentMacChallenge];
727
728     clearAuthentication();
729 }
730
731 void ResourceHandle::continueWillCacheResponse(NSCachedURLResponse *response)
732 {
733     ASSERT(d->m_usesAsyncCallbacks);
734
735     [(id)delegate() continueWillCacheResponse:response];
736 }
737     
738 #endif // !USE(CFNETWORK)
739     
740 #if ENABLE(WEB_TIMING)
741     
742 void ResourceHandle::getConnectionTimingData(NSDictionary *timingData, ResourceLoadTiming& timing)
743 {
744     if (!timingData)
745         return;
746
747     // This is not the navigationStart time in monotonic time, but the other times are relative to this time
748     // and only the differences between times are stored.
749     double referenceStart = [[timingData valueForKey:@"_kCFNTimingDataFetchStart"] doubleValue];
750             
751     double domainLookupStart = [[timingData valueForKey:@"_kCFNTimingDataDomainLookupStart"] doubleValue];
752     double domainLookupEnd = [[timingData valueForKey:@"_kCFNTimingDataDomainLookupEnd"] doubleValue];
753     double connectStart = [[timingData valueForKey:@"_kCFNTimingDataConnectStart"] doubleValue];
754     double secureConnectionStart = [[timingData valueForKey:@"_kCFNTimingDataSecureConnectionStart"] doubleValue];
755     double connectEnd = [[timingData valueForKey:@"_kCFNTimingDataConnectEnd"] doubleValue];
756     double requestStart = [[timingData valueForKey:@"_kCFNTimingDataRequestStart"] doubleValue];
757     double responseStart = [[timingData valueForKey:@"_kCFNTimingDataResponseStart"] doubleValue];
758         
759     timing.domainLookupStart = domainLookupStart <= 0 ? -1 : (domainLookupStart - referenceStart) * 1000;
760     timing.domainLookupEnd = domainLookupEnd <= 0 ? -1 : (domainLookupEnd - referenceStart) * 1000;
761     timing.connectStart = connectStart <= 0 ? -1 : (connectStart - referenceStart) * 1000;
762     timing.secureConnectionStart = secureConnectionStart <= 0 ? -1 : (secureConnectionStart - referenceStart) * 1000;
763     timing.connectEnd = connectEnd <= 0 ? -1 : (connectEnd - referenceStart) * 1000;
764     timing.requestStart = requestStart <= 0 ? 0 : (requestStart - referenceStart) * 1000;
765     timing.responseStart = responseStart <= 0 ? 0 : (responseStart - referenceStart) * 1000;
766 }
767
768 void ResourceHandle::setCollectsTimingData()
769 {
770 #if !HAVE(TIMINGDATAOPTIONS)
771     static dispatch_once_t onceToken;
772     dispatch_once(&onceToken, ^{
773         [NSURLConnection _setCollectsTimingData:YES];
774     });
775 #endif
776 }
777
778 #if USE(CFNETWORK)
779     
780 void ResourceHandle::getConnectionTimingData(CFURLConnectionRef connection, ResourceLoadTiming& timing)
781 {
782     getConnectionTimingData((__bridge NSDictionary*)(adoptCF(_CFURLConnectionCopyTimingData(connection)).get()), timing);
783 }
784     
785 #else
786     
787 void ResourceHandle::getConnectionTimingData(NSURLConnection *connection, ResourceLoadTiming& timing)
788 {
789     getConnectionTimingData([connection _timingData], timing);
790 }
791     
792 #endif
793     
794 #endif // ENABLE(WEB_TIMING)
795
796 } // namespace WebCore
797