initial import
[vuplus_webkit] / Source / WebCore / loader / DocumentThreadableLoader.cpp
1 /*
2  * Copyright (C) 2011 Google 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 are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "DocumentThreadableLoader.h"
33
34 #include "AuthenticationChallenge.h"
35 #include "CrossOriginAccessControl.h"
36 #include "CrossOriginPreflightResultCache.h"
37 #include "Document.h"
38 #include "DocumentThreadableLoaderClient.h"
39 #include "Frame.h"
40 #include "FrameLoader.h"
41 #include "ResourceHandle.h"
42 #include "ResourceLoadScheduler.h"
43 #include "ResourceRequest.h"
44 #include "SecurityOrigin.h"
45 #include "SubresourceLoader.h"
46 #include "ThreadableLoaderClient.h"
47 #include <wtf/UnusedParam.h>
48
49 #if ENABLE(INSPECTOR)
50 #include "InspectorInstrumentation.h"
51 #include "ProgressTracker.h"
52 #endif
53
54 namespace WebCore {
55
56 void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
57 {
58     // The loader will be deleted as soon as this function exits.
59     RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, &client, LoadSynchronously, request, options));
60     ASSERT(loader->hasOneRef());
61 }
62
63 PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
64 {
65     RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
66     if (!loader->m_loader)
67         loader = 0;
68     return loader.release();
69 }
70
71 DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options)
72     : m_client(client)
73     , m_document(document)
74     , m_options(options)
75     , m_sameOriginRequest(securityOrigin()->canRequest(request.url()))
76     , m_async(blockingBehavior == LoadAsynchronously)
77 #if ENABLE(INSPECTOR)
78     , m_preflightRequestIdentifier(0)
79 #endif
80 {
81     ASSERT(document);
82     ASSERT(client);
83     // Setting an outgoing referer is only supported in the async code path.
84     ASSERT(m_async || request.httpReferrer().isEmpty());
85
86     if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
87         loadRequest(request, DoSecurityCheck);
88         return;
89     }
90
91     if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
92         m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are not supported."));
93         return;
94     }
95     
96     ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
97
98     OwnPtr<ResourceRequest> crossOriginRequest = adoptPtr(new ResourceRequest(request));
99     updateRequestForAccessControl(*crossOriginRequest, securityOrigin(), m_options.allowCredentials);
100
101     if ((m_options.preflightPolicy == ConsiderPreflight && isSimpleCrossOriginAccessRequest(crossOriginRequest->httpMethod(), crossOriginRequest->httpHeaderFields())) || m_options.preflightPolicy == PreventPreflight)
102         makeSimpleCrossOriginAccessRequest(*crossOriginRequest);
103     else {
104         m_actualRequest = crossOriginRequest.release();
105
106         if (CrossOriginPreflightResultCache::shared().canSkipPreflight(securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials, m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
107             preflightSuccess();
108         else
109             makeCrossOriginAccessRequestWithPreflight(*m_actualRequest);
110     }
111 }
112
113 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const ResourceRequest& request)
114 {
115     ASSERT(m_options.preflightPolicy != ForcePreflight);
116     ASSERT(m_options.preflightPolicy == PreventPreflight || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
117
118     // Cross-origin requests are only defined for HTTP. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
119     // FIXME: Consider allowing simple CORS requests to non-HTTP URLs.
120     if (!request.url().protocolInHTTPFamily()) {
121         m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are only supported for HTTP."));
122         return;
123     }
124
125     loadRequest(request, DoSecurityCheck);
126 }
127
128 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
129 {
130     ResourceRequest preflightRequest = createAccessControlPreflightRequest(request, securityOrigin(), m_options.allowCredentials);
131     loadRequest(preflightRequest, DoSecurityCheck);
132 }
133
134 DocumentThreadableLoader::~DocumentThreadableLoader()
135 {
136     if (m_loader)
137         m_loader->clearClient();
138 }
139
140 void DocumentThreadableLoader::cancel()
141 {
142     if (!m_loader)
143         return;
144
145     m_loader->cancel();
146     m_loader->clearClient();
147     m_loader = 0;
148     m_client = 0;
149 }
150
151 void DocumentThreadableLoader::setDefersLoading(bool value)
152 {
153     if (m_loader)
154         m_loader->setDefersLoading(value);
155 }
156
157 void DocumentThreadableLoader::willSendRequest(SubresourceLoader* loader, ResourceRequest& request, const ResourceResponse& redirectResponse)
158 {
159     ASSERT(m_client);
160     ASSERT_UNUSED(loader, loader == m_loader);
161
162     if (!isAllowedRedirect(request.url())) {
163         RefPtr<DocumentThreadableLoader> protect(this);
164         m_client->didFailRedirectCheck();
165         request = ResourceRequest();
166     } else {
167         if (m_client->isDocumentThreadableLoaderClient())
168             static_cast<DocumentThreadableLoaderClient*>(m_client)->willSendRequest(request, redirectResponse);
169     }
170 }
171
172 void DocumentThreadableLoader::didSendData(SubresourceLoader* loader, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
173 {
174     ASSERT(m_client);
175     ASSERT_UNUSED(loader, loader == m_loader);
176
177     m_client->didSendData(bytesSent, totalBytesToBeSent);
178 }
179
180 void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader* loader, const ResourceResponse& response)
181 {
182     ASSERT(loader == m_loader);
183     didReceiveResponse(loader->identifier(), response);
184 }
185
186 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
187 {
188     ASSERT(m_client);
189
190 #if ENABLE(INSPECTOR)
191     if (m_preflightRequestIdentifier) {
192         DocumentLoader* loader = m_document->frame()->loader()->documentLoader();
193         InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_document->frame(), m_preflightRequestIdentifier, response);
194         InspectorInstrumentation::didReceiveResourceResponse(cookie, m_preflightRequestIdentifier, loader, response);
195     }
196 #endif
197
198     String accessControlErrorDescription;
199     if (m_actualRequest) {
200         if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
201             preflightFailure(response.url(), accessControlErrorDescription);
202             return;
203         }
204
205         OwnPtr<CrossOriginPreflightResultCacheItem> preflightResult = adoptPtr(new CrossOriginPreflightResultCacheItem(m_options.allowCredentials));
206         if (!preflightResult->parse(response, accessControlErrorDescription)
207             || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod(), accessControlErrorDescription)
208             || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeaderFields(), accessControlErrorDescription)) {
209             preflightFailure(response.url(), accessControlErrorDescription);
210             return;
211         }
212
213         CrossOriginPreflightResultCache::shared().appendEntry(securityOrigin()->toString(), m_actualRequest->url(), preflightResult.release());
214     } else {
215         if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessControl) {
216             if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
217                 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, response.url().string(), accessControlErrorDescription));
218                 return;
219             }
220         }
221
222         m_client->didReceiveResponse(identifier, response);
223     }
224 }
225
226 void DocumentThreadableLoader::didReceiveData(SubresourceLoader* loader, const char* data, int dataLength)
227 {
228     ASSERT(m_client);
229     ASSERT_UNUSED(loader, loader == m_loader);
230
231 #if ENABLE(INSPECTOR)
232     if (m_preflightRequestIdentifier)
233         InspectorInstrumentation::didReceiveData(m_document->frame(), m_preflightRequestIdentifier, 0, 0, dataLength);
234 #endif
235
236     // Preflight data should be invisible to clients.
237     if (m_actualRequest)
238         return;
239
240     m_client->didReceiveData(data, dataLength);
241 }
242
243 void DocumentThreadableLoader::didReceiveCachedMetadata(SubresourceLoader* loader, const char* data, int dataLength)
244 {
245     ASSERT(m_client);
246     ASSERT_UNUSED(loader, loader == m_loader);
247
248     // Preflight data should be invisible to clients.
249     if (m_actualRequest)
250         return;
251
252     m_client->didReceiveCachedMetadata(data, dataLength);
253 }
254
255 void DocumentThreadableLoader::didFinishLoading(SubresourceLoader* loader, double finishTime)
256 {
257     ASSERT(loader == m_loader);
258     ASSERT(m_client);
259     didFinishLoading(loader->identifier(), finishTime);
260 }
261
262 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
263 {
264 #if ENABLE(INSPECTOR)
265     if (m_preflightRequestIdentifier)
266         InspectorInstrumentation::didFinishLoading(m_document->frame(), m_document->frame()->loader()->documentLoader(), m_preflightRequestIdentifier, finishTime);
267 #endif
268
269     if (m_actualRequest) {
270         ASSERT(!m_sameOriginRequest);
271         ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
272         preflightSuccess();
273     } else
274         m_client->didFinishLoading(identifier, finishTime);
275 }
276
277 void DocumentThreadableLoader::didFail(SubresourceLoader* loader, const ResourceError& error)
278 {
279     ASSERT(m_client);
280     // m_loader may be null if we arrive here via SubresourceLoader::create in the ctor
281     ASSERT_UNUSED(loader, loader == m_loader || !m_loader);
282
283 #if ENABLE(INSPECTOR)
284     if (m_preflightRequestIdentifier)
285         InspectorInstrumentation::didFailLoading(m_document->frame(), m_document->frame()->loader()->documentLoader(), m_preflightRequestIdentifier, error);
286 #endif
287
288     m_client->didFail(error);
289 }
290
291 void DocumentThreadableLoader::didReceiveAuthenticationChallenge(SubresourceLoader* loader, const AuthenticationChallenge& challenge)
292 {
293     ASSERT(loader == m_loader);
294     // Users are not prompted for credentials for cross-origin requests.
295     if (!m_sameOriginRequest) {
296 #if PLATFORM(MAC) || USE(CFNETWORK) || USE(CURL)
297         loader->handle()->receivedRequestToContinueWithoutCredential(challenge);
298 #else
299         // These platforms don't provide a way to continue without credentials, cancel the load altogether.
300         UNUSED_PARAM(challenge);
301         RefPtr<DocumentThreadableLoader> protect(this);
302         m_client->didFail(loader->blockedError());
303         cancel();
304 #endif
305     }
306 }
307
308 void DocumentThreadableLoader::preflightSuccess()
309 {
310     OwnPtr<ResourceRequest> actualRequest;
311     actualRequest.swap(m_actualRequest);
312
313     actualRequest->setHTTPOrigin(securityOrigin()->toString());
314
315     // It should be ok to skip the security check since we already asked about the preflight request.
316     loadRequest(*actualRequest, SkipSecurityCheck);
317 }
318
319 void DocumentThreadableLoader::preflightFailure(const String& url, const String& errorDescription)
320 {
321     m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
322     m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, url, errorDescription));
323 }
324
325 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, SecurityCheckPolicy securityCheck)
326 {
327     // Any credential should have been removed from the cross-site requests.
328     const KURL& requestURL = request.url();
329     ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
330     ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
331
332     if (m_async) {
333         ThreadableLoaderOptions options = m_options;
334         if (m_actualRequest) {
335             // Don't sniff content or send load callbacks for the preflight request.
336             options.sendLoadCallbacks = DoNotSendCallbacks;
337             options.sniffContent = DoNotSniffContent;
338             // Keep buffering the data for the preflight request.
339             options.shouldBufferData = BufferData;
340         }
341
342 #if ENABLE(INSPECTOR)
343         if (m_actualRequest) {
344             ResourceRequest newRequest(request);
345             // Because willSendRequest only gets called during redirects, we initialize the identifier and the first willSendRequest here.
346             m_preflightRequestIdentifier = m_document->frame()->page()->progress()->createUniqueIdentifier();
347             ResourceResponse redirectResponse = ResourceResponse();
348             InspectorInstrumentation::willSendRequest(m_document->frame(), m_preflightRequestIdentifier, m_document->frame()->loader()->documentLoader(), newRequest, redirectResponse);
349         }
350 #endif
351
352         // Clear the loader so that any callbacks from SubresourceLoader::create will not have the old loader.
353         m_loader = 0;
354         m_loader = resourceLoadScheduler()->scheduleSubresourceLoad(m_document->frame(), this, request, ResourceLoadPriorityMedium, securityCheck, options);
355         return;
356     }
357     
358     // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
359     Vector<char> data;
360     ResourceError error;
361     ResourceResponse response;
362     unsigned long identifier = std::numeric_limits<unsigned long>::max();
363     if (m_document->frame())
364         identifier = m_document->frame()->loader()->loadResourceSynchronously(request, m_options.allowCredentials, error, response, data);
365
366     // No exception for file:/// resources, see <rdar://problem/4962298>.
367     // Also, if we have an HTTP response, then it wasn't a network error in fact.
368     if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
369         m_client->didFail(error);
370         return;
371     }
372
373     // FIXME: FrameLoader::loadSynchronously() does not tell us whether a redirect happened or not, so we guess by comparing the
374     // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
375     // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
376     if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
377         m_client->didFailRedirectCheck();
378         return;
379     }
380
381     didReceiveResponse(identifier, response);
382
383     const char* bytes = static_cast<const char*>(data.data());
384     int len = static_cast<int>(data.size());
385     didReceiveData(0, bytes, len);
386
387     didFinishLoading(identifier, 0.0);
388 }
389
390 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url)
391 {
392     if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
393         return true;
394
395     // FIXME: We need to implement access control for each redirect. This will require some refactoring though, because the code
396     // that processes redirects doesn't know about access control and expects a synchronous answer from its client about whether
397     // a redirect should proceed.
398     return m_sameOriginRequest && securityOrigin()->canRequest(url);
399 }
400
401 SecurityOrigin* DocumentThreadableLoader::securityOrigin() const
402 {
403     return m_options.securityOrigin ? m_options.securityOrigin.get() : m_document->securityOrigin();
404 }
405
406 } // namespace WebCore