[Resource Timing] Gather timing information with reliable responseEnd time
[WebKit-https.git] / Source / WebCore / platform / network / mac / WebCoreResourceHandleAsDelegate.mm
1 /*
2  * Copyright (C) 2004-2017 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(CFURLCONNECTION)
30
31 #import "AuthenticationChallenge.h"
32 #import "AuthenticationMac.h"
33 #import "Logging.h"
34 #import "NSURLRequestSPI.h"
35 #import "ResourceHandle.h"
36 #import "ResourceHandleClient.h"
37 #import "ResourceRequest.h"
38 #import "ResourceResponse.h"
39 #import "SharedBuffer.h"
40 #import "WebCoreURLResponse.h"
41
42 using namespace WebCore;
43
44 @implementation WebCoreResourceHandleAsDelegate
45
46 - (id)initWithHandle:(ResourceHandle*)handle
47 {
48     self = [self init];
49     if (!self)
50         return nil;
51     m_handle = handle;
52     return self;
53 }
54
55 - (void)detachHandle
56 {
57     m_handle = nullptr;
58 }
59
60 - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)newRequest redirectResponse:(NSURLResponse *)redirectResponse
61 {
62     UNUSED_PARAM(connection);
63
64     if (!m_handle)
65         return nil;
66
67     redirectResponse = synthesizeRedirectResponseIfNecessary([connection currentRequest], newRequest, redirectResponse);
68     
69     // See <rdar://problem/5380697>. This is a workaround for a behavior change in CFNetwork where willSendRequest gets called more often.
70     if (!redirectResponse)
71         return newRequest;
72
73 #if !LOG_DISABLED
74     if ([redirectResponse isKindOfClass:[NSHTTPURLResponse class]])
75         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"]);
76     else
77         LOG(Network, "Handle %p delegate connection:%p willSendRequest:%@ redirectResponse:non-HTTP", m_handle, connection, [newRequest description]); 
78 #endif
79
80     return m_handle->willSendRequest(newRequest, redirectResponse).nsURLRequest(UpdateHTTPBody);
81 }
82
83 - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
84 {
85     UNUSED_PARAM(connection);
86
87     LOG(Network, "Handle %p delegate connectionShouldUseCredentialStorage:%p", m_handle, connection);
88
89 #if PLATFORM(IOS)
90     return NO;
91 #else
92     if (!m_handle)
93         return NO;
94
95     return m_handle->shouldUseCredentialStorage();
96 #endif
97 }
98
99 - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
100 {
101     UNUSED_PARAM(connection);
102
103     LOG(Network, "Handle %p delegate connection:%p didReceiveAuthenticationChallenge:%p", m_handle, connection, challenge);
104
105     if (!m_handle) {
106         [[challenge sender] cancelAuthenticationChallenge:challenge];
107         return;
108     }
109     m_handle->didReceiveAuthenticationChallenge(core(challenge));
110 }
111
112 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
113 - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
114 {
115     UNUSED_PARAM(connection);
116
117     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] : @"");
118
119     if (!m_handle)
120         return NO;
121
122     return m_handle->canAuthenticateAgainstProtectionSpace(ProtectionSpace(protectionSpace));
123 }
124 #endif
125
126 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
127 {
128     LOG(Network, "Handle %p delegate connection:%p didReceiveResponse:%p (HTTP status %d, reported MIMEType '%s')", m_handle, connection, response, [response respondsToSelector:@selector(statusCode)] ? [(id)response statusCode] : 0, [[response MIMEType] UTF8String]);
129
130     if (!m_handle || !m_handle->client())
131         return;
132
133     // Avoid MIME type sniffing if the response comes back as 304 Not Modified.
134     int statusCode = [response respondsToSelector:@selector(statusCode)] ? [(id)response statusCode] : 0;
135     if (statusCode != 304) {
136         bool isMainResourceLoad = m_handle->firstRequest().requester() == ResourceRequest::Requester::Main;
137         adjustMIMETypeIfNecessary([response _CFURLResponse], isMainResourceLoad);
138     }
139
140 #if !PLATFORM(IOS)
141     if ([m_handle->firstRequest().nsURLRequest(DoNotUpdateHTTPBody) _propertyForKey:@"ForceHTMLMIMEType"])
142         [response _setMIMEType:@"text/html"];
143 #endif
144
145     ResourceResponse resourceResponse(response);
146     resourceResponse.setSource(ResourceResponse::Source::Network);
147 #if ENABLE(WEB_TIMING)
148     ResourceHandle::getConnectionTimingData(connection, resourceResponse.deprecatedNetworkLoadMetrics());
149 #else
150     UNUSED_PARAM(connection);
151 #endif
152
153     m_handle->didReceiveResponse(WTFMove(resourceResponse));
154 }
155
156 #if USE(NETWORK_CFDATA_ARRAY_CALLBACK)
157 - (void)connection:(NSURLConnection *)connection didReceiveDataArray:(NSArray *)dataArray
158 {
159     UNUSED_PARAM(connection);
160     LOG(Network, "Handle %p delegate connection:%p didReceiveDataArray:%p arraySize:%d", m_handle, connection, dataArray, [dataArray count]);
161
162     if (!dataArray)
163         return;
164
165     if (!m_handle || !m_handle->client())
166         return;
167
168     m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::wrapCFDataArray(reinterpret_cast<CFArrayRef>(dataArray)), -1);
169     // The call to didReceiveData above can cancel a load, and if so, the delegate (self) could have been deallocated by this point.
170 }
171 #endif
172
173 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data lengthReceived:(long long)lengthReceived
174 {
175     UNUSED_PARAM(connection);
176     UNUSED_PARAM(lengthReceived);
177
178     LOG(Network, "Handle %p delegate connection:%p didReceiveData:%p lengthReceived:%lld", m_handle, connection, data, lengthReceived);
179
180 #if PLATFORM(IOS)
181     if ([data length] == 0) // <rdar://problem/5532931>
182         return;
183 #endif
184
185     if (!m_handle || !m_handle->client())
186         return;
187     // FIXME: If we get more than 2B bytes in a single chunk, this code won't do the right thing.
188     // However, with today's computers and networking speeds, this won't happen in practice.
189     // Could be an issue with a giant local file.
190
191     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=19793
192     // -1 means we do not provide any data about transfer size to inspector so it would use
193     // Content-Length headers or content size to show transfer size.
194     m_handle->client()->didReceiveBuffer(m_handle, SharedBuffer::wrapNSData(data), -1);
195 }
196
197 - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
198 {
199     UNUSED_PARAM(connection);
200     UNUSED_PARAM(bytesWritten);
201
202     LOG(Network, "Handle %p delegate connection:%p didSendBodyData:%d totalBytesWritten:%d totalBytesExpectedToWrite:%d", m_handle, connection, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
203
204     if (!m_handle || !m_handle->client())
205         return;
206     m_handle->client()->didSendData(m_handle, totalBytesWritten, totalBytesExpectedToWrite);
207 }
208
209 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
210 {
211     UNUSED_PARAM(connection);
212
213     LOG(Network, "Handle %p delegate connectionDidFinishLoading:%p", m_handle, connection);
214
215     if (!m_handle || !m_handle->client())
216         return;
217
218     m_handle->client()->didFinishLoading(m_handle);
219 }
220
221 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
222 {
223     UNUSED_PARAM(connection);
224
225     LOG(Network, "Handle %p delegate connection:%p didFailWithError:%@", m_handle, connection, error);
226
227     if (!m_handle || !m_handle->client())
228         return;
229
230     m_handle->client()->didFail(m_handle, error);
231 }
232
233
234 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
235 {
236     LOG(Network, "Handle %p delegate connection:%p willCacheResponse:%p", m_handle, connection, cachedResponse);
237
238     UNUSED_PARAM(connection);
239
240     if (!m_handle || !m_handle->client())
241         return nil;
242
243     return m_handle->client()->willCacheResponse(m_handle, cachedResponse);
244 }
245
246 @end
247
248 #endif // !USE(CFURLCONNECTION)
249