2011-01-23 Patrick Gansterer <paroga@webkit.org>
[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 (supportsSettingConnectionProperties) {
243         NSDictionary *sessionID = shouldUseCredentialStorage ? [NSDictionary dictionary] : [NSDictionary dictionaryWithObject:@"WebKitPrivateSession" forKey:@"_kCFURLConnectionSessionID"];
244         NSDictionary *propertyDictionary = [NSDictionary dictionaryWithObject:sessionID forKey:@"kCFURLConnectionSocketStreamProperties"];
245         d->m_connection.adoptNS([[NSURLConnection alloc] _initWithRequest:nsRequest delegate:delegate usesCache:YES maxContentLength:0 startImmediately:NO connectionProperties:propertyDictionary]);
246         return;
247     }
248
249     d->m_connection.adoptNS([[NSURLConnection alloc] initWithRequest:nsRequest delegate:delegate startImmediately:NO]);
250     return;
251
252 #else
253     // Building on Tiger. Don't use WebCore credential storage, don't try to disable content sniffing.
254     UNUSED_PARAM(shouldUseCredentialStorage);
255     UNUSED_PARAM(shouldContentSniff);
256     d->m_connection.adoptNS([[NSURLConnection alloc] initWithRequest:firstRequest().nsURLRequest() delegate:delegate]);
257 #endif
258 }
259
260 bool ResourceHandle::start(NetworkingContext* context)
261 {
262     if (!context)
263         return false;
264
265     BEGIN_BLOCK_OBJC_EXCEPTIONS;
266
267     // If NetworkingContext is invalid then we are no longer attached to a Page,
268     // this must be an attempted load from an unload event handler, so let's just block it.
269     if (!context->isValid())
270         return false;
271
272 #ifndef NDEBUG
273     isInitializingConnection = YES;
274 #endif
275
276     ASSERT(!d->m_proxy);
277     d->m_proxy.adoptNS(wkCreateNSURLConnectionDelegateProxy());
278     [static_cast<WebCoreNSURLConnectionDelegateProxy*>(d->m_proxy.get()) setDelegate:ResourceHandle::delegate()];
279
280     bool shouldUseCredentialStorage = !client() || client()->shouldUseCredentialStorage(this);
281
282     if (!ResourceHandle::didSendBodyDataDelegateExists())
283         associateStreamWithResourceHandle([firstRequest().nsURLRequest() HTTPBodyStream], this);
284
285 #ifdef BUILDING_ON_TIGER
286     // A conditional request sent by WebCore (e.g. to update appcache) can be for a resource that is not cacheable by NSURLConnection,
287     // which can get confused and fail to load it in this case.
288     if (firstRequest().isConditional())
289         firstRequest().setCachePolicy(ReloadIgnoringCacheData);
290 #endif
291
292     d->m_needsSiteSpecificQuirks = context->needsSiteSpecificQuirks();
293
294     createNSURLConnection(
295         d->m_proxy.get(),
296         shouldUseCredentialStorage,
297         d->m_shouldContentSniff || context->localFileContentSniffingEnabled());
298
299 #ifndef BUILDING_ON_TIGER
300     bool scheduled = false;
301     if (SchedulePairHashSet* scheduledPairs = context->scheduledRunLoopPairs()) {
302         SchedulePairHashSet::iterator end = scheduledPairs->end();
303         for (SchedulePairHashSet::iterator it = scheduledPairs->begin(); it != end; ++it) {
304             if (NSRunLoop *runLoop = (*it)->nsRunLoop()) {
305                 [connection() scheduleInRunLoop:runLoop forMode:(NSString *)(*it)->mode()];
306                 scheduled = true;
307             }
308         }
309     }
310
311     // Start the connection if we did schedule with at least one runloop.
312     // We can't start the connection until we have one runloop scheduled.
313     if (scheduled)
314         [connection() start];
315     else
316         d->m_startWhenScheduled = true;
317 #endif
318
319 #ifndef NDEBUG
320     isInitializingConnection = NO;
321 #endif
322
323     LOG(Network, "Handle %p starting connection %p for %@", this, connection(), firstRequest().nsURLRequest());
324     
325     if (d->m_connection) {
326         if (d->m_defersLoading)
327             wkSetNSURLConnectionDefersCallbacks(connection(), YES);
328
329         return true;
330     }
331
332     END_BLOCK_OBJC_EXCEPTIONS;
333
334     return false;
335 }
336
337 void ResourceHandle::cancel()
338 {
339     LOG(Network, "Handle %p cancel connection %p", this, d->m_connection.get());
340
341     // Leaks were seen on HTTP tests without this; can be removed once <rdar://problem/6886937> is fixed.
342     if (d->m_currentMacChallenge)
343         [[d->m_currentMacChallenge sender] cancelAuthenticationChallenge:d->m_currentMacChallenge];
344
345     if (!ResourceHandle::didSendBodyDataDelegateExists())
346         disassociateStreamWithResourceHandle([firstRequest().nsURLRequest() HTTPBodyStream]);
347     [d->m_connection.get() cancel];
348 }
349
350 void ResourceHandle::platformSetDefersLoading(bool defers)
351 {
352     if (d->m_connection)
353         wkSetNSURLConnectionDefersCallbacks(d->m_connection.get(), defers);
354 }
355
356 void ResourceHandle::schedule(SchedulePair* pair)
357 {
358 #ifndef BUILDING_ON_TIGER
359     NSRunLoop *runLoop = pair->nsRunLoop();
360     if (!runLoop)
361         return;
362     [d->m_connection.get() scheduleInRunLoop:runLoop forMode:(NSString *)pair->mode()];
363     if (d->m_startWhenScheduled) {
364         [d->m_connection.get() start];
365         d->m_startWhenScheduled = false;
366     }
367 #else
368     UNUSED_PARAM(pair);
369 #endif
370 }
371
372 void ResourceHandle::unschedule(SchedulePair* pair)
373 {
374 #ifndef BUILDING_ON_TIGER
375     if (NSRunLoop *runLoop = pair->nsRunLoop())
376         [d->m_connection.get() unscheduleFromRunLoop:runLoop forMode:(NSString *)pair->mode()];
377 #else
378     UNUSED_PARAM(pair);
379 #endif
380 }
381
382 WebCoreResourceHandleAsDelegate *ResourceHandle::delegate()
383 {
384     if (!d->m_delegate) {
385         WebCoreResourceHandleAsDelegate *delegate = [[WebCoreResourceHandleAsDelegate alloc] initWithHandle:this];
386         d->m_delegate = delegate;
387         [delegate release];
388     }
389     return d->m_delegate.get();
390 }
391
392 void ResourceHandle::releaseDelegate()
393 {
394     if (!d->m_delegate)
395         return;
396     if (d->m_proxy)
397         [d->m_proxy.get() setDelegate:nil];
398     [d->m_delegate.get() detachHandle];
399     d->m_delegate = nil;
400 }
401
402 bool ResourceHandle::supportsBufferedData()
403 {
404     static bool supportsBufferedData = [NSURLConnection instancesRespondToSelector:@selector(_bufferedData)];
405     return supportsBufferedData;
406 }
407
408 PassRefPtr<SharedBuffer> ResourceHandle::bufferedData()
409 {
410     if (ResourceHandle::supportsBufferedData())
411         return SharedBuffer::wrapNSData([d->m_connection.get() _bufferedData]);
412
413     return 0;
414 }
415
416 id ResourceHandle::releaseProxy()
417 {
418     id proxy = [[d->m_proxy.get() retain] autorelease];
419     d->m_proxy = nil;
420     [proxy setDelegate:nil];
421     return proxy;
422 }
423
424 NSURLConnection *ResourceHandle::connection() const
425 {
426     return d->m_connection.get();
427 }
428
429 bool ResourceHandle::loadsBlocked()
430 {
431 #ifndef BUILDING_ON_TIGER
432     return false;
433 #else
434     // On Tiger, if we're in an NSURLConnection callback, that blocks all other NSURLConnection callbacks.
435     // On Leopard and newer, it blocks only callbacks on that same NSURLConnection object, which is not
436     // a problem in practice.
437     return inNSURLConnectionCallback != 0;
438 #endif
439 }
440
441 bool ResourceHandle::willLoadFromCache(ResourceRequest& request, Frame*)
442 {
443 #ifndef BUILDING_ON_TIGER
444     request.setCachePolicy(ReturnCacheDataDontLoad);
445     NSURLResponse *nsURLResponse = nil;
446     BEGIN_BLOCK_OBJC_EXCEPTIONS;
447     
448    [NSURLConnection sendSynchronousRequest:request.nsURLRequest() returningResponse:&nsURLResponse error:nil];
449     
450     END_BLOCK_OBJC_EXCEPTIONS;
451     
452     return nsURLResponse;
453 #else
454     // <rdar://problem/6803217> - Re-enable after <rdar://problem/6786454> is resolved.
455     UNUSED_PARAM(request);
456     return false;
457 #endif
458 }
459
460 void ResourceHandle::loadResourceSynchronously(NetworkingContext* context, const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
461 {
462     LOG(Network, "ResourceHandle::loadResourceSynchronously:%@ allowStoredCredentials:%u", request.nsURLRequest(), storedCredentials);
463
464 #if ENABLE(BLOB)
465     if (request.url().protocolIs("blob"))
466         if (blobRegistry().loadResourceSynchronously(request, error, response, data))
467             return;
468 #endif
469
470     NSError *nsError = nil;
471     NSURLResponse *nsURLResponse = nil;
472     NSData *result = nil;
473
474     ASSERT(!request.isEmpty());
475     
476 #ifndef BUILDING_ON_TIGER
477     OwnPtr<WebCoreSynchronousLoaderClient> client = WebCoreSynchronousLoaderClient::create();
478     client->setAllowStoredCredentials(storedCredentials == AllowStoredCredentials);
479
480     RefPtr<ResourceHandle> handle = adoptRef(new ResourceHandle(request, client.get(), false /*defersLoading*/, true /*shouldContentSniff*/));
481
482     if (context && handle->d->m_scheduledFailureType != NoFailure) {
483         error = context->blockedError(request);
484         return;
485     }
486
487     handle->createNSURLConnection(
488         handle->delegate(), // A synchronous request cannot turn into a download, so there is no need to proxy the delegate.
489         storedCredentials == AllowStoredCredentials,
490         handle->shouldContentSniff() || (context && context->localFileContentSniffingEnabled()));
491
492     [handle->connection() scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:WebCoreSynchronousLoaderRunLoopMode];
493     [handle->connection() start];
494     
495     while (!client->isDone())
496         [[NSRunLoop currentRunLoop] runMode:WebCoreSynchronousLoaderRunLoopMode beforeDate:[NSDate distantFuture]];
497
498     result = client->data();
499     nsURLResponse = client->response();
500     nsError = client->error();
501     
502     [handle->connection() cancel];
503
504 #else
505     UNUSED_PARAM(storedCredentials);
506     UNUSED_PARAM(context);
507     NSURLRequest *firstRequest = request.nsURLRequest();
508
509     // If a URL already has cookies, then we'll relax the 3rd party cookie policy and accept new cookies.
510     NSHTTPCookieStorage *sharedStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
511     if ([sharedStorage cookieAcceptPolicy] == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain && [[sharedStorage cookiesForURL:[firstRequest URL]] count]) {
512         NSMutableURLRequest *mutableRequest = [[firstRequest mutableCopy] autorelease];
513         [mutableRequest setMainDocumentURL:[mutableRequest URL]];
514         firstRequest = mutableRequest;
515     }
516
517     BEGIN_BLOCK_OBJC_EXCEPTIONS;
518     result = [NSURLConnection sendSynchronousRequest:firstRequest returningResponse:&nsURLResponse error:&nsError];
519     END_BLOCK_OBJC_EXCEPTIONS;
520 #endif
521
522     if (!nsError)
523         response = nsURLResponse;
524     else {
525         response = ResourceResponse(request.url(), String(), 0, String(), String());
526         if ([nsError domain] == NSURLErrorDomain)
527             switch ([nsError code]) {
528                 case NSURLErrorUserCancelledAuthentication:
529                     // FIXME: we should really return the actual HTTP response, but sendSynchronousRequest doesn't provide us with one.
530                     response.setHTTPStatusCode(401);
531                     break;
532                 default:
533                     response.setHTTPStatusCode([nsError code]);
534             }
535         else
536             response.setHTTPStatusCode(404);
537     }
538     
539     data.resize([result length]);
540     memcpy(data.data(), [result bytes], [result length]);
541     
542     error = nsError;
543 }
544
545 void ResourceHandle::willSendRequest(ResourceRequest& request, const ResourceResponse& redirectResponse)
546 {
547     const KURL& url = request.url();
548     d->m_user = url.user();
549     d->m_pass = url.pass();
550     d->m_lastHTTPMethod = request.httpMethod();
551     request.removeCredentials();
552     if (!protocolHostAndPortAreEqual(request.url(), redirectResponse.url()))
553         request.clearHTTPAuthorization();
554
555     client()->willSendRequest(this, request, redirectResponse);
556 }
557
558 bool ResourceHandle::shouldUseCredentialStorage()
559 {
560     if (client())
561         return client()->shouldUseCredentialStorage(this);
562
563     return false;
564 }
565
566 void ResourceHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge& challenge)
567 {
568     ASSERT(!d->m_currentMacChallenge);
569     ASSERT(d->m_currentWebChallenge.isNull());
570     // Since NSURLConnection networking relies on keeping a reference to the original NSURLAuthenticationChallenge,
571     // we make sure that is actually present
572     ASSERT(challenge.nsURLAuthenticationChallenge());
573
574     if (!d->m_user.isNull() && !d->m_pass.isNull()) {
575         NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:d->m_user
576                                                                    password:d->m_pass
577                                                                 persistence:NSURLCredentialPersistenceForSession];
578         d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
579         d->m_currentWebChallenge = challenge;
580         receivedCredential(challenge, core(credential));
581         [credential release];
582         // FIXME: Per the specification, the user shouldn't be asked for credentials if there were incorrect ones provided explicitly.
583         d->m_user = String();
584         d->m_pass = String();
585         return;
586     }
587
588 #ifndef BUILDING_ON_TIGER
589     if (!client() || client()->shouldUseCredentialStorage(this)) {
590         if (!d->m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
591             // The stored credential wasn't accepted, stop using it.
592             // There is a race condition here, since a different credential might have already been stored by another ResourceHandle,
593             // but the observable effect should be very minor, if any.
594             CredentialStorage::remove(challenge.protectionSpace());
595         }
596
597         if (!challenge.previousFailureCount()) {
598             Credential credential = CredentialStorage::get(challenge.protectionSpace());
599             if (!credential.isEmpty() && credential != d->m_initialCredential) {
600                 ASSERT(credential.persistence() == CredentialPersistenceNone);
601                 if (challenge.failureResponse().httpStatusCode() == 401) {
602                     // Store the credential back, possibly adding it as a default for this directory.
603                     CredentialStorage::set(credential, challenge.protectionSpace(), firstRequest().url());
604                 }
605                 [challenge.sender() useCredential:mac(credential) forAuthenticationChallenge:mac(challenge)];
606                 return;
607             }
608         }
609     }
610 #endif
611
612     d->m_currentMacChallenge = challenge.nsURLAuthenticationChallenge();
613     d->m_currentWebChallenge = core(d->m_currentMacChallenge);
614     d->m_currentWebChallenge.setAuthenticationClient(this);
615
616     if (client())
617         client()->didReceiveAuthenticationChallenge(this, d->m_currentWebChallenge);
618 }
619
620 void ResourceHandle::didCancelAuthenticationChallenge(const AuthenticationChallenge& challenge)
621 {
622     ASSERT(d->m_currentMacChallenge);
623     ASSERT(d->m_currentMacChallenge == challenge.nsURLAuthenticationChallenge());
624     ASSERT(!d->m_currentWebChallenge.isNull());
625
626     if (client())
627         client()->didCancelAuthenticationChallenge(this, challenge);
628 }
629
630 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
631 bool ResourceHandle::canAuthenticateAgainstProtectionSpace(const ProtectionSpace& protectionSpace)
632 {
633     if (client())
634         return client()->canAuthenticateAgainstProtectionSpace(this, protectionSpace);
635         
636     return false;
637 }
638 #endif
639
640 void ResourceHandle::receivedCredential(const AuthenticationChallenge& challenge, const Credential& credential)
641 {
642     ASSERT(!challenge.isNull());
643     if (challenge != d->m_currentWebChallenge)
644         return;
645
646     // FIXME: Support empty credentials. Currently, an empty credential cannot be stored in WebCore credential storage, as that's empty value for its map.
647     if (credential.isEmpty()) {
648         receivedRequestToContinueWithoutCredential(challenge);
649         return;
650     }
651
652 #ifdef BUILDING_ON_TIGER
653     if (credential.persistence() == CredentialPersistenceNone) {
654         // NSURLCredentialPersistenceNone doesn't work on Tiger, so we have to use session persistence.
655         Credential webCredential(credential.user(), credential.password(), CredentialPersistenceForSession);
656         [[d->m_currentMacChallenge sender] useCredential:mac(webCredential) forAuthenticationChallenge:d->m_currentMacChallenge];
657     } else
658 #else
659     if (credential.persistence() == CredentialPersistenceForSession && (!d->m_needsSiteSpecificQuirks || ![[[mac(challenge) protectionSpace] host] isEqualToString:@"gallery.me.com"])) {
660         // Manage per-session credentials internally, because once NSURLCredentialPersistenceForSession is used, there is no way
661         // to ignore it for a particular request (short of removing it altogether).
662         // <rdar://problem/6867598> gallery.me.com is temporarily whitelisted, so that QuickTime plug-in could see the credentials.
663         Credential webCredential(credential, CredentialPersistenceNone);
664         KURL urlToStore;
665         if (challenge.failureResponse().httpStatusCode() == 401)
666             urlToStore = firstRequest().url();
667         CredentialStorage::set(webCredential, core([d->m_currentMacChallenge protectionSpace]), urlToStore);
668         [[d->m_currentMacChallenge sender] useCredential:mac(webCredential) forAuthenticationChallenge:d->m_currentMacChallenge];
669     } else
670 #endif
671         [[d->m_currentMacChallenge sender] useCredential:mac(credential) forAuthenticationChallenge:d->m_currentMacChallenge];
672
673     clearAuthentication();
674 }
675
676 void ResourceHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge& challenge)
677 {
678     ASSERT(!challenge.isNull());
679     if (challenge != d->m_currentWebChallenge)
680         return;
681
682     [[d->m_currentMacChallenge sender] continueWithoutCredentialForAuthenticationChallenge:d->m_currentMacChallenge];
683
684     clearAuthentication();
685 }
686
687 void ResourceHandle::receivedCancellation(const AuthenticationChallenge& challenge)
688 {
689     if (challenge != d->m_currentWebChallenge)
690         return;
691
692     if (client())
693         client()->receivedCancellation(this, challenge);
694 }
695
696 } // namespace WebCore
697
698 @implementation WebCoreResourceHandleAsDelegate
699
700 - (id)initWithHandle:(ResourceHandle*)handle
701 {
702     self = [self init];
703     if (!self)
704         return nil;
705     m_handle = handle;
706     return self;
707 }
708
709 - (void)detachHandle
710 {
711     m_handle = 0;
712 }
713
714 - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)newRequest redirectResponse:(NSURLResponse *)redirectResponse
715 {
716     UNUSED_PARAM(connection);
717
718     // the willSendRequest call may cancel this load, in which case self could be deallocated
719     RetainPtr<WebCoreResourceHandleAsDelegate> protect(self);
720
721     if (!m_handle || !m_handle->client())
722         return nil;
723     
724     // See <rdar://problem/5380697> .  This is a workaround for a behavior change in CFNetwork where willSendRequest gets called more often.
725     if (!redirectResponse)
726         return newRequest;
727
728 #if !LOG_DISABLED
729     if ([redirectResponse isKindOfClass:[NSHTTPURLResponse class]])
730         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"]);
731     else
732         LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:non-HTTP", m_handle, connection, [newRequest description]); 
733 #endif
734
735     if ([redirectResponse isKindOfClass:[NSHTTPURLResponse class]] && [(NSHTTPURLResponse *)redirectResponse statusCode] == 307) {
736         String lastHTTPMethod = m_handle->lastHTTPMethod();
737         if (!equalIgnoringCase(lastHTTPMethod, String([newRequest HTTPMethod]))) {
738             NSMutableURLRequest *mutableRequest = [newRequest mutableCopy];
739             [mutableRequest setHTTPMethod:lastHTTPMethod];
740     
741             FormData* body = m_handle->firstRequest().httpBody();
742             if (!equalIgnoringCase(lastHTTPMethod, "GET") && body && !body->isEmpty())
743                 WebCore::setHTTPBody(mutableRequest, body);
744
745             String originalContentType = m_handle->firstRequest().httpContentType();
746             if (!originalContentType.isEmpty())
747                 [mutableRequest setValue:originalContentType forHTTPHeaderField:@"Content-Type"];
748
749             newRequest = [mutableRequest autorelease];
750         }
751     }
752
753     CallbackGuard guard;
754     ResourceRequest request = newRequest;
755
756     // Should not set Referer after a redirect from a secure resource to non-secure one.
757     if (!request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https"))
758         request.clearHTTPReferrer();
759
760     m_handle->willSendRequest(request, redirectResponse);
761
762     if (!ResourceHandle::didSendBodyDataDelegateExists()) {
763         // The client may change the request's body stream, in which case we have to re-associate
764         // the handle with the new stream so upload progress callbacks continue to work correctly.
765         NSInputStream* oldBodyStream = [newRequest HTTPBodyStream];
766         NSInputStream* newBodyStream = [request.nsURLRequest() HTTPBodyStream];
767         if (oldBodyStream != newBodyStream) {
768             disassociateStreamWithResourceHandle(oldBodyStream);
769             associateStreamWithResourceHandle(newBodyStream, m_handle);
770         }
771     }
772
773     return request.nsURLRequest();
774 }
775
776 - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
777 {
778     UNUSED_PARAM(connection);
779
780     LOG(Network, "Handle %p delegate connectionShouldUseCredentialStorage:%p", m_handle, connection);
781
782     if (!m_handle)
783         return NO;
784
785     CallbackGuard guard;
786     return m_handle->shouldUseCredentialStorage();
787 }
788
789 - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
790 {
791     UNUSED_PARAM(connection);
792
793     LOG(Network, "Handle %p delegate connection:%p didReceiveAuthenticationChallenge:%p", m_handle, connection, challenge);
794
795     if (!m_handle)
796         return;
797     CallbackGuard guard;
798     m_handle->didReceiveAuthenticationChallenge(core(challenge));
799 }
800
801 - (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
802 {
803     UNUSED_PARAM(connection);
804
805     LOG(Network, "Handle %p delegate connection:%p didCancelAuthenticationChallenge:%p", m_handle, connection, challenge);
806
807     if (!m_handle)
808         return;
809     CallbackGuard guard;
810     m_handle->didCancelAuthenticationChallenge(core(challenge));
811 }
812
813 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
814 - (BOOL)connection:(NSURLConnection *)unusedConnection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
815 {
816     UNUSED_PARAM(unusedConnection);
817     
818     if (!m_handle)
819         return NO;
820         
821     CallbackGuard guard;
822     return m_handle->canAuthenticateAgainstProtectionSpace(core(protectionSpace));
823 }
824 #endif
825
826 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)r
827 {
828     UNUSED_PARAM(connection);
829
830     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]);
831
832     if (!m_handle || !m_handle->client())
833         return;
834     CallbackGuard guard;
835
836     // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
837     int statusCode = [r respondsToSelector:@selector(statusCode)] ? [(id)r statusCode] : 0;
838     if (statusCode != 304)
839         [r adjustMIMETypeIfNecessary];
840
841     if ([m_handle->firstRequest().nsURLRequest() _propertyForKey:@"ForceHTMLMIMEType"])
842         [r _setMIMEType:@"text/html"];
843
844 #if ENABLE(WML)
845     const KURL& url = [r URL];
846     if (url.isLocalFile()) {
847         // FIXME: Workaround for <rdar://problem/6917571>: The WML file extension ".wml" is not mapped to
848         // the right MIME type, work around that CFNetwork problem, to unbreak WML support for local files.
849         const String& path = url.path();
850   
851         DEFINE_STATIC_LOCAL(const String, wmlExt, (".wml"));
852         if (path.endsWith(wmlExt, false)) {
853             static NSString* defaultMIMETypeString = [(NSString*) defaultMIMEType() retain];
854             if ([[r MIMEType] isEqualToString:defaultMIMETypeString])
855                 [r _setMIMEType:@"text/vnd.wap.wml"];
856         }
857     }
858 #endif
859
860     m_handle->client()->didReceiveResponse(m_handle, r);
861 }
862
863 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data lengthReceived:(long long)lengthReceived
864 {
865     UNUSED_PARAM(connection);
866
867     LOG(Network, "Handle %p delegate connection:%p didReceiveData:%p lengthReceived:%lld", m_handle, connection, data, lengthReceived);
868
869     if (!m_handle || !m_handle->client())
870         return;
871     // FIXME: If we get more than 2B bytes in a single chunk, this code won't do the right thing.
872     // However, with today's computers and networking speeds, this won't happen in practice.
873     // Could be an issue with a giant local file.
874     CallbackGuard guard;
875     m_handle->client()->didReceiveData(m_handle, (const char*)[data bytes], [data length], static_cast<int>(lengthReceived));
876 }
877
878 - (void)connection:(NSURLConnection *)connection willStopBufferingData:(NSData *)data
879 {
880     UNUSED_PARAM(connection);
881
882     LOG(Network, "Handle %p delegate connection:%p willStopBufferingData:%p", m_handle, connection, data);
883
884     if (!m_handle || !m_handle->client())
885         return;
886     // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
887     // However, with today's computers and networking speeds, this won't happen in practice.
888     // Could be an issue with a giant local file.
889     CallbackGuard guard;
890     m_handle->client()->willStopBufferingData(m_handle, (const char*)[data bytes], static_cast<int>([data length]));
891 }
892
893 - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
894 {
895     UNUSED_PARAM(connection);
896     UNUSED_PARAM(bytesWritten);
897
898     LOG(Network, "Handle %p delegate connection:%p didSendBodyData:%d totalBytesWritten:%d totalBytesExpectedToWrite:%d", m_handle, connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
899
900     if (!m_handle || !m_handle->client())
901         return;
902     CallbackGuard guard;
903     m_handle->client()->didSendData(m_handle, totalBytesWritten, totalBytesExpectedToWrite);
904 }
905
906 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
907 {
908     UNUSED_PARAM(connection);
909
910     LOG(Network, "Handle %p delegate connectionDidFinishLoading:%p", m_handle, connection);
911
912     if (!m_handle || !m_handle->client())
913         return;
914     CallbackGuard guard;
915
916     if (!ResourceHandle::didSendBodyDataDelegateExists())
917         disassociateStreamWithResourceHandle([m_handle->firstRequest().nsURLRequest() HTTPBodyStream]);
918
919     m_handle->client()->didFinishLoading(m_handle, 0);
920 }
921
922 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
923 {
924     UNUSED_PARAM(connection);
925
926     LOG(Network, "Handle %p delegate connection:%p didFailWithError:%@", m_handle, connection, error);
927
928     if (!m_handle || !m_handle->client())
929         return;
930     CallbackGuard guard;
931
932     if (!ResourceHandle::didSendBodyDataDelegateExists())
933         disassociateStreamWithResourceHandle([m_handle->firstRequest().nsURLRequest() HTTPBodyStream]);
934
935     m_handle->client()->didFail(m_handle, error);
936 }
937
938 #ifdef BUILDING_ON_TIGER
939 - (void)_callConnectionWillCacheResponseWithInfo:(NSMutableDictionary *)info
940 {
941     NSURLConnection *connection = [info objectForKey:@"connection"];
942     NSCachedURLResponse *cachedResponse = [info objectForKey:@"cachedResponse"];
943     NSCachedURLResponse *result = [self connection:connection willCacheResponse:cachedResponse];
944     if (result)
945         [info setObject:result forKey:@"result"];
946 }
947 #endif
948
949 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
950 {
951     LOG(Network, "Handle %p delegate connection:%p willCacheResponse:%p", m_handle, connection, cachedResponse);
952
953 #ifdef BUILDING_ON_TIGER
954     // On Tiger CFURLConnection can sometimes call the connection:willCacheResponse: delegate method on
955     // a secondary thread instead of the main thread. If this happens perform the work on the main thread.
956     if (!pthread_main_np()) {
957         NSMutableDictionary *info = [[NSMutableDictionary alloc] init];
958         if (connection)
959             [info setObject:connection forKey:@"connection"];
960         if (cachedResponse)
961             [info setObject:cachedResponse forKey:@"cachedResponse"];
962
963         // Include synchronous url connection's mode as an acceptable run loopmode
964         // <rdar://problem/5511842>
965         NSArray *modes = [[NSArray alloc] initWithObjects:(NSString *)kCFRunLoopCommonModes, @"NSSynchronousURLConnection_PrivateMode", nil];        
966         [self performSelectorOnMainThread:@selector(_callConnectionWillCacheResponseWithInfo:) withObject:info waitUntilDone:YES modes:modes];
967         [modes release];
968
969         NSCachedURLResponse *result = [[info valueForKey:@"result"] retain];
970         [info release];
971
972         return [result autorelease];
973     }
974 #else
975     UNUSED_PARAM(connection);
976 #endif
977
978 #ifndef NDEBUG
979     if (isInitializingConnection)
980         LOG_ERROR("connection:willCacheResponse: was called inside of [NSURLConnection initWithRequest:delegate:] (4067625)");
981 #endif
982
983     if (!m_handle || !m_handle->client())
984         return nil;
985
986     CallbackGuard guard;
987     
988     NSCachedURLResponse *newResponse = m_handle->client()->willCacheResponse(m_handle, cachedResponse);
989     if (newResponse != cachedResponse)
990         return newResponse;
991     
992     CacheStoragePolicy policy = static_cast<CacheStoragePolicy>([newResponse storagePolicy]);
993         
994     m_handle->client()->willCacheResponse(m_handle, policy);
995
996     if (static_cast<NSURLCacheStoragePolicy>(policy) != [newResponse storagePolicy])
997         newResponse = [[[NSCachedURLResponse alloc] initWithResponse:[newResponse response]
998                                                                 data:[newResponse data]
999                                                             userInfo:[newResponse userInfo]
1000                                                        storagePolicy:static_cast<NSURLCacheStoragePolicy>(policy)] autorelease];
1001
1002     return newResponse;
1003 }
1004
1005 @end
1006
1007 #ifndef BUILDING_ON_TIGER
1008
1009 WebCoreSynchronousLoaderClient::~WebCoreSynchronousLoaderClient()
1010 {
1011     [m_response release];
1012     [m_data release];
1013     [m_error release];
1014 }
1015
1016 void WebCoreSynchronousLoaderClient::willSendRequest(ResourceHandle* handle, ResourceRequest& request, const ResourceResponse& /*redirectResponse*/)
1017 {
1018     // FIXME: This needs to be fixed to follow the redirect correctly even for cross-domain requests.
1019     if (!protocolHostAndPortAreEqual(handle->firstRequest().url(), request.url())) {
1020         ASSERT(!m_error);
1021         m_error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:nil];
1022         m_isDone = true;
1023         request = 0;
1024         return;
1025     }
1026 }
1027
1028 bool WebCoreSynchronousLoaderClient::shouldUseCredentialStorage(ResourceHandle*)
1029 {
1030     // FIXME: We should ask FrameLoaderClient whether using credential storage is globally forbidden.
1031     return m_allowStoredCredentials;
1032 }
1033
1034 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
1035 bool WebCoreSynchronousLoaderClient::canAuthenticateAgainstProtectionSpace(ResourceHandle*, const ProtectionSpace&)
1036 {
1037     // FIXME: We should ask FrameLoaderClient.
1038     return true;
1039 }
1040 #endif
1041
1042 void WebCoreSynchronousLoaderClient::didReceiveAuthenticationChallenge(ResourceHandle*, const AuthenticationChallenge& challenge)
1043 {
1044     // FIXME: The user should be asked for credentials, as in async case.
1045     [challenge.sender() continueWithoutCredentialForAuthenticationChallenge:challenge.nsURLAuthenticationChallenge()];
1046 }
1047
1048 void WebCoreSynchronousLoaderClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
1049 {
1050     [m_response release];
1051     m_response = [response.nsURLResponse() copy];
1052 }
1053
1054 void WebCoreSynchronousLoaderClient::didReceiveData(ResourceHandle*, const char* data, int length, int /*lengthReceived*/)
1055 {
1056     if (!m_data)
1057         m_data = [[NSMutableData alloc] init];
1058     [m_data appendBytes:data length:length];
1059 }
1060
1061 void WebCoreSynchronousLoaderClient::didFinishLoading(ResourceHandle*, double)
1062 {
1063     m_isDone = true;
1064 }
1065
1066 void WebCoreSynchronousLoaderClient::didFail(ResourceHandle*, const ResourceError& error)
1067 {
1068     ASSERT(!m_error);
1069
1070     m_error = [error copy];
1071     m_isDone = true;
1072 }
1073
1074 #endif // BUILDING_ON_TIGER
1075
1076 #endif // !USE(CFNETWORK)