2 * Copyright (C) 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "DocumentThreadableLoader.h"
34 #include "AuthenticationChallenge.h"
35 #include "CrossOriginAccessControl.h"
36 #include "CrossOriginPreflightResultCache.h"
38 #include "DocumentThreadableLoaderClient.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>
50 #include "InspectorInstrumentation.h"
51 #include "ProgressTracker.h"
56 void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
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());
63 PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
65 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
66 if (!loader->m_loader)
68 return loader.release();
71 DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options)
73 , m_document(document)
75 , m_sameOriginRequest(securityOrigin()->canRequest(request.url()))
76 , m_async(blockingBehavior == LoadAsynchronously)
78 , m_preflightRequestIdentifier(0)
83 // Setting an outgoing referer is only supported in the async code path.
84 ASSERT(m_async || request.httpReferrer().isEmpty());
86 if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
87 loadRequest(request, DoSecurityCheck);
91 if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
92 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are not supported."));
96 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
98 OwnPtr<ResourceRequest> crossOriginRequest = adoptPtr(new ResourceRequest(request));
99 updateRequestForAccessControl(*crossOriginRequest, securityOrigin(), m_options.allowCredentials);
101 if ((m_options.preflightPolicy == ConsiderPreflight && isSimpleCrossOriginAccessRequest(crossOriginRequest->httpMethod(), crossOriginRequest->httpHeaderFields())) || m_options.preflightPolicy == PreventPreflight)
102 makeSimpleCrossOriginAccessRequest(*crossOriginRequest);
104 m_actualRequest = crossOriginRequest.release();
106 if (CrossOriginPreflightResultCache::shared().canSkipPreflight(securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials, m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
109 makeCrossOriginAccessRequestWithPreflight(*m_actualRequest);
113 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const ResourceRequest& request)
115 ASSERT(m_options.preflightPolicy != ForcePreflight);
116 ASSERT(m_options.preflightPolicy == PreventPreflight || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
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."));
125 loadRequest(request, DoSecurityCheck);
128 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
130 ResourceRequest preflightRequest = createAccessControlPreflightRequest(request, securityOrigin(), m_options.allowCredentials);
131 loadRequest(preflightRequest, DoSecurityCheck);
134 DocumentThreadableLoader::~DocumentThreadableLoader()
137 m_loader->clearClient();
140 void DocumentThreadableLoader::cancel()
146 m_loader->clearClient();
151 void DocumentThreadableLoader::setDefersLoading(bool value)
154 m_loader->setDefersLoading(value);
157 void DocumentThreadableLoader::willSendRequest(SubresourceLoader* loader, ResourceRequest& request, const ResourceResponse& redirectResponse)
160 ASSERT_UNUSED(loader, loader == m_loader);
162 if (!isAllowedRedirect(request.url())) {
163 RefPtr<DocumentThreadableLoader> protect(this);
164 m_client->didFailRedirectCheck();
165 request = ResourceRequest();
167 if (m_client->isDocumentThreadableLoaderClient())
168 static_cast<DocumentThreadableLoaderClient*>(m_client)->willSendRequest(request, redirectResponse);
172 void DocumentThreadableLoader::didSendData(SubresourceLoader* loader, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
175 ASSERT_UNUSED(loader, loader == m_loader);
177 m_client->didSendData(bytesSent, totalBytesToBeSent);
180 void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader* loader, const ResourceResponse& response)
182 ASSERT(loader == m_loader);
183 didReceiveResponse(loader->identifier(), response);
186 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
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);
198 String accessControlErrorDescription;
199 if (m_actualRequest) {
200 if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
201 preflightFailure(response.url(), accessControlErrorDescription);
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);
213 CrossOriginPreflightResultCache::shared().appendEntry(securityOrigin()->toString(), m_actualRequest->url(), preflightResult.release());
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));
222 m_client->didReceiveResponse(identifier, response);
226 void DocumentThreadableLoader::didReceiveData(SubresourceLoader* loader, const char* data, int dataLength)
229 ASSERT_UNUSED(loader, loader == m_loader);
231 #if ENABLE(INSPECTOR)
232 if (m_preflightRequestIdentifier)
233 InspectorInstrumentation::didReceiveData(m_document->frame(), m_preflightRequestIdentifier, 0, 0, dataLength);
236 // Preflight data should be invisible to clients.
240 m_client->didReceiveData(data, dataLength);
243 void DocumentThreadableLoader::didReceiveCachedMetadata(SubresourceLoader* loader, const char* data, int dataLength)
246 ASSERT_UNUSED(loader, loader == m_loader);
248 // Preflight data should be invisible to clients.
252 m_client->didReceiveCachedMetadata(data, dataLength);
255 void DocumentThreadableLoader::didFinishLoading(SubresourceLoader* loader, double finishTime)
257 ASSERT(loader == m_loader);
259 didFinishLoading(loader->identifier(), finishTime);
262 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
264 #if ENABLE(INSPECTOR)
265 if (m_preflightRequestIdentifier)
266 InspectorInstrumentation::didFinishLoading(m_document->frame(), m_document->frame()->loader()->documentLoader(), m_preflightRequestIdentifier, finishTime);
269 if (m_actualRequest) {
270 ASSERT(!m_sameOriginRequest);
271 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
274 m_client->didFinishLoading(identifier, finishTime);
277 void DocumentThreadableLoader::didFail(SubresourceLoader* loader, const ResourceError& error)
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);
283 #if ENABLE(INSPECTOR)
284 if (m_preflightRequestIdentifier)
285 InspectorInstrumentation::didFailLoading(m_document->frame(), m_document->frame()->loader()->documentLoader(), m_preflightRequestIdentifier, error);
288 m_client->didFail(error);
291 void DocumentThreadableLoader::didReceiveAuthenticationChallenge(SubresourceLoader* loader, const AuthenticationChallenge& challenge)
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);
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());
308 void DocumentThreadableLoader::preflightSuccess()
310 OwnPtr<ResourceRequest> actualRequest;
311 actualRequest.swap(m_actualRequest);
313 actualRequest->setHTTPOrigin(securityOrigin()->toString());
315 // It should be ok to skip the security check since we already asked about the preflight request.
316 loadRequest(*actualRequest, SkipSecurityCheck);
319 void DocumentThreadableLoader::preflightFailure(const String& url, const String& errorDescription)
321 m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
322 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, url, errorDescription));
325 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, SecurityCheckPolicy securityCheck)
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());
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;
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);
352 // Clear the loader so that any callbacks from SubresourceLoader::create will not have the old loader.
354 m_loader = resourceLoadScheduler()->scheduleSubresourceLoad(m_document->frame(), this, request, ResourceLoadPriorityMedium, securityCheck, options);
358 // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
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);
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);
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();
381 didReceiveResponse(identifier, response);
383 const char* bytes = static_cast<const char*>(data.data());
384 int len = static_cast<int>(data.size());
385 didReceiveData(0, bytes, len);
387 didFinishLoading(identifier, 0.0);
390 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url)
392 if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
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);
401 SecurityOrigin* DocumentThreadableLoader::securityOrigin() const
403 return m_options.securityOrigin ? m_options.securityOrigin.get() : m_document->securityOrigin();
406 } // namespace WebCore