1/*
2 * Copyright (C) 2004, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#import "config.h"
27#import "WebCoreResourceHandleAsDelegate.h"
28
29#if !USE(CFNETWORK)
30
31#import "AuthenticationChallenge.h"
32#import "AuthenticationMac.h"
33#import "Logging.h"
34#import "ResourceHandle.h"
35#import "ResourceHandleClient.h"
36#import "ResourceRequest.h"
37#import "ResourceResponse.h"
38#import "SharedBuffer.h"
39#import "WebCoreURLResponse.h"
40
41@interface NSURLRequest (Details)
42- (id)_propertyForKey:(NSString *)key;
43@end
44
45using namespace WebCore;
46
47@implementation WebCoreResourceHandleAsDelegate
48
49- (id)initWithHandle:(ResourceHandle*)handle
50{
51    self = [self init];
52    if (!self)
53        return nil;
54    m_handle = handle;
55    return self;
56}
57
58- (void)detachHandle
59{
60    m_handle = 0;
61}
62
63- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)newRequest redirectResponse:(NSURLResponse *)redirectResponse
64{
65    UNUSED_PARAM(connection);
66
67    if (!m_handle)
68        return nil;
69
70    redirectResponse = synthesizeRedirectResponseIfNecessary(connection, newRequest, redirectResponse);
71
72    // See <rdar://problem/5380697>. This is a workaround for a behavior change in CFNetwork where willSendRequest gets called more often.
73    if (!redirectResponse)
74        return newRequest;
75
76#if !LOG_DISABLED
77    if ([redirectResponse isKindOfClass:[NSHTTPURLResponse class]])
78        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"]);
79    else
80        LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:non-HTTP", m_handle, connection, [newRequest description]);
81#endif
82
83    ResourceRequest request = newRequest;
84
85    m_handle->willSendRequest(request, redirectResponse);
86
87    return request.nsURLRequest(UpdateHTTPBody);
88}
89
90- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
91{
92    UNUSED_PARAM(connection);
93
94    LOG(Network, "Handle %p delegate connectionShouldUseCredentialStorage:%p", m_handle, connection);
95
96    if (!m_handle)
97        return NO;
98
99    return m_handle->shouldUseCredentialStorage();
100}
101
102- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
103{
104    UNUSED_PARAM(connection);
105
106    LOG(Network, "Handle %p delegate connection:%p didReceiveAuthenticationChallenge:%p", m_handle, connection, challenge);
107
108    if (!m_handle) {
109        [[challenge sender] cancelAuthenticationChallenge:challenge];
110        return;
111    }
112    m_handle->didReceiveAuthenticationChallenge(core(challenge));
113}
114
115- (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
116{
117    // FIXME: We probably don't need to implement this (see <rdar://problem/8960124>).
118
119    UNUSED_PARAM(connection);
120
121    LOG(Network, "Handle %p delegate connection:%p didCancelAuthenticationChallenge:%p", m_handle, connection, challenge);
122
123    if (!m_handle)
124        return;
125    m_handle->didCancelAuthenticationChallenge(core(challenge));
126}
127
128#if USE(PROTECTION_SPACE_AUTH_CALLBACK)
129- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
130{
131    UNUSED_PARAM(connection);
132
133    LOG(Network, "Handle %p delegate connection:%p canAuthenticateAgainstProtectionSpace:%@://%@:%u realm:%@ method:%@ %@%@", m_handle, connection, [protectionSpace protocol], [protectionSpace host], [protectionSpace port], [protectionSpace realm], [protectionSpace authenticationMethod], [protectionSpace isProxy] ? @"proxy:" : @"", [protectionSpace isProxy] ? [protectionSpace proxyType] : @"");
134
135    if (!m_handle)
136        return NO;
137
138    return m_handle->canAuthenticateAgainstProtectionSpace(core(protectionSpace));
139}
140#endif
141
142- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)r
143{
144    UNUSED_PARAM(connection);
145
146    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]);
147
148    if (!m_handle || !m_handle->client())
149        return;
150
151    // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
152    int statusCode = [r respondsToSelector:@selector(statusCode)] ? [(id)r statusCode] : 0;
153    if (statusCode != 304)
154        adjustMIMETypeIfNecessary([r _CFURLResponse]);
155
156    if ([m_handle->firstRequest().nsURLRequest(DoNotUpdateHTTPBody) _propertyForKey:@"ForceHTMLMIMEType"])
157        [r _setMIMEType:@"text/html"];
158
159    m_handle->client()->didReceiveResponse(m_handle, r);
160}
161
162#if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
163- (void)connection:(NSURLConnection *)connection didReceiveDataArray:(NSArray *)dataArray
164{
165    UNUSED_PARAM(connection);
166    LOG(Network, "Handle %p delegate connection:%p didReceiveDataArray:%p arraySize:%d", m_handle, connection, dataArray, [dataArray count]);
167
168    if (!dataArray)
169        return;
170
171    if (!m_handle || !m_handle->client())
172        return;
173
174    m_handle->handleDataArray(reinterpret_cast<CFArrayRef>(dataArray));
175    // The call to didReceiveData above can cancel a load, and if so, the delegate (self) could have been deallocated by this point.
176}
177#endif
178
179- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data lengthReceived:(long long)lengthReceived
180{
181    UNUSED_PARAM(connection);
182    UNUSED_PARAM(lengthReceived);
183
184    LOG(Network, "Handle %p delegate connection:%p didReceiveData:%p lengthReceived:%lld", m_handle, connection, data, lengthReceived);
185
186    if (!m_handle || !m_handle->client())
187        return;
188    // FIXME: If we get more than 2B bytes in a single chunk, this code won't do the right thing.
189    // However, with today's computers and networking speeds, this won't happen in practice.
190    // Could be an issue with a giant local file.
191
192    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793
193    // -1 means we do not provide any data about transfer size to inspector so it would use
194    // Content-Length headers or content size to show transfer size.
195    m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::wrapNSData(data), -1);
196}
197
198- (void)connection:(NSURLConnection *)connection willStopBufferingData:(NSData *)data
199{
200    UNUSED_PARAM(connection);
201
202    LOG(Network, "Handle %p delegate connection:%p willStopBufferingData:%p", m_handle, connection, data);
203
204    if (!m_handle || !m_handle->client())
205        return;
206    // FIXME: If we get a resource with more than 2B bytes, this code won't do the right thing.
207    // However, with today's computers and networking speeds, this won't happen in practice.
208    // Could be an issue with a giant local file.
209    m_handle->client()->willStopBufferingData(m_handle, (const char*)[data bytes], static_cast<int>([data length]));
210}
211
212- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
213{
214    UNUSED_PARAM(connection);
215    UNUSED_PARAM(bytesWritten);
216
217    LOG(Network, "Handle %p delegate connection:%p didSendBodyData:%d totalBytesWritten:%d totalBytesExpectedToWrite:%d", m_handle, connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
218
219    if (!m_handle || !m_handle->client())
220        return;
221    m_handle->client()->didSendData(m_handle, totalBytesWritten, totalBytesExpectedToWrite);
222}
223
224- (void)connectionDidFinishLoading:(NSURLConnection *)connection
225{
226    UNUSED_PARAM(connection);
227
228    LOG(Network, "Handle %p delegate connectionDidFinishLoading:%p", m_handle, connection);
229
230    if (!m_handle || !m_handle->client())
231        return;
232
233    m_handle->client()->didFinishLoading(m_handle, 0);
234}
235
236- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
237{
238    UNUSED_PARAM(connection);
239
240    LOG(Network, "Handle %p delegate connection:%p didFailWithError:%@", m_handle, connection, error);
241
242    if (!m_handle || !m_handle->client())
243        return;
244
245    m_handle->client()->didFail(m_handle, error);
246}
247
248
249- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
250{
251    LOG(Network, "Handle %p delegate connection:%p willCacheResponse:%p", m_handle, connection, cachedResponse);
252
253    UNUSED_PARAM(connection);
254
255    if (!m_handle || !m_handle->client())
256        return nil;
257
258    // Workaround for <rdar://problem/6300990> Caching does not respect Vary HTTP header.
259    // FIXME: WebCore cache has issues with Vary, too (bug 58797, bug 71509).
260    if ([[cachedResponse response] isKindOfClass:[NSHTTPURLResponse class]]
261        && [[(NSHTTPURLResponse *)[cachedResponse response] allHeaderFields] objectForKey:@"Vary"])
262        return nil;
263
264    return m_handle->client()->willCacheResponse(m_handle, cachedResponse);
265}
266
267@end
268
269#endif // !USE(CFNETWORK)
270
271