2 * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
3 * Copyright (C) 2013, Intel Corporation
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following disclaimer
13 * in the documentation and/or other materials provided with the
15 * * Neither the name of Google Inc. nor the names of its
16 * contributors may be used to endorse or promote products derived from
17 * this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "core/loader/DocumentThreadableLoader.h"
35 #include "core/dom/Document.h"
36 #include "core/fetch/CrossOriginAccessControl.h"
37 #include "core/fetch/FetchRequest.h"
38 #include "core/fetch/Resource.h"
39 #include "core/fetch/ResourceFetcher.h"
40 #include "core/frame/ContentSecurityPolicy.h"
41 #include "core/frame/Frame.h"
42 #include "core/inspector/InspectorInstrumentation.h"
43 #include "core/loader/CrossOriginPreflightResultCache.h"
44 #include "core/loader/DocumentThreadableLoaderClient.h"
45 #include "core/loader/FrameLoader.h"
46 #include "core/loader/ThreadableLoaderClient.h"
47 #include "platform/SharedBuffer.h"
48 #include "platform/network/ResourceRequest.h"
49 #include "platform/weborigin/SchemeRegistry.h"
50 #include "platform/weborigin/SecurityOrigin.h"
51 #include "wtf/Assertions.h"
55 void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
57 // The loader will be deleted as soon as this function exits.
58 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, &client, LoadSynchronously, request, options));
59 ASSERT(loader->hasOneRef());
62 PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
64 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
65 if (!loader->resource())
67 return loader.release();
70 DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options)
72 , m_document(document)
74 , m_sameOriginRequest(securityOrigin()->canRequest(request.url()))
75 , m_simpleRequest(true)
76 , m_async(blockingBehavior == LoadAsynchronously)
77 , m_timeoutTimer(this, &DocumentThreadableLoader::didTimeout)
81 // Setting an outgoing referer is only supported in the async code path.
82 ASSERT(m_async || request.httpReferrer().isEmpty());
84 if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
89 if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
90 m_client->didFail(ResourceError(errorDomainBlinkInternal, 0, request.url().string(), "Cross origin requests are not supported."));
94 makeCrossOriginAccessRequest(request);
97 void DocumentThreadableLoader::makeCrossOriginAccessRequest(const ResourceRequest& request)
99 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
101 OwnPtr<ResourceRequest> crossOriginRequest = adoptPtr(new ResourceRequest(request));
103 if ((m_options.preflightPolicy == ConsiderPreflight && isSimpleCrossOriginAccessRequest(crossOriginRequest->httpMethod(), crossOriginRequest->httpHeaderFields())) || m_options.preflightPolicy == PreventPreflight) {
104 updateRequestForAccessControl(*crossOriginRequest, securityOrigin(), m_options.allowCredentials);
105 makeSimpleCrossOriginAccessRequest(*crossOriginRequest);
107 m_simpleRequest = false;
108 // Do not set the Origin header for preflight requests.
109 updateRequestForAccessControl(*crossOriginRequest, 0, m_options.allowCredentials);
110 m_actualRequest = crossOriginRequest.release();
112 if (CrossOriginPreflightResultCache::shared().canSkipPreflight(securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials, m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
115 makeCrossOriginAccessRequestWithPreflight(*m_actualRequest);
119 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const ResourceRequest& request)
121 ASSERT(m_options.preflightPolicy != ForcePreflight);
122 ASSERT(m_options.preflightPolicy == PreventPreflight || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
124 // Cross-origin requests are only allowed for HTTP and registered schemes. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
125 if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol())) {
126 m_client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal, 0, request.url().string(), "Cross origin requests are only supported for HTTP."));
130 loadRequest(request);
133 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
135 ResourceRequest preflightRequest = createAccessControlPreflightRequest(request, securityOrigin());
136 loadRequest(preflightRequest);
139 DocumentThreadableLoader::~DocumentThreadableLoader()
143 void DocumentThreadableLoader::cancel()
145 cancelWithError(ResourceError());
148 void DocumentThreadableLoader::cancelWithError(const ResourceError& error)
150 RefPtr<DocumentThreadableLoader> protect(this);
152 // Cancel can re-enter and m_resource might be null here as a result.
153 if (m_client && resource()) {
154 ResourceError errorForCallback = error;
155 if (errorForCallback.isNull()) {
156 // FIXME: This error is sent to the client in didFail(), so it should not be an internal one. Use FrameLoaderClient::cancelledError() instead.
157 errorForCallback = ResourceError(errorDomainBlinkInternal, 0, resource()->url().string(), "Load cancelled");
158 errorForCallback.setIsCancellation(true);
160 m_client->didFail(errorForCallback);
166 void DocumentThreadableLoader::setDefersLoading(bool value)
169 resource()->setDefersLoading(value);
172 void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
175 ASSERT_UNUSED(resource, resource == this->resource());
177 RefPtr<DocumentThreadableLoader> protect(this);
178 if (!isAllowedByPolicy(request.url())) {
179 m_client->didFailRedirectCheck();
180 request = ResourceRequest();
184 // Allow same origin requests to continue after allowing clients to audit the redirect.
185 if (isAllowedRedirect(request.url())) {
186 if (m_client->isDocumentThreadableLoaderClient())
187 static_cast<DocumentThreadableLoaderClient*>(m_client)->willSendRequest(request, redirectResponse);
191 // When using access control, only simple cross origin requests are allowed to redirect. The new request URL must have a supported
192 // scheme and not contain the userinfo production. In addition, the redirect response must pass the access control check if the
193 // original request was not same-origin.
194 if (m_options.crossOriginRequestPolicy == UseAccessControl) {
196 InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document->frame(), resource->identifier(), m_document->frame()->loader().documentLoader(), redirectResponse, 0);
198 bool allowRedirect = false;
199 String accessControlErrorDescription;
201 if (m_simpleRequest) {
202 allowRedirect = CrossOriginAccessControl::isLegalRedirectLocation(request.url(), accessControlErrorDescription)
203 && (m_sameOriginRequest || passesAccessControlCheck(redirectResponse, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription));
205 accessControlErrorDescription = "The request was redirected to '"+ request.url().string() + "', which is disallowed for cross-origin requests that require preflight.";
209 // FIXME: consider combining this with CORS redirect handling performed by
210 // CrossOriginAccessControl::handleRedirect().
213 RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::create(redirectResponse.url());
214 RefPtr<SecurityOrigin> requestOrigin = SecurityOrigin::create(request.url());
215 // If the original request wasn't same-origin, then if the request URL origin is not same origin with the original URL origin,
216 // set the source origin to a globally unique identifier. (If the original request was same-origin, the origin of the new request
217 // should be the original URL origin.)
218 if (!m_sameOriginRequest && !originalOrigin->isSameSchemeHostPort(requestOrigin.get()))
219 m_options.securityOrigin = SecurityOrigin::createUnique();
220 // Force any subsequent requests to use these checks.
221 m_sameOriginRequest = false;
223 // Since the request is no longer same-origin, if the user didn't request credentials in
224 // the first place, update our state so we neither request them nor expect they must be allowed.
225 if (m_options.credentialsRequested == ClientDidNotRequestCredentials)
226 m_options.allowCredentials = DoNotAllowStoredCredentials;
228 // Remove any headers that may have been added by the network layer that cause access control to fail.
229 request.clearHTTPContentType();
230 request.clearHTTPReferrer();
231 request.clearHTTPOrigin();
232 request.clearHTTPUserAgent();
233 request.clearHTTPAccept();
234 makeCrossOriginAccessRequest(request);
238 ResourceError error(errorDomainBlinkInternal, 0, redirectResponse.url().string(), accessControlErrorDescription);
239 m_client->didFailAccessControlCheck(error);
241 m_client->didFailRedirectCheck();
243 request = ResourceRequest();
246 void DocumentThreadableLoader::dataSent(Resource* resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
249 ASSERT_UNUSED(resource, resource == this->resource());
250 m_client->didSendData(bytesSent, totalBytesToBeSent);
253 void DocumentThreadableLoader::dataDownloaded(Resource* resource, int dataLength)
256 ASSERT_UNUSED(resource, resource == this->resource());
257 ASSERT(!m_actualRequest);
259 m_client->didDownloadData(dataLength);
262 void DocumentThreadableLoader::responseReceived(Resource* resource, const ResourceResponse& response)
264 ASSERT_UNUSED(resource, resource == this->resource());
265 didReceiveResponse(resource->identifier(), response);
268 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
272 String accessControlErrorDescription;
273 if (m_actualRequest) {
274 // Notifying the inspector here is necessary because a call to preflightFailure() might synchronously
275 // cause the underlying ResourceLoader to be cancelled before it tells the inspector about the response.
276 // In that case, if we don't tell the inspector about the response now, the resource type in the inspector
277 // will default to "other" instead of something more descriptive.
278 DocumentLoader* loader = m_document->frame()->loader().documentLoader();
279 InspectorInstrumentation::didReceiveResourceResponse(m_document->frame(), identifier, loader, response, resource() ? resource()->loader() : 0);
281 if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
282 preflightFailure(response.url().string(), accessControlErrorDescription);
286 if (!passesPreflightStatusCheck(response, accessControlErrorDescription)) {
287 preflightFailure(response.url().string(), accessControlErrorDescription);
291 OwnPtr<CrossOriginPreflightResultCacheItem> preflightResult = adoptPtr(new CrossOriginPreflightResultCacheItem(m_options.allowCredentials));
292 if (!preflightResult->parse(response, accessControlErrorDescription)
293 || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod(), accessControlErrorDescription)
294 || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeaderFields(), accessControlErrorDescription)) {
295 preflightFailure(response.url().string(), accessControlErrorDescription);
299 CrossOriginPreflightResultCache::shared().appendEntry(securityOrigin()->toString(), m_actualRequest->url(), preflightResult.release());
301 if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessControl) {
302 if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
303 m_client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal, 0, response.url().string(), accessControlErrorDescription));
308 m_client->didReceiveResponse(identifier, response);
312 void DocumentThreadableLoader::dataReceived(Resource* resource, const char* data, int dataLength)
314 ASSERT_UNUSED(resource, resource == this->resource());
315 didReceiveData(data, dataLength);
318 void DocumentThreadableLoader::didReceiveData(const char* data, int dataLength)
321 // Preflight data should be invisible to clients.
322 if (!m_actualRequest)
323 m_client->didReceiveData(data, dataLength);
326 void DocumentThreadableLoader::notifyFinished(Resource* resource)
329 ASSERT(resource == this->resource());
331 m_timeoutTimer.stop();
333 if (resource->errorOccurred())
334 m_client->didFail(resource->resourceError());
336 didFinishLoading(resource->identifier(), resource->loadFinishTime());
339 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
341 if (m_actualRequest) {
342 ASSERT(!m_sameOriginRequest);
343 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
346 m_client->didFinishLoading(identifier, finishTime);
349 void DocumentThreadableLoader::didTimeout(Timer<DocumentThreadableLoader>* timer)
351 ASSERT_UNUSED(timer, timer == &m_timeoutTimer);
353 // Using values from net/base/net_error_list.h ERR_TIMED_OUT,
354 // Same as existing FIXME above - this error should be coming from FrameLoaderClient to be identifiable.
355 static const int timeoutError = -7;
356 ResourceError error("net", timeoutError, resource()->url(), String());
357 error.setIsTimeout(true);
358 cancelWithError(error);
361 void DocumentThreadableLoader::preflightSuccess()
363 OwnPtr<ResourceRequest> actualRequest;
364 actualRequest.swap(m_actualRequest);
366 actualRequest->setHTTPOrigin(securityOrigin()->toAtomicString());
370 loadRequest(*actualRequest);
373 void DocumentThreadableLoader::preflightFailure(const String& url, const String& errorDescription)
375 ResourceError error(errorDomainBlinkInternal, 0, url, errorDescription);
376 m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
377 m_client->didFailAccessControlCheck(error);
380 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request)
382 // Any credential should have been removed from the cross-site requests.
383 const KURL& requestURL = request.url();
384 ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
385 ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
387 ThreadableLoaderOptions options = m_options;
389 if (m_actualRequest) {
390 options.sniffContent = DoNotSniffContent;
391 options.dataBufferingPolicy = BufferData;
394 if (m_options.timeoutMilliseconds > 0)
395 m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0);
397 FetchRequest newRequest(request, m_options.initiator, options);
399 setResource(m_document->fetcher()->fetchRawResource(newRequest));
400 if (resource() && resource()->loader()) {
401 unsigned long identifier = resource()->identifier();
402 InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
407 FetchRequest fetchRequest(request, m_options.initiator, options);
408 ResourcePtr<Resource> resource = m_document->fetcher()->fetchSynchronously(fetchRequest);
409 ResourceResponse response = resource ? resource->response() : ResourceResponse();
410 unsigned long identifier = resource ? resource->identifier() : std::numeric_limits<unsigned long>::max();
411 ResourceError error = resource ? resource->resourceError() : ResourceError();
413 InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
416 m_client->didFail(error);
420 // No exception for file:/// resources, see <rdar://problem/4962298>.
421 // Also, if we have an HTTP response, then it wasn't a network error in fact.
422 if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
423 m_client->didFail(error);
427 // FIXME: A synchronous request does not tell us whether a redirect happened or not, so we guess by comparing the
428 // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
429 // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
430 if (requestURL != response.url() && (!isAllowedByPolicy(response.url()) || !isAllowedRedirect(response.url()))) {
431 m_client->didFailRedirectCheck();
435 didReceiveResponse(identifier, response);
437 SharedBuffer* data = resource->resourceBuffer();
439 didReceiveData(data->data(), data->size());
441 didFinishLoading(identifier, 0.0);
444 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url) const
446 if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
449 return m_sameOriginRequest && securityOrigin()->canRequest(url);
452 bool DocumentThreadableLoader::isAllowedByPolicy(const KURL& url) const
454 if (m_options.contentSecurityPolicyEnforcement != EnforceConnectSrcDirective)
456 return m_document->contentSecurityPolicy()->allowConnectToSource(url);
459 SecurityOrigin* DocumentThreadableLoader::securityOrigin() const
461 return m_options.securityOrigin ? m_options.securityOrigin.get() : m_document->securityOrigin();
464 } // namespace WebCore