WebKit2: Use CFNetwork Sessions API.
[WebKit-https.git] / Source / WebCore / platform / network / mac / ResourceHandleMac.mm
1 /*
2  * Copyright (C) 2004, 2006, 2007, 2008, 2009, 2010 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 COMPUTER, 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 COMPUTER, 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 #if !USE(CFNETWORK)
30
31 #import "AuthenticationChallenge.h"
32 #import "AuthenticationMac.h"
33 #import "Base64.h"
34 #import "BlobRegistry.h"
35 #import "BlockExceptions.h"
36 #import "CredentialStorage.h"
37 #import "CachedResourceLoader.h"
38 #import "EmptyProtocolDefinitions.h"
39 #import "FormDataStreamMac.h"
40 #import "Frame.h"
41 #import "FrameLoader.h"
42 #import "Logging.h"
43 #import "MIMETypeRegistry.h"
44 #import "Page.h"
45 #import "ResourceError.h"
46 #import "ResourceResponse.h"
47 #import "SchedulePair.h"
48 #import "Settings.h"
49 #import "SharedBuffer.h"
50 #import "SubresourceLoader.h"
51 #import "WebCoreSystemInterface.h"
52 #import "WebCoreURLResponse.h"
53 #import <wtf/text/CString.h>
54 #import <wtf/UnusedParam.h>
55
56 #ifdef BUILDING_ON_TIGER
57 typedef int NSInteger;
58 #endif
59
60 using namespace WebCore;
61
62 @interface WebCoreResourceHandleAsDelegate : NSObject <NSURLConnectionDelegate> {
63     ResourceHandle* m_handle;
64 }
65 - (id)initWithHandle:(ResourceHandle*)handle;
66 - (void)detachHandle;
67 @end
68
69 // WebCoreNSURLConnectionDelegateProxy exists so that we can cast m_proxy to it in order
70 // to disambiguate the argument type in the -setDelegate: call.  This avoids a spurious
71 // warning that the compiler would otherwise emit.
72 @interface WebCoreNSURLConnectionDelegateProxy : NSObject <NSURLConnectionDelegate>
73 - (void)setDelegate:(id<NSURLConnectionDelegate>)delegate;
74 @end
75
76 @interface NSURLConnection (NSURLConnectionTigerPrivate)
77 - (NSData *)_bufferedData;
78 @end
79
80 @interface NSURLConnection (Details)
81 -(id)_initWithRequest:(NSURLRequest *)request delegate:(id)delegate usesCache:(BOOL)usesCacheFlag maxContentLength:(long long)maxContentLength startImmediately:(BOOL)startImmediately connectionProperties:(NSDictionary *)connectionProperties;
82 @end
83
84 @interface NSURLRequest (Details)
85 - (id)_propertyForKey:(NSString *)key;
86 @end
87
88 #ifndef BUILDING_ON_TIGER
89
90 class WebCoreSynchronousLoaderClient : public ResourceHandleClient {
91 public:
92     static PassOwnPtr<WebCoreSynchronousLoaderClient> create()
93     {
94         return adoptPtr(new WebCoreSynchronousLoaderClient);
95     }
96
97     virtual ~WebCoreSynchronousLoaderClient();
98
99     void setAllowStoredCredentials(bool allow) { m_allowStoredCredentials = allow; }
100     NSURLResponse *response() { return m_response; }
101     NSMutableData *data() { return m_data; }
102     NSError *error() { return m_error; }
103     bool isDone() { return m_isDone; }
104
105 private:
106     WebCoreSynchronousLoaderClient()
107         : m_allowStoredCredentials(false)
108         , m_response(0)
109         , m_data(0)
110         , m_error(0)
111         , m_isDone(false)
112     {
113     }
114
115     virtual void willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse& /*redirectResponse*/);
116     virtual bool shouldUseCredentialStorage(ResourceHandle*);
117     virtual void didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge&);
118     virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
119     virtual void didReceiveData(ResourceHandle*, const char*, int, int /*lengthReceived*/);
120     virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
121     virtual void didFail(ResourceHandle*, const ResourceError&);
122 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
123     virtual bool canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&);
124 #endif
125
126     bool m_allowStoredCredentials;
127     NSURLResponse *m_response;
128     NSMutableData *m_data;
129     NSError *m_error;
130     bool m_isDone;
131 };
132
133 static NSString *WebCoreSynchronousLoaderRunLoopMode = @"WebCoreSynchronousLoaderRunLoopMode";
134
135 #endif
136
137 namespace WebCore {
138
139 #ifdef BUILDING_ON_TIGER
140 static unsigned inNSURLConnectionCallback;
141 #endif
142
143 #ifndef NDEBUG
144 static bool isInitializingConnection;
145 #endif
146     
147 class CallbackGuard {
148 public:
149     CallbackGuard()
150     {
151 #ifdef BUILDING_ON_TIGER
152         ++inNSURLConnectionCallback;
153 #endif
154     }
155     ~CallbackGuard()
156     {
157 #ifdef BUILDING_ON_TIGER
158         ASSERT(inNSURLConnectionCallback > 0);
159         --inNSURLConnectionCallback;
160 #endif
161     }
162 };
163
164 #ifndef BUILDING_ON_TIGER
165 static String encodeBasicAuthorization(const String& user, const String& password)
166 {
167     return base64Encode((user + ":" + password).utf8());
168 }
169 #endif
170
171 ResourceHandleInternal::~ResourceHandleInternal()
172 {
173 }
174
175 ResourceHandle::~ResourceHandle()
176 {
177     releaseDelegate();
178     d->m_currentWebChallenge.setAuthenticationClient(0);
179
180     LOG(Network, "Handle %p destroyed", this);
181 }
182
183 static const double MaxFoundationVersionWithoutdidSendBodyDataDelegate = 677.21;
184 bool ResourceHandle::didSendBodyDataDelegateExists()
185 {
186     return NSFoundationVersionNumber > MaxFoundationVersionWithoutdidSendBodyDataDelegate;
187 }
188
189 void ResourceHandle::createNSURLConnection(id delegate, bool shouldUseCredentialStorage, bool shouldContentSniff)
190 {
191     // Credentials for ftp can only be passed in URL, the connection:didReceiveAuthenticationChallenge: delegate call won't be made.
192     if ((!d->m_user.isEmpty() || !d->m_pass.isEmpty())
193 #ifndef BUILDING_ON_TIGER
194      && !firstRequest().url().protocolInHTTPFamily() // On Tiger, always pass credentials in URL, so that they get stored even if the request gets cancelled right away.
195 #endif
196     ) {
197         KURL urlWithCredentials(firstRequest().url());
198         urlWithCredentials.setUser(d->m_user);
199         urlWithCredentials.setPass(d->m_pass);
200         firstRequest().setURL(urlWithCredentials);
201     }
202
203     // If a URL already has cookies, then we'll relax the 3rd party cookie policy and accept new cookies.
204     NSHTTPCookieStorage *sharedStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
205     if ([sharedStorage cookieAcceptPolicy] == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain && [[sharedStorage cookiesForURL:firstRequest().url()] count])
206         firstRequest().setFirstPartyForCookies(firstRequest().url());
207
208 #if !defined(BUILDING_ON_TIGER)
209     if (shouldUseCredentialStorage && firstRequest().url().protocolInHTTPFamily()) {
210         if (d->m_user.isEmpty() && d->m_pass.isEmpty()) {
211             // <rdar://problem/7174050> - For URLs that match the paths of those previously challenged for HTTP Basic authentication, 
212             // try and reuse the credential preemptively, as allowed by RFC 2617.
213             d->m_initialCredential = CredentialStorage::get(firstRequest().url());
214         } else {
215             // If there is already a protection space known for the URL, update stored credentials before sending a request.
216             // This makes it possible to implement logout by sending an XMLHttpRequest with known incorrect credentials, and aborting it immediately
217             // (so that an authentication dialog doesn't pop up).
218             CredentialStorage::set(Credential(d->m_user, d->m_pass, CredentialPersistenceNone), firstRequest().url());
219         }
220     }
221         
222     if (!d->m_initialCredential.isEmpty()) {
223         // FIXME: Support Digest authentication, and Proxy-Authorization.
224         String authHeader = "Basic " + encodeBasicAuthorization(d->m_initialCredential.user(), d->m_initialCredential.password());
225         firstRequest().addHTTPHeaderField("Authorization", authHeader);
226     }
227
228     NSURLRequest *nsRequest = firstRequest().nsURLRequest();
229     if (!shouldContentSniff) {
230         NSMutableURLRequest *mutableRequest = [[nsRequest copy] autorelease];
231         wkSetNSURLRequestShouldContentSniff(mutableRequest, NO);
232         nsRequest = mutableRequest;
233     }
234
235 #if !defined(BUILDING_ON_LEOPARD)
236     ASSERT([NSURLConnection instancesRespondToSelector:@selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)]);
237     static bool supportsSettingConnectionProperties = true;
238 #else
239     static bool supportsSettingConnectionProperties = [NSURLConnection instancesRespondToSelector:@selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)];
240 #endif
241
242 #if USE(CFURLSTORAGESESSIONS)
243     if (CFURLStorageSessionRef storageSession = privateBrowsingStorageSession())
244         nsRequest = [wkCopyRequestWithStorageSession(storageSession, nsRequest) autorelease];
245 #endif
246
247     if (supportsSettingConnectionProperties) {
248         NSDictionary *sessionID = shouldUseCredentialStorage ? [NSDictionary dictionary] : [NSDictionary dictionaryWithObject:@"WebKitPrivateSession" forKey:@"_kCFURLConnectionSessionID"];
249         NSDictionary *propertyDictionary = [NSDictionary dictionaryWithObject:sessionID forKey:@"kCFURLConnectionSocketStreamProperties"];
250         d->m_connection.adoptNS([[NSURLConnection alloc] _initWithRequest:nsRequest delegate:delegate usesCache:YES maxContentLength:0 startImmediately:NO connectionProperties:propertyDictionary]);
251         return;
252     }
253
254     d->m_connection.adoptNS([[NSURLConnection alloc] initWithRequest:nsRequest delegate:delegate startImmediately:NO]);
255     return;
256
257 #else
258     // Building on Tiger. Don't use WebCore credential storage, don't try to disable content sniffing.
259     UNUSED_PARAM(shouldUseCredentialStorage);
260     UNUSED_PARAM(shouldContentSniff);
261     d->m_connection.adoptNS([[NSURLConnection alloc] initWithRequest:firstRequest().nsURLRequest() delegate:delegate]);
262 #endif
263 }
264
265 bool ResourceHandle::start(NetworkingContext* context)
266 {
267     if (!context)
268         return false;
269
270     BEGIN_BLOCK_OBJC_EXCEPTIONS;
271
272     // If NetworkingContext is invalid then we are no longer attached to a Page,
273     // this must be an attempted load from an unload event handler, so let's just block it.
274     if (!context->isValid())
275         return false;
276
277 #ifndef NDEBUG
278     isInitializingConnection = YES;
279 #endif
280
281     ASSERT(!d->m_proxy);
282     d->m_proxy.adoptNS(wkCreateNSURLConnectionDelegateProxy());
283     [static_cast<WebCoreNSURLConnectionDelegateProxy*>(d->m_proxy.get()) setDelegate:ResourceHandle::delegate()];
284
285     bool shouldUseCredentialStorage = !client() || client()->shouldUseCredentialStorage(this);
286
287     if (!ResourceHandle::didSendBodyDataDelegateExists())
288         associateStreamWithResourceHandle([firstRequest().nsURLRequest() HTTPBodyStream], this);
289
290 #ifdef BUILDING_ON_TIGER
291     // A conditional request sent by WebCore (e.g. to update appcache) can be for a resource that is not cacheable by NSURLConnection,
292     // which can get confused and fail to load it in this case.
293     if (firstRequest().isConditional())
294         firstRequest().setCachePolicy(ReloadIgnoringCacheData);
295 #endif
296
297     d->m_needsSiteSpecificQuirks = context->needsSiteSpecificQuirks();
298
299     createNSURLConnection(
300         d->m_proxy.get(),
301         shouldUseCredentialStorage,
302         d->m_shouldContentSniff || context->localFileContentSniffingEnabled());
303
304 #ifndef BUILDING_ON_TIGER
305     bool scheduled = false;
306     if (SchedulePairHashSet* scheduledPairs = context->scheduledRunLoopPairs()) {
307         SchedulePairHashSet::iterator end = scheduledPairs->end();
308         for (SchedulePairHashSet::iterator it = scheduledPairs->begin(); it != end; ++it) {
309             if (NSRunLoop *runLoop = (*it)->nsRunLoop()) {
310                 [connection() scheduleInRunLoop:runLoop forMode:(NSString *)(*it)->mode()];
311                 scheduled = true;
312             }
313         }
314     }
315
316     // Start the connection if we did schedule with at least one runloop.
317     // We can't start the connection until we have one runloop scheduled.
318     if (scheduled)
319         [connection() start];
320     else
321         d->m_startWhenScheduled = true;
322 #endif
323
324 #ifndef NDEBUG
325     isInitializingConnection = NO;
326 #endif
327
328     LOG(Network, "Handle %p starting connection %p for %@", this, connection(), firstRequest().nsURLRequest());
329     
330     if (d->m_connection) {
331         if (d->m_defersLoading)
332             wkSetNSURLConnectionDefersCallbacks(connection(), YES);
333
334         return true;
335     }
336
337     END_BLOCK_OBJC_EXCEPTIONS;
338
339     return false;
340 }
341
342 void ResourceHandle::cancel()
343 {
344     LOG(Network, "Handle %p cancel connection %p", this, d->m_connection.get());
345
346     // Leaks were seen on HTTP tests without this; can be removed once <rdar://problem/6886937> is fixed.
347     if (d->m_currentMacChallenge)
348         [[d->m_currentMacChallenge sender] cancelAuthenticationChallenge:d->m_currentMacChallenge];
349
350     if (!ResourceHandle::didSendBodyDataDelegateExists())
351         disassociateStreamWithResourceHandle([firstRequest().nsURLRequest() HTTPBodyStream]);
352     [d->m_connection.get() cancel];
353 }
354
355 void ResourceHandle::platformSetDefersLoading(bool defers)
356 {
357     if (d->m_connection)
358         wkSetNSURLConnectionDefersCallbacks(d->m_connection.get(), defers);
359 }
360
361 void ResourceHandle::schedule(SchedulePair* pair)
362 {
363 #ifndef BUILDING_ON_TIGER
364     NSRunLoop *runLoop = pair->nsRunLoop();
365     if (!runLoop)
366         return;
367     [d->m_connection.get() scheduleInRunLoop:runLoop forMode:(NSString *)pair->mode()];
368     if (d->m_startWhenScheduled) {
369         [d->m_connection.get() start];
370         d->m_startWhenScheduled = false;
371     }
372 #else
373     UNUSED_PARAM(pair);
374 #endif
375 }
376
377 void ResourceHandle::unschedule(SchedulePair* pair)
378 {
379 #ifndef BUILDING_ON_TIGER
380     if (NSRunLoop *runLoop = pair->nsRunLoop())
381         [d->m_connection.get() unscheduleFromRunLoop:runLoop forMode:(NSString *)pair->mode()];
382 #else
383     UNUSED_PARAM(pair);
384 #endif
385 }
386
387 WebCoreResourceHandleAsDelegate *ResourceHandle::delegate()
388 {
389     if (!d->m_delegate) {
390         WebCoreResourceHandleAsDelegate *delegate = [[WebCoreResourceHandleAsDelegate alloc] initWithHandle:this];
391         d->m_delegate = delegate;
392         [delegate release];
393     }
394     return d->m_delegate.get();
395 }
396
397 void ResourceHandle::releaseDelegate()
398 {
399     if (!d->m_delegate)
400         return;
401     if (d->m_proxy)
402         [d->m_proxy.get() setDelegate:nil];
403     [d->m_delegate.get() detachHandle];
404     d->m_delegate = nil;
405 }
406
407 bool ResourceHandle::supportsBufferedData()
408 {
409     static bool supportsBufferedData = [NSURLConnection instancesRespondToSelector:@selector(_bufferedData)];
410     return supportsBufferedData;
411 }
412
413 PassRefPtr<SharedBuffer> ResourceHandle::bufferedData()
414 {
415     if (ResourceHandle::supportsBufferedData())
416         return SharedBuffer::wrapNSData([d->m_connection.get() _bufferedData]);
417
418     return 0;
419 }
420
421 id ResourceHandle::releaseProxy()
422 {
423     id proxy = [[d->m_proxy.get() retain] autorelease];
424     d->m_proxy = nil;
425     [proxy setDelegate:nil];
426     return proxy;
427 }
428
429 NSURLConnection *ResourceHandle::connection() const
430 {
431     return d->m_connection.get();
432 }
433
434 bool ResourceHandle::loadsBlocked()
435 {
436 #ifndef BUILDING_ON_TIGER
437     return false;
438 #else
439     // On Tiger, if we're in an NSURLConnection callback, that blocks all other NSURLConnection callbacks.
440     // On Leopard and newer, it blocks only callbacks on that same NSURLConnection object, which is not
441     // a problem in practice.
442     return inNSURLConnectionCallback != 0;
443 #endif
444 }
445
446 bool ResourceHandle::willLoadFromCache(ResourceRequest& request, Frame*)
447 {
448 #ifndef BUILDING_ON_TIGER
449     request.setCachePolicy(ReturnCacheDataDontLoad);
450     NSURLResponse *nsURLResponse = nil;
451     BEGIN_BLOCK_OBJC_EXCEPTIONS;
452     
453    [NSURLConnection sendSynchronousRequest:request.nsURLRequest() returningResponse:&nsURLResponse error:nil];
454     
455     END_BLOCK_OBJC_EXCEPTIONS;
456     
457     return nsURLResponse;
458 #else
459     // <rdar://problem/6803217> - Re-enable after <rdar://problem/6786454> is resolved.
460     UNUSED_PARAM(request);
461     return false;
462 #endif
463 }
464
465 void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
466 {
467     LOG(Network, "ResourceHandle::loadResourceSynchronously:%@ allowStoredCredentials:%u", request.nsURLRequest(), storedCredentials);
468
469 #if ENABLE(BLOB)
470     if (request.url().protocolIs("blob"))
471         if (blobRegistry().loadResourceSynchronously(request, error, response, data))
472             return;
473 #endif
474
475     NSError *nsError = nil;
476     NSURLResponse *nsURLResponse = nil;
477     NSData *result = nil;
478
479     ASSERT(!request.isEmpty());
480     
481 #ifndef BUILDING_ON_TIGER
482     OwnPtr<WebCoreSynchronousLoaderClient> client = WebCoreSynchronousLoaderClient::create();
483     client->setAllowStoredCredentials(storedCredentials == AllowStoredCredentials);
484
485     RefPtr<ResourceHandle> handle = adoptRef(new ResourceHandle(request, client.get(), false /*defersLoading*/, true /*shouldContentSniff*/));
486
487     if (context && handle->d->m_scheduledFailureType != NoFailure) {
488         error = context->blockedError(request);
489         return;
490     }
491
492     handle->createNSURLConnection(
493         handle->delegate(), // A synchronous request cannot turn into a download, so there is no need to proxy the delegate.
494         storedCredentials == AllowStoredCredentials,
495         handle->shouldContentSniff() || (context && context->localFileContentSniffingEnabled()));
496
497     [handle->connection() scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:WebCoreSynchronousLoaderRunLoopMode];
498     [handle->connection() start];
499     
500     while (!client->isDone())
501         [[NSRunLoop currentRunLoop] runMode:WebCoreSynchronousLoaderRunLoopMode beforeDate:[NSDate distantFuture]];
502
503     result = client->data();
504     nsURLResponse = client->response();
505     nsError = client->error();
506     
507     [handle->connection() cancel];
508
509 #else
510     UNUSED_PARAM(storedCredentials);
511     UNUSED_PARAM(context);
512     NSURLRequest *firstRequest = request.nsURLRequest();
513
514     // If a URL already has cookies, then we'll relax the 3rd party cookie policy and accept new cookies.
515     NSHTTPCookieStorage *sharedStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
516     if ([sharedStorage cookieAcceptPolicy] == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain && [[sharedStorage cookiesForURL:[firstRequest URL]] count]) {
517         NSMutableURLRequest *mutableRequest = [[firstRequest mutableCopy] autorelease];
518         [mutableRequest setMainDocumentURL:[mutableRequest URL]];
519         firstRequest = mutableRequest;
520     }
521
522     BEGIN_BLOCK_OBJC_EXCEPTIONS;
523     result = [NSURLConnection sendSynchronousRequest:firstRequest returningResponse:&nsURLResponse error:&nsError];
524     END_BLOCK_OBJC_EXCEPTIONS;
525 #endif
526
527     if (!nsError)
528         response = nsURLResponse;
529     else {
530         response = ResourceResponse(request.url(), String(), 0, String(), String());
531         if ([nsError domain] == NSURLErrorDomain)
532             switch ([nsError code]) {
533                 case NSURLErrorUserCancelledAuthentication:
534                     // FIXME: we should really return the actual HTTP response, but sendSynchronousRequest doesn't provide us with one.
535                     response.setHTTPStatusCode(401);
536                     break;
537                 default:
538                     response.setHTTPStatusCode([nsError code]);
539             }
540         else
541             response.setHTTPStatusCode(404);
542     }
543     
544     data.resize([result length]);
545     memcpy(data.data(), [result bytes], [result length]);
546     
547     error = nsError;
548 }
549
550 void ResourceHandle::willSendRequest(ResourceRequest& request, const ResourceResponse& redirectResponse)
551 {
552     const KURL& url = request.url();
553     d->m_user = url.user();
554     d->m_pass = url.pass();
555     d->m_lastHTTPMethod = request.httpMethod();
556     request.removeCredentials();
557     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url()))
558         request.clearHTTPAuthorization();
559
560 #if USE(CFURLSTORAGESESSIONS)
561     if (CFURLStorageSessionRef storageSession = privateBrowsingStorageSession())
562         request.setStorageSession(storageSession);
563 #endif
564
565     client()->willSendRequest(this, request, redirectResponse);
566 }
567
568 bool ResourceHandle::shouldUseCredentialStorage()
569 {
570     if (client())
571         return client()->shouldUseCredentialStorage(this);
572
573     return false;
574 }
575
576 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
577 {
578     ASSERT(!d->m_currentMacChallenge);
579     ASSERT(d->m_currentWebChallenge.isNull());
580     // Since NSURLConnection networking relies on keeping a reference to the original NSURLAuthenticationChallenge,
581     // we make sure that is actually present
582     ASSERT(challenge.nsURLAuthenticationChallenge());
583
584     if (!d->m_user.isNull() && !d->m_pass.isNull()) {
585         NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:d->m_user
586                                                                    password:d->m_pass
587                                                                 persistence:NSURLCredentialPersistenceForSession];
588         d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
589         d->m_currentWebChallenge = challenge;
590         receivedCredential(challenge, core(credential));
591         [credential release];
592         // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly.
593         d->m_user = String();
594         d->m_pass = String();
595         return;
596     }
597
598 #ifndef BUILDING_ON_TIGER
599     if (!client() || client()->shouldUseCredentialStorage(this)) {
600         if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
601             // The stored credential wasn't accepted, stop using it.
602             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
603             // but the observable effect should be very minor, if any.
604             CredentialStorage::remove(challenge.protectionSpace());
605         }
606
607         if (!challenge.previousFailureCount()) {
608             Credential credential = CredentialStorage::get(challenge.protectionSpace());
609             if (!credential.isEmpty() && credential != d->m_initialCredential) {
610                 ASSERT(credential.persistence() == CredentialPersistenceNone);
611                 if (challenge.failureResponse().httpStatusCode() == 401) {
612                     // Store the credential back, possibly adding it as a default for this directory.
613                     CredentialStorage::set(credential, challenge.protectionSpace(), firstRequest().url());
614                 }
615                 [challenge.sender() useCredential:mac(credential) forAuthenticationChallenge:mac(challenge)];
616                 return;
617             }
618         }
619     }
620 #endif
621
622     d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
623     d->m_currentWebChallenge = core(d->m_currentMacChallenge);
624     d->m_currentWebChallenge.setAuthenticationClient(this);
625
626     if (client())
627         client()->didReceiveAuthenticationChallenge(this, d->m_currentWebChallenge);
628 }
629
630 void ResourceHandle::didCancelAuthenticationChallenge(const AuthenticationChallenge& challenge)
631 {
632     ASSERT(d->m_currentMacChallenge);
633     ASSERT(d->m_currentMacChallenge == challenge.nsURLAuthenticationChallenge());
634     ASSERT(!d->m_currentWebChallenge.isNull());
635
636     if (client())
637         client()->didCancelAuthenticationChallenge(this, challenge);
638 }
639
640 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
641 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
642 {
643     if (client())
644         return client()->canAuthenticateAgainstProtectionSpace(this, protectionSpace);
645         
646     return false;
647 }
648 #endif
649
650 void ResourceHandle::receivedCredential(const AuthenticationChallenge& challenge, const Credential& credential)
651 {
652     ASSERT(!challenge.isNull());
653     if (challenge != d->m_currentWebChallenge)
654         return;
655
656     // FIXME: Support empty credentials. Currently, an empty credential cannot be stored in WebCore credential storage, as that's empty value for its map.
657     if (credential.isEmpty()) {
658         receivedRequestToContinueWithoutCredential(challenge);
659         return;
660     }
661
662 #ifdef BUILDING_ON_TIGER
663     if (credential.persistence() == CredentialPersistenceNone) {
664         // NSURLCredentialPersistenceNone doesn't work on Tiger, so we have to use session persistence.
665         Credential webCredential(credential.user(), credential.password(), CredentialPersistenceForSession);
666         [[d->m_currentMacChallenge sender] useCredential:mac(webCredential) forAuthenticationChallenge:d->m_currentMacChallenge];
667     } else
668 #else
669     if (credential.persistence() == CredentialPersistenceForSession && (!d->m_needsSiteSpecificQuirks || ![[[mac(challenge) protectionSpace] host] isEqualToString:@"gallery.me.com"])) {
670         // Manage per-session credentials internally, because once NSURLCredentialPersistenceForSession is used, there is no way
671         // to ignore it for a particular request (short of removing it altogether).
672         // <rdar://problem/6867598> gallery.me.com is temporarily whitelisted, so that QuickTime plug-in could see the credentials.
673         Credential webCredential(credential, CredentialPersistenceNone);
674         KURL urlToStore;
675         if (challenge.failureResponse().httpStatusCode() == 401)
676             urlToStore = firstRequest().url();
677         CredentialStorage::set(webCredential, core([d->m_currentMacChallenge protectionSpace]), urlToStore);
678         [[d->m_currentMacChallenge sender] useCredential:mac(webCredential) forAuthenticationChallenge:d->m_currentMacChallenge];
679     } else
680 #endif
681         [[d->m_currentMacChallenge sender] useCredential:mac(credential) forAuthenticationChallenge:d->m_currentMacChallenge];
682
683     clearAuthentication();
684 }
685
686 void ResourceHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& challenge)
687 {
688     ASSERT(!challenge.isNull());
689     if (challenge != d->m_currentWebChallenge)
690         return;
691
692     [[d->m_currentMacChallenge sender] continueWithoutCredentialForAuthenticationChallenge:d->m_currentMacChallenge];
693
694     clearAuthentication();
695 }
696
697 void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challenge)
698 {
699     if (challenge != d->m_currentWebChallenge)
700         return;
701
702     if (client())
703         client()->receivedCancellation(this, challenge);
704 }
705
706 #if USE(CFURLSTORAGESESSIONS)
707
708 RetainPtr<CFURLStorageSessionRef> ResourceHandle::createPrivateBrowsingStorageSession(CFStringRef identifier)
709 {
710     return RetainPtr<CFURLStorageSessionRef>(AdoptCF, wkCreatePrivateStorageSession(identifier));
711 }
712
713 String ResourceHandle::privateBrowsingStorageSessionIdentifierDefaultBase()
714 {
715     return String([[NSBundle mainBundle] bundleIdentifier]);
716 }
717
718 #endif
719
720 } // namespace WebCore
721
722 @implementation WebCoreResourceHandleAsDelegate
723
724 - (id)initWithHandle:(ResourceHandle*)handle
725 {
726     self = [self init];
727     if (!self)
728         return nil;
729     m_handle = handle;
730     return self;
731 }
732
733 - (void)detachHandle
734 {
735     m_handle = 0;
736 }
737
738 - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)newRequest redirectResponse:(NSURLResponse *)redirectResponse
739 {
740     UNUSED_PARAM(connection);
741
742     // the willSendRequest call may cancel this load, in which case self could be deallocated
743     RetainPtr<WebCoreResourceHandleAsDelegate> protect(self);
744
745     if (!m_handle || !m_handle->client())
746         return nil;
747     
748     // See <rdar://problem/5380697> .  This is a workaround for a behavior change in CFNetwork where willSendRequest gets called more often.
749     if (!redirectResponse)
750         return newRequest;
751
752 #if !LOG_DISABLED
753     if ([redirectResponse isKindOfClass:[NSHTTPURLResponse class]])
754         LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:%d, Location:<%@>", m_handle, connection, [newRequest description], static_cast<int>([(id)redirectResponse statusCode]), [[(id)redirectResponse allHeaderFields] objectForKey:@"Location"]);
755     else
756         LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:non-HTTP", m_handle, connection, [newRequest description]); 
757 #endif
758
759     if ([redirectResponse isKindOfClass:[NSHTTPURLResponse class]] && [(NSHTTPURLResponse *)redirectResponse statusCode] == 307) {
760         String lastHTTPMethod = m_handle->lastHTTPMethod();
761         if (!equalIgnoringCase(lastHTTPMethod, String([newRequest HTTPMethod]))) {
762             NSMutableURLRequest *mutableRequest = [newRequest mutableCopy];
763             [mutableRequest setHTTPMethod:lastHTTPMethod];
764     
765             FormData* body = m_handle->firstRequest().httpBody();
766             if (!equalIgnoringCase(lastHTTPMethod, "GET") && body && !body->isEmpty())
767                 WebCore::setHTTPBody(mutableRequest, body);
768
769             String originalContentType = m_handle->firstRequest().httpContentType();
770             if (!originalContentType.isEmpty())
771                 [mutableRequest setValue:originalContentType forHTTPHeaderField:@"Content-Type"];
772
773             newRequest = [mutableRequest autorelease];
774         }
775     }
776
777     CallbackGuard guard;
778     ResourceRequest request = newRequest;
779
780     // Should not set Referer after a redirect from a secure resource to non-secure one.
781     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https"))
782         request.clearHTTPReferrer();
783
784     m_handle->willSendRequest(request, redirectResponse);
785
786     if (!ResourceHandle::didSendBodyDataDelegateExists()) {
787         // The client may change the request's body stream, in which case we have to re-associate
788         // the handle with the new stream so upload progress callbacks continue to work correctly.
789         NSInputStream* oldBodyStream = [newRequest HTTPBodyStream];
790         NSInputStream* newBodyStream = [request.nsURLRequest() HTTPBodyStream];
791         if (oldBodyStream != newBodyStream) {
792             disassociateStreamWithResourceHandle(oldBodyStream);
793             associateStreamWithResourceHandle(newBodyStream, m_handle);
794         }
795     }
796
797     return request.nsURLRequest();
798 }
799
800 - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
801 {
802     UNUSED_PARAM(connection);
803
804     LOG(Network, "Handle %p delegate connectionShouldUseCredentialStorage:%p", m_handle, connection);
805
806     if (!m_handle)
807         return NO;
808
809     CallbackGuard guard;
810     return m_handle->shouldUseCredentialStorage();
811 }
812
813 - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
814 {
815     UNUSED_PARAM(connection);
816
817     LOG(Network, "Handle %p delegate connection:%p didReceiveAuthenticationChallenge:%p", m_handle, connection, challenge);
818
819     if (!m_handle)
820         return;
821     CallbackGuard guard;
822     m_handle->didReceiveAuthenticationChallenge(core(challenge));
823 }
824
825 - (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
826 {
827     UNUSED_PARAM(connection);
828
829     LOG(Network, "Handle %p delegate connection:%p didCancelAuthenticationChallenge:%p", m_handle, connection, challenge);
830
831     if (!m_handle)
832         return;
833     CallbackGuard guard;
834     m_handle->didCancelAuthenticationChallenge(core(challenge));
835 }
836
837 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
838 - (BOOL)connection:(NSURLConnection *)unusedConnection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
839 {
840     UNUSED_PARAM(unusedConnection);
841     
842     if (!m_handle)
843         return NO;
844         
845     CallbackGuard guard;
846     return m_handle->canAuthenticateAgainstProtectionSpace(core(protectionSpace));
847 }
848 #endif
849
850 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)r
851 {
852     UNUSED_PARAM(connection);
853
854     LOG(Network, "Handle %p delegate connection:%p didReceiveResponse:%p (HTTP status %d, reported MIMEType '%s')", m_handle, connection, r, [r respondsToSelector:@selector(statusCode)] ? [(id)r statusCode] : 0, [[r MIMEType] UTF8String]);
855
856     if (!m_handle || !m_handle->client())
857         return;
858     CallbackGuard guard;
859
860     // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
861     int statusCode = [r respondsToSelector:@selector(statusCode)] ? [(id)r statusCode] : 0;
862     if (statusCode != 304)
863         [r adjustMIMETypeIfNecessary];
864
865     if ([m_handle->firstRequest().nsURLRequest() _propertyForKey:@"ForceHTMLMIMEType"])
866         [r _setMIMEType:@"text/html"];
867
868 #if ENABLE(WML)
869     const KURL& url = [r URL];
870     if (url.isLocalFile()) {
871         // FIXME: Workaround for <rdar://problem/6917571>: The WML file extension ".wml" is not mapped to
872         // the right MIME type, work around that CFNetwork problem, to unbreak WML support for local files.
873         const String& path = url.path();
874   
875         DEFINE_STATIC_LOCAL(const String, wmlExt, (".wml"));
876         if (path.endsWith(wmlExt, false)) {
877             static NSString* defaultMIMETypeString = [(NSString*) defaultMIMEType() retain];
878             if ([[r MIMEType] isEqualToString:defaultMIMETypeString])
879                 [r _setMIMEType:@"text/vnd.wap.wml"];
880         }
881     }
882 #endif
883
884     m_handle->client()->didReceiveResponse(m_handle, r);
885 }
886
887 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data lengthReceived:(long long)lengthReceived
888 {
889     UNUSED_PARAM(connection);
890
891     LOG(Network, "Handle %p delegate connection:%p didReceiveData:%p lengthReceived:%lld", m_handle, connection, data, lengthReceived);
892
893     if (!m_handle || !m_handle->client())
894         return;
895     // FIXME: If we get more than 2B bytes in a single chunk, this code won't do the right thing.
896     // However, with today's computers and networking speeds, this won't happen in practice.
897     // Could be an issue with a giant local file.
898     CallbackGuard guard;
899     m_handle->client()->didReceiveData(m_handle, (const char*)[data bytes], [data length], static_cast<int>(lengthReceived));
900 }
901
902 - (void)connection:(NSURLConnection *)connection willStopBufferingData:(NSData *)data
903 {
904     UNUSED_PARAM(connection);
905
906     LOG(Network, "Handle %p delegate connection:%p willStopBufferingData:%p", m_handle, connection, data);
907
908     if (!m_handle || !m_handle->client())
909         return;
910     // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
911     // However, with today's computers and networking speeds, this won't happen in practice.
912     // Could be an issue with a giant local file.
913     CallbackGuard guard;
914     m_handle->client()->willStopBufferingData(m_handle, (const char*)[data bytes], static_cast<int>([data length]));
915 }
916
917 - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
918 {
919     UNUSED_PARAM(connection);
920     UNUSED_PARAM(bytesWritten);
921
922     LOG(Network, "Handle %p delegate connection:%p didSendBodyData:%d totalBytesWritten:%d totalBytesExpectedToWrite:%d", m_handle, connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
923
924     if (!m_handle || !m_handle->client())
925         return;
926     CallbackGuard guard;
927     m_handle->client()->didSendData(m_handle, totalBytesWritten, totalBytesExpectedToWrite);
928 }
929
930 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
931 {
932     UNUSED_PARAM(connection);
933
934     LOG(Network, "Handle %p delegate connectionDidFinishLoading:%p", m_handle, connection);
935
936     if (!m_handle || !m_handle->client())
937         return;
938     CallbackGuard guard;
939
940     if (!ResourceHandle::didSendBodyDataDelegateExists())
941         disassociateStreamWithResourceHandle([m_handle->firstRequest().nsURLRequest() HTTPBodyStream]);
942
943     m_handle->client()->didFinishLoading(m_handle, 0);
944 }
945
946 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
947 {
948     UNUSED_PARAM(connection);
949
950     LOG(Network, "Handle %p delegate connection:%p didFailWithError:%@", m_handle, connection, error);
951
952     if (!m_handle || !m_handle->client())
953         return;
954     CallbackGuard guard;
955
956     if (!ResourceHandle::didSendBodyDataDelegateExists())
957         disassociateStreamWithResourceHandle([m_handle->firstRequest().nsURLRequest() HTTPBodyStream]);
958
959     m_handle->client()->didFail(m_handle, error);
960 }
961
962 #ifdef BUILDING_ON_TIGER
963 - (void)_callConnectionWillCacheResponseWithInfo:(NSMutableDictionary *)info
964 {
965     NSURLConnection *connection = [info objectForKey:@"connection"];
966     NSCachedURLResponse *cachedResponse = [info objectForKey:@"cachedResponse"];
967     NSCachedURLResponse *result = [self connection:connection willCacheResponse:cachedResponse];
968     if (result)
969         [info setObject:result forKey:@"result"];
970 }
971 #endif
972
973 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
974 {
975     LOG(Network, "Handle %p delegate connection:%p willCacheResponse:%p", m_handle, connection, cachedResponse);
976
977 #ifdef BUILDING_ON_TIGER
978     // On Tiger CFURLConnection can sometimes call the connection:willCacheResponse: delegate method on
979     // a secondary thread instead of the main thread. If this happens perform the work on the main thread.
980     if (!pthread_main_np()) {
981         NSMutableDictionary *info = [[NSMutableDictionary alloc] init];
982         if (connection)
983             [info setObject:connection forKey:@"connection"];
984         if (cachedResponse)
985             [info setObject:cachedResponse forKey:@"cachedResponse"];
986
987         // Include synchronous url connection's mode as an acceptable run loopmode
988         // <rdar://problem/5511842>
989         NSArray *modes = [[NSArray alloc] initWithObjects:(NSString *)kCFRunLoopCommonModes, @"NSSynchronousURLConnection_PrivateMode", nil];        
990         [self performSelectorOnMainThread:@selector(_callConnectionWillCacheResponseWithInfo:) withObject:info waitUntilDone:YES modes:modes];
991         [modes release];
992
993         NSCachedURLResponse *result = [[info valueForKey:@"result"] retain];
994         [info release];
995
996         return [result autorelease];
997     }
998 #else
999     UNUSED_PARAM(connection);
1000 #endif
1001
1002 #ifndef NDEBUG
1003     if (isInitializingConnection)
1004         LOG_ERROR("connection:willCacheResponse: was called inside of [NSURLConnection initWithRequest:delegate:] (4067625)");
1005 #endif
1006
1007     if (!m_handle || !m_handle->client())
1008         return nil;
1009
1010     CallbackGuard guard;
1011     
1012     NSCachedURLResponse *newResponse = m_handle->client()->willCacheResponse(m_handle, cachedResponse);
1013     if (newResponse != cachedResponse)
1014         return newResponse;
1015     
1016     CacheStoragePolicy policy = static_cast<CacheStoragePolicy>([newResponse storagePolicy]);
1017         
1018     m_handle->client()->willCacheResponse(m_handle, policy);
1019
1020     if (static_cast<NSURLCacheStoragePolicy>(policy) != [newResponse storagePolicy])
1021         newResponse = [[[NSCachedURLResponse alloc] initWithResponse:[newResponse response]
1022                                                                 data:[newResponse data]
1023                                                             userInfo:[newResponse userInfo]
1024                                                        storagePolicy:static_cast<NSURLCacheStoragePolicy>(policy)] autorelease];
1025
1026     return newResponse;
1027 }
1028
1029 @end
1030
1031 #ifndef BUILDING_ON_TIGER
1032
1033 WebCoreSynchronousLoaderClient::~WebCoreSynchronousLoaderClient()
1034 {
1035     [m_response release];
1036     [m_data release];
1037     [m_error release];
1038 }
1039
1040 void WebCoreSynchronousLoaderClient::willSendRequest(ResourceHandle* handle, ResourceRequest& request, const ResourceResponse& /*redirectResponse*/)
1041 {
1042     // FIXME: This needs to be fixed to follow the redirect correctly even for cross-domain requests.
1043     if (!protocolHostAndPortAreEqual(handle->firstRequest().url(), request.url())) {
1044         ASSERT(!m_error);
1045         m_error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:nil];
1046         m_isDone = true;
1047         request = 0;
1048         return;
1049     }
1050 }
1051
1052 bool WebCoreSynchronousLoaderClient::shouldUseCredentialStorage(ResourceHandle*)
1053 {
1054     // FIXME: We should ask FrameLoaderClient whether using credential storage is globally forbidden.
1055     return m_allowStoredCredentials;
1056 }
1057
1058 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
1059 bool WebCoreSynchronousLoaderClient::canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&)
1060 {
1061     // FIXME: We should ask FrameLoaderClient.
1062     return true;
1063 }
1064 #endif
1065
1066 void WebCoreSynchronousLoaderClient::didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge& challenge)
1067 {
1068     // FIXME: The user should be asked for credentials, as in async case.
1069     [challenge.sender() continueWithoutCredentialForAuthenticationChallenge:challenge.nsURLAuthenticationChallenge()];
1070 }
1071
1072 void WebCoreSynchronousLoaderClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
1073 {
1074     [m_response release];
1075     m_response = [response.nsURLResponse() copy];
1076 }
1077
1078 void WebCoreSynchronousLoaderClient::didReceiveData(ResourceHandle*, const char* data, int length, int /*lengthReceived*/)
1079 {
1080     if (!m_data)
1081         m_data = [[NSMutableData alloc] init];
1082     [m_data appendBytes:data length:length];
1083 }
1084
1085 void WebCoreSynchronousLoaderClient::didFinishLoading(ResourceHandle*, double)
1086 {
1087     m_isDone = true;
1088 }
1089
1090 void WebCoreSynchronousLoaderClient::didFail(ResourceHandle*, const ResourceError& error)
1091 {
1092     ASSERT(!m_error);
1093
1094     m_error = [error copy];
1095     m_isDone = true;
1096 }
1097
1098 #endif // BUILDING_ON_TIGER
1099
1100 #endif // !USE(CFNETWORK)