Fix the build.
[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 + (void)_setCollectsTimingData:(BOOL)collect;
73 - (NSDictionary *)_timingData;
74 @end
75 #endif
76
77 #if PLATFORM(IOS)
78 #import "CFURLRequestSPI.h"
79 #import "RuntimeApplicationChecksIOS.h"
80 #import "WebCoreThreadRun.h"
81
82 @interface NSURLRequest (iOSDetails)
83 - (CFURLRequestRef) _CFURLRequest;
84 @end
85 #endif
86
87 #if USE(QUICK_LOOK)
88 #import "QuickLook.h"
89 #endif
90
91 using namespace WebCore;
92
93 @interface NSURLConnection (Details)
94 -(id)_initWithRequest:(NSURLRequest *)request delegate:(id)delegate usesCache:(BOOL)usesCacheFlag maxContentLength:(long long)maxContentLength startImmediately:(BOOL)startImmediately connectionProperties:(NSDictionary *)connectionProperties;
95 @end
96
97 namespace WebCore {
98     
99 #if !USE(CFNETWORK)
100     
101 static void applyBasicAuthorizationHeader(ResourceRequest& request, const Credential& credential)
102 {
103     String authenticationHeader = "Basic " + base64Encode(String(credential.user() + ":" + credential.password()).utf8());
104
105     request.setHTTPHeaderField(HTTPHeaderName::Authorization, authenticationHeader);
106 }
107
108 #if !PLATFORM(IOS)
109 static NSOperationQueue *operationQueueForAsyncClients()
110 {
111     static NSOperationQueue *queue;
112     if (!queue) {
113         queue = [[NSOperationQueue alloc] init];
114         // 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.
115         [queue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
116     }
117     return queue;
118 }
119 #endif
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 = 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             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 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
212     RetainPtr<CFDataRef> sourceApplicationAuditData = d->m_context->sourceApplicationAuditData();
213     if (sourceApplicationAuditData)
214         [streamProperties setObject:(NSData *)sourceApplicationAuditData.get() forKey:@"kCFStreamPropertySourceApplication"];
215 #endif
216
217 #if PLATFORM(IOS)
218     NSMutableDictionary *propertyDictionary = [NSMutableDictionary dictionaryWithDictionary:connectionProperties];
219     [propertyDictionary setObject:streamProperties forKey:@"kCFURLConnectionSocketStreamProperties"];
220     const bool usesCache = false;
221     if (synchronousWillSendRequestEnabled())
222         CFURLRequestSetShouldStartSynchronously([nsRequest _CFURLRequest], 1);
223 #else
224     NSDictionary *propertyDictionary = [NSDictionary dictionaryWithObject:streamProperties forKey:@"kCFURLConnectionSocketStreamProperties"];
225     const bool usesCache = true;
226 #endif
227     d->m_connection = adoptNS([[NSURLConnection alloc] _initWithRequest:nsRequest delegate:delegate usesCache:usesCache maxContentLength:0 startImmediately:NO connectionProperties:propertyDictionary]);
228 }
229
230 bool ResourceHandle::start()
231 {
232     if (!d->m_context)
233         return false;
234
235     BEGIN_BLOCK_OBJC_EXCEPTIONS;
236
237     // If NetworkingContext is invalid then we are no longer attached to a Page,
238     // this must be an attempted load from an unload event handler, so let's just block it.
239     if (!d->m_context->isValid())
240         return false;
241
242     d->m_storageSession = d->m_context->storageSession().platformSession();
243
244     // FIXME: Do not use the sync version of shouldUseCredentialStorage when the client returns true from usesAsyncCallbacks.
245     bool shouldUseCredentialStorage = !client() || client()->shouldUseCredentialStorage(this);
246
247     d->m_needsSiteSpecificQuirks = d->m_context->needsSiteSpecificQuirks();
248
249 #if !PLATFORM(IOS)
250     createNSURLConnection(
251         ResourceHandle::makeDelegate(shouldUseCredentialStorage),
252         shouldUseCredentialStorage,
253         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
254         SchedulingBehavior::Asynchronous);
255 #else
256     createNSURLConnection(
257         ResourceHandle::makeDelegate(shouldUseCredentialStorage),
258         shouldUseCredentialStorage,
259         d->m_shouldContentSniff || d->m_context->localFileContentSniffingEnabled(),
260         SchedulingBehavior::Asynchronous,
261         (NSDictionary *)client()->connectionProperties(this).get());
262 #endif
263
264 #if PLATFORM(IOS)
265     NSURLConnection *urlConnection = connection();
266     [urlConnection scheduleInRunLoop:WebThreadNSRunLoop() forMode:NSDefaultRunLoopMode];
267     [urlConnection start];
268 #else
269     bool scheduled = false;
270     if (SchedulePairHashSet* scheduledPairs = d->m_context->scheduledRunLoopPairs()) {
271         SchedulePairHashSet::iterator end = scheduledPairs->end();
272         for (SchedulePairHashSet::iterator it = scheduledPairs->begin(); it != end; ++it) {
273             if (NSRunLoop *runLoop = (*it)->nsRunLoop()) {
274                 [connection() scheduleInRunLoop:runLoop forMode:(NSString *)(*it)->mode()];
275                 scheduled = true;
276             }
277         }
278     }
279
280     if (client() && client()->usesAsyncCallbacks()) {
281         ASSERT(!scheduled);
282         [connection() setDelegateQueue:operationQueueForAsyncClients()];
283         scheduled = true;
284     }
285
286     // Start the connection if we did schedule with at least one runloop.
287     // We can't start the connection until we have one runloop scheduled.
288     if (scheduled)
289         [connection() start];
290     else
291         d->m_startWhenScheduled = true;
292 #endif
293
294     LOG(Network, "Handle %p starting connection %p for %@", this, connection(), firstRequest().nsURLRequest(DoNotUpdateHTTPBody));
295     
296     if (d->m_connection) {
297         if (d->m_defersLoading)
298             wkSetNSURLConnectionDefersCallbacks(connection(), YES);
299
300         return true;
301     }
302
303     END_BLOCK_OBJC_EXCEPTIONS;
304
305     return false;
306 }
307
308 void ResourceHandle::cancel()
309 {
310     LOG(Network, "Handle %p cancel connection %p", this, d->m_connection.get());
311
312     // Leaks were seen on HTTP tests without this; can be removed once <rdar://problem/6886937> is fixed.
313     if (d->m_currentMacChallenge)
314         [[d->m_currentMacChallenge sender] cancelAuthenticationChallenge:d->m_currentMacChallenge];
315
316     [d->m_connection.get() cancel];
317 }
318
319 void ResourceHandle::platformSetDefersLoading(bool defers)
320 {
321     if (d->m_connection)
322         wkSetNSURLConnectionDefersCallbacks(d->m_connection.get(), defers);
323 }
324
325 #if PLATFORM(MAC)
326
327 void ResourceHandle::schedule(SchedulePair& pair)
328 {
329     NSRunLoop *runLoop = pair.nsRunLoop();
330     if (!runLoop)
331         return;
332     [d->m_connection.get() scheduleInRunLoop:runLoop forMode:(NSString *)pair.mode()];
333     if (d->m_startWhenScheduled) {
334         [d->m_connection.get() start];
335         d->m_startWhenScheduled = false;
336     }
337 }
338
339 void ResourceHandle::unschedule(SchedulePair& pair)
340 {
341     if (NSRunLoop *runLoop = pair.nsRunLoop())
342         [d->m_connection.get() unscheduleFromRunLoop:runLoop forMode:(NSString *)pair.mode()];
343 }
344
345 #endif
346
347 id ResourceHandle::makeDelegate(bool shouldUseCredentialStorage)
348 {
349     ASSERT(!d->m_delegate);
350
351     id <NSURLConnectionDelegate> delegate;
352     if (client() && client()->usesAsyncCallbacks()) {
353         if (shouldUseCredentialStorage)
354             delegate = [[WebCoreResourceHandleAsOperationQueueDelegate alloc] initWithHandle:this];
355         else
356             delegate = [[WebCoreResourceHandleWithCredentialStorageAsOperationQueueDelegate alloc] initWithHandle:this];
357     } else
358         delegate = [[WebCoreResourceHandleAsDelegate alloc] initWithHandle:this];
359
360     d->m_delegate = delegate;
361     [delegate release];
362
363     return d->m_delegate.get();
364 }
365
366 id ResourceHandle::delegate()
367 {
368     if (!d->m_delegate)
369         return makeDelegate(false);
370     return d->m_delegate.get();
371 }
372
373 void ResourceHandle::releaseDelegate()
374 {
375     if (!d->m_delegate)
376         return;
377     [d->m_delegate.get() detachHandle];
378     d->m_delegate = nil;
379 }
380
381 NSURLConnection *ResourceHandle::connection() const
382 {
383     return d->m_connection.get();
384 }
385     
386 bool ResourceHandle::loadsBlocked()
387 {
388     return false;
389 }
390
391 CFStringRef ResourceHandle::synchronousLoadRunLoopMode()
392 {
393     return CFSTR("WebCoreSynchronousLoaderRunLoopMode");
394 }
395
396 void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
397 {
398     LOG(Network, "ResourceHandle::platformLoadResourceSynchronously:%@ allowStoredCredentials:%u", request.nsURLRequest(DoNotUpdateHTTPBody), storedCredentials);
399
400     ASSERT(!request.isEmpty());
401     
402     OwnPtr<SynchronousLoaderClient> client = SynchronousLoaderClient::create();
403     client->setAllowStoredCredentials(storedCredentials == AllowStoredCredentials);
404
405     RefPtr<ResourceHandle> handle = adoptRef(new ResourceHandle(context, request, client.get(), false /*defersLoading*/, true /*shouldContentSniff*/));
406
407     handle->d->m_storageSession = context->storageSession().platformSession();
408
409     if (context && handle->d->m_scheduledFailureType != NoFailure) {
410         error = context->blockedError(request);
411         return;
412     }
413
414     bool shouldUseCredentialStorage = storedCredentials == AllowStoredCredentials;
415 #if !PLATFORM(IOS)
416     handle->createNSURLConnection(
417         handle->makeDelegate(shouldUseCredentialStorage),
418         shouldUseCredentialStorage,
419         handle->shouldContentSniff() || context->localFileContentSniffingEnabled(),
420         SchedulingBehavior::Synchronous);
421 #else
422     handle->createNSURLConnection(
423         handle->makeDelegate(shouldUseCredentialStorage), // A synchronous request cannot turn into a download, so there is no need to proxy the delegate.
424         shouldUseCredentialStorage,
425         handle->shouldContentSniff() || (context && context->localFileContentSniffingEnabled()),
426         SchedulingBehavior::Synchronous,
427         (NSDictionary *)handle->client()->connectionProperties(handle.get()).get());
428 #endif
429
430     [handle->connection() scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(NSString *)synchronousLoadRunLoopMode()];
431     [handle->connection() start];
432     
433     while (!client->isDone())
434         [[NSRunLoop currentRunLoop] runMode:(NSString *)synchronousLoadRunLoopMode() beforeDate:[NSDate distantFuture]];
435
436     error = client->error();
437     
438     [handle->connection() cancel];
439
440     if (error.isNull())
441         response = client->response();
442
443     data.swap(client->mutableData());
444 }
445
446 void ResourceHandle::willSendRequest(ResourceRequest& request, const ResourceResponse& redirectResponse)
447 {
448     ASSERT(!redirectResponse.isNull());
449
450     if (redirectResponse.httpStatusCode() == 307) {
451         String lastHTTPMethod = d->m_lastHTTPMethod;
452         if (!equalIgnoringCase(lastHTTPMethod, request.httpMethod())) {
453             request.setHTTPMethod(lastHTTPMethod);
454     
455             FormData* body = d->m_firstRequest.httpBody();
456             if (!equalIgnoringCase(lastHTTPMethod, "GET") && body && !body->isEmpty())
457                 request.setHTTPBody(body);
458
459             String originalContentType = d->m_firstRequest.httpContentType();
460             if (!originalContentType.isEmpty())
461                 request.setHTTPHeaderField(HTTPHeaderName::ContentType, originalContentType);
462         }
463     }
464
465     // Should not set Referer after a redirect from a secure resource to non-secure one.
466     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https") && d->m_context->shouldClearReferrerOnHTTPSToHTTPRedirect())
467         request.clearHTTPReferrer();
468
469     const URL& url = request.url();
470     d->m_user = url.user();
471     d->m_pass = url.pass();
472     d->m_lastHTTPMethod = request.httpMethod();
473     request.removeCredentials();
474
475     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) {
476         // If the network layer carries over authentication headers from the original request
477         // in a cross-origin redirect, we want to clear those headers here.
478         // As of Lion, CFNetwork no longer does this.
479         request.clearHTTPAuthorization();
480     } else {
481         // Only consider applying authentication credentials if this is actually a redirect and the redirect
482         // URL didn't include credentials of its own.
483         if (d->m_user.isEmpty() && d->m_pass.isEmpty() && !redirectResponse.isNull()) {
484             Credential credential = CredentialStorage::get(request.url());
485             if (!credential.isEmpty()) {
486                 d->m_initialCredential = credential;
487                 
488                 // FIXME: Support Digest authentication, and Proxy-Authorization.
489                 applyBasicAuthorizationHeader(request, d->m_initialCredential);
490             }
491         }
492     }
493
494     if (client()->usesAsyncCallbacks()) {
495         client()->willSendRequestAsync(this, request, redirectResponse);
496     } else {
497         Ref<ResourceHandle> protect(*this);
498         client()->willSendRequest(this, request, redirectResponse);
499
500         // Client call may not preserve the session, especially if the request is sent over IPC.
501         if (!request.isNull())
502             request.setStorageSession(d->m_storageSession.get());
503     }
504 }
505
506 void ResourceHandle::continueWillSendRequest(const ResourceRequest& request)
507 {
508     ASSERT(client());
509     ASSERT(client()->usesAsyncCallbacks());
510
511     // Client call may not preserve the session, especially if the request is sent over IPC.
512     ResourceRequest newRequest = request;
513     if (!newRequest.isNull())
514         newRequest.setStorageSession(d->m_storageSession.get());
515     [(id)delegate() continueWillSendRequest:newRequest.nsURLRequest(UpdateHTTPBody)];
516 }
517
518 void ResourceHandle::continueDidReceiveResponse()
519 {
520     ASSERT(client());
521     ASSERT(client()->usesAsyncCallbacks());
522
523     [delegate() continueDidReceiveResponse];
524 }
525
526 bool ResourceHandle::shouldUseCredentialStorage()
527 {
528     ASSERT(!client()->usesAsyncCallbacks());
529     return client() && client()->shouldUseCredentialStorage(this);
530 }
531
532 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
533 {
534     ASSERT(!d->m_currentMacChallenge);
535     ASSERT(d->m_currentWebChallenge.isNull());
536     // Since NSURLConnection networking relies on keeping a reference to the original NSURLAuthenticationChallenge,
537     // we make sure that is actually present
538     ASSERT(challenge.nsURLAuthenticationChallenge());
539
540     // Proxy authentication is handled by CFNetwork internally. We can get here if the user cancels
541     // CFNetwork authentication dialog, and we shouldn't ask the client to display another one in that case.
542     if (challenge.protectionSpace().isProxy()) {
543         // Cannot use receivedRequestToContinueWithoutCredential(), because current challenge is not yet set.
544         [challenge.sender() continueWithoutCredentialForAuthenticationChallenge:challenge.nsURLAuthenticationChallenge()];
545         return;
546     }
547
548     if (!d->m_user.isNull() && !d->m_pass.isNull()) {
549         NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:d->m_user
550                                                                    password:d->m_pass
551                                                                 persistence:NSURLCredentialPersistenceForSession];
552         d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
553         d->m_currentWebChallenge = challenge;
554         receivedCredential(challenge, Credential(credential));
555         [credential release];
556         // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly.
557         d->m_user = String();
558         d->m_pass = String();
559         return;
560     }
561
562     // FIXME: Do not use the sync version of shouldUseCredentialStorage when the client returns true from usesAsyncCallbacks.
563     if (!client() || client()->shouldUseCredentialStorage(this)) {
564         if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
565             // The stored credential wasn't accepted, stop using it.
566             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
567             // but the observable effect should be very minor, if any.
568             CredentialStorage::remove(challenge.protectionSpace());
569         }
570
571         if (!challenge.previousFailureCount()) {
572             Credential credential = CredentialStorage::get(challenge.protectionSpace());
573             if (!credential.isEmpty() && credential != d->m_initialCredential) {
574                 ASSERT(credential.persistence() == CredentialPersistenceNone);
575                 if (challenge.failureResponse().httpStatusCode() == 401) {
576                     // Store the credential back, possibly adding it as a default for this directory.
577                     CredentialStorage::set(credential, challenge.protectionSpace(), challenge.failureResponse().url());
578                 }
579                 [challenge.sender() useCredential:credential.nsCredential() forAuthenticationChallenge:mac(challenge)];
580                 return;
581             }
582         }
583     }
584
585 #if PLATFORM(IOS)
586     // If the challenge is for a proxy protection space, look for default credentials in
587     // the keychain.  CFNetwork used to handle this until WebCore was changed to always
588     // return NO to -connectionShouldUseCredentialStorage: for <rdar://problem/7704943>.
589     if (!challenge.previousFailureCount() && challenge.protectionSpace().isProxy()) {
590         NSURLAuthenticationChallenge *macChallenge = mac(challenge);
591         if (NSURLCredential *credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:[macChallenge protectionSpace]]) {
592             [challenge.sender() useCredential:credential forAuthenticationChallenge:macChallenge];
593             return;
594         }
595     }
596 #endif // PLATFORM(IOS)
597
598     d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
599     d->m_currentWebChallenge = core(d->m_currentMacChallenge);
600     d->m_currentWebChallenge.setAuthenticationClient(this);
601
602     // FIXME: Several concurrent requests can return with the an authentication challenge for the same protection space.
603     // We should avoid making additional client calls for the same protection space when already waiting for the user,
604     // because typing the same credentials several times is annoying.
605     if (client())
606         client()->didReceiveAuthenticationChallenge(this, d->m_currentWebChallenge);
607 }
608
609 void ResourceHandle::didCancelAuthenticationChallenge(const AuthenticationChallenge& challenge)
610 {
611     ASSERT(d->m_currentMacChallenge);
612     ASSERT(d->m_currentMacChallenge == challenge.nsURLAuthenticationChallenge());
613     ASSERT(!d->m_currentWebChallenge.isNull());
614
615     if (client())
616         client()->didCancelAuthenticationChallenge(this, challenge);
617 }
618
619 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
620 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
621 {
622     if (client()->usesAsyncCallbacks()) {
623         if (client())
624             client()->canAuthenticateAgainstProtectionSpaceAsync(this, protectionSpace);
625         else
626             continueCanAuthenticateAgainstProtectionSpace(false);
627         return false; // Ignored by caller.
628     } else
629         return client() && client()->canAuthenticateAgainstProtectionSpace(this, protectionSpace);
630 }
631
632 void ResourceHandle::continueCanAuthenticateAgainstProtectionSpace(bool result)
633 {
634     ASSERT(client());
635     ASSERT(client()->usesAsyncCallbacks());
636
637     [(id)delegate() continueCanAuthenticateAgainstProtectionSpace:result];
638 }
639 #endif
640
641 void ResourceHandle::receivedCredential(const AuthenticationChallenge& challenge, const Credential& credential)
642 {
643     LOG(Network, "Handle %p receivedCredential", this);
644
645     ASSERT(!challenge.isNull());
646     if (challenge != d->m_currentWebChallenge)
647         return;
648
649     // FIXME: Support empty credentials. Currently, an empty credential cannot be stored in WebCore credential storage, as that's empty value for its map.
650     if (credential.isEmpty()) {
651         receivedRequestToContinueWithoutCredential(challenge);
652         return;
653     }
654
655     if (credential.persistence() == CredentialPersistenceForSession && challenge.protectionSpace().authenticationScheme() != ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
656         // Manage per-session credentials internally, because once NSURLCredentialPersistenceForSession is used, there is no way
657         // to ignore it for a particular request (short of removing it altogether).
658         Credential webCredential(credential, CredentialPersistenceNone);
659         URL urlToStore;
660         if (challenge.failureResponse().httpStatusCode() == 401)
661             urlToStore = challenge.failureResponse().url();
662         CredentialStorage::set(webCredential, ProtectionSpace([d->m_currentMacChallenge protectionSpace]), urlToStore);
663         [[d->m_currentMacChallenge sender] useCredential:webCredential.nsCredential() forAuthenticationChallenge:d->m_currentMacChallenge];
664     } else
665         [[d->m_currentMacChallenge sender] useCredential:credential.nsCredential() forAuthenticationChallenge:d->m_currentMacChallenge];
666
667     clearAuthentication();
668 }
669
670 void ResourceHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& challenge)
671 {
672     LOG(Network, "Handle %p receivedRequestToContinueWithoutCredential", this);
673
674     ASSERT(!challenge.isNull());
675     if (challenge != d->m_currentWebChallenge)
676         return;
677
678     [[d->m_currentMacChallenge sender] continueWithoutCredentialForAuthenticationChallenge:d->m_currentMacChallenge];
679
680     clearAuthentication();
681 }
682
683 void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challenge)
684 {
685     LOG(Network, "Handle %p receivedCancellation", this);
686
687     if (challenge != d->m_currentWebChallenge)
688         return;
689
690     if (client())
691         client()->receivedCancellation(this, challenge);
692 }
693
694 void ResourceHandle::receivedRequestToPerformDefaultHandling(const AuthenticationChallenge& challenge)
695 {
696     LOG(Network, "Handle %p receivedRequestToPerformDefaultHandling", this);
697
698     ASSERT(!challenge.isNull());
699     if (challenge != d->m_currentWebChallenge)
700         return;
701
702     [[d->m_currentMacChallenge sender] performDefaultHandlingForAuthenticationChallenge:d->m_currentMacChallenge];
703
704     clearAuthentication();
705 }
706
707 void ResourceHandle::receivedChallengeRejection(const AuthenticationChallenge& challenge)
708 {
709     LOG(Network, "Handle %p receivedChallengeRejection", this);
710
711     ASSERT(!challenge.isNull());
712     if (challenge != d->m_currentWebChallenge)
713         return;
714
715     [[d->m_currentMacChallenge sender] rejectProtectionSpaceAndContinueWithChallenge:d->m_currentMacChallenge];
716
717     clearAuthentication();
718 }
719
720 void ResourceHandle::continueWillCacheResponse(NSCachedURLResponse *response)
721 {
722     ASSERT(client());
723     ASSERT(client()->usesAsyncCallbacks());
724
725     [(id)delegate() continueWillCacheResponse:response];
726 }
727     
728 #endif // !USE(CFNETWORK)
729     
730 #if ENABLE(WEB_TIMING)
731     
732 void ResourceHandle::getConnectionTimingData(NSDictionary *timingData, ResourceLoadTiming& timing)
733 {
734     if (!timingData)
735         return;
736
737     // This is not the navigationStart time in monotonic time, but the other times are relative to this time
738     // and only the differences between times are stored.
739     double referenceStart = [[timingData valueForKey:@"_kCFNTimingDataFetchStart"] doubleValue];
740             
741     double domainLookupStart = [[timingData valueForKey:@"_kCFNTimingDataDomainLookupStart"] doubleValue];
742     double domainLookupEnd = [[timingData valueForKey:@"_kCFNTimingDataDomainLookupEnd"] doubleValue];
743     double connectStart = [[timingData valueForKey:@"_kCFNTimingDataConnectStart"] doubleValue];
744     double secureConnectionStart = [[timingData valueForKey:@"_kCFNTimingDataSecureConnectionStart"] doubleValue];
745     double connectEnd = [[timingData valueForKey:@"_kCFNTimingDataConnectEnd"] doubleValue];
746     double requestStart = [[timingData valueForKey:@"_kCFNTimingDataRequestStart"] doubleValue];
747     double responseStart = [[timingData valueForKey:@"_kCFNTimingDataResponseStart"] doubleValue];
748         
749     timing.domainLookupStart = domainLookupStart <= 0 ? -1 : (domainLookupStart - referenceStart) * 1000;
750     timing.domainLookupEnd = domainLookupEnd <= 0 ? -1 : (domainLookupEnd - referenceStart) * 1000;
751     timing.connectStart = connectStart <= 0 ? -1 : (connectStart - referenceStart) * 1000;
752     timing.secureConnectionStart = secureConnectionStart <= 0 ? -1 : (secureConnectionStart - referenceStart) * 1000;
753     timing.connectEnd = connectEnd <= 0 ? -1 : (connectEnd - referenceStart) * 1000;
754     timing.requestStart = requestStart <= 0 ? 0 : (requestStart - referenceStart) * 1000;
755     timing.responseStart = responseStart <= 0 ? 0 : (responseStart - referenceStart) * 1000;
756 }
757
758 void ResourceHandle::setCollectsTimingData()
759 {
760     static dispatch_once_t onceToken;
761     dispatch_once(&onceToken, ^{
762         [NSURLConnection _setCollectsTimingData:YES];
763     });
764 }
765
766 #if USE(CFNETWORK)
767     
768 void ResourceHandle::getConnectionTimingData(CFURLConnectionRef connection, ResourceLoadTiming& timing)
769 {
770     getConnectionTimingData((__bridge NSDictionary*)(adoptCF(_CFURLConnectionCopyTimingData(connection)).get()), timing);
771 }
772     
773 #else
774     
775 void ResourceHandle::getConnectionTimingData(NSURLConnection *connection, ResourceLoadTiming& timing)
776 {
777     getConnectionTimingData([connection _timingData], timing);
778 }
779     
780 #endif
781     
782 #endif // ENABLE(WEB_TIMING)
783
784 } // namespace WebCore
785