2 * Copyright (C) 2011, 2012 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 "CachedRawResource.h"
35 #include "CachedResourceLoader.h"
36 #include "CachedResourceRequest.h"
37 #include "CrossOriginAccessControl.h"
38 #include "CrossOriginPreflightResultCache.h"
40 #include "DocumentThreadableLoaderClient.h"
42 #include "FrameLoader.h"
43 #include "InspectorInstrumentation.h"
44 #include "ResourceError.h"
45 #include "ResourceRequest.h"
46 #include "SchemeRegistry.h"
47 #include "SecurityOrigin.h"
48 #include "SubresourceLoader.h"
49 #include "ThreadableLoaderClient.h"
50 #include <wtf/Assertions.h>
51 #include <wtf/UnusedParam.h>
54 #include "ProgressTracker.h"
59 void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
61 // The loader will be deleted as soon as this function exits.
62 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, &client, LoadSynchronously, request, options));
63 ASSERT(loader->hasOneRef());
66 PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
68 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
69 if (!loader->m_resource)
71 return loader.release();
74 DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options)
76 , m_document(document)
78 , m_sameOriginRequest(securityOrigin()->canRequest(request.url()))
79 , m_simpleRequest(true)
80 , m_async(blockingBehavior == LoadAsynchronously)
84 // Setting an outgoing referer is only supported in the async code path.
85 ASSERT(m_async || request.httpReferrer().isEmpty());
87 if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
88 loadRequest(request, DoSecurityCheck);
92 if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
93 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are not supported."));
97 makeCrossOriginAccessRequest(request);
100 void DocumentThreadableLoader::makeCrossOriginAccessRequest(const ResourceRequest& request)
102 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
104 OwnPtr<ResourceRequest> crossOriginRequest = adoptPtr(new ResourceRequest(request));
105 updateRequestForAccessControl(*crossOriginRequest, securityOrigin(), m_options.allowCredentials);
107 if ((m_options.preflightPolicy == ConsiderPreflight && isSimpleCrossOriginAccessRequest(crossOriginRequest->httpMethod(), crossOriginRequest->httpHeaderFields())) || m_options.preflightPolicy == PreventPreflight)
108 makeSimpleCrossOriginAccessRequest(*crossOriginRequest);
110 m_simpleRequest = false;
111 m_actualRequest = crossOriginRequest.release();
113 if (CrossOriginPreflightResultCache::shared().canSkipPreflight(securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials, m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
116 makeCrossOriginAccessRequestWithPreflight(*m_actualRequest);
120 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const ResourceRequest& request)
122 ASSERT(m_options.preflightPolicy != ForcePreflight);
123 ASSERT(m_options.preflightPolicy == PreventPreflight || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
125 // 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.
126 if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol())) {
127 m_client->didFailAccessControlCheck(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are only supported for HTTP."));
131 loadRequest(request, DoSecurityCheck);
134 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
136 ResourceRequest preflightRequest = createAccessControlPreflightRequest(request, securityOrigin());
137 loadRequest(preflightRequest, DoSecurityCheck);
140 DocumentThreadableLoader::~DocumentThreadableLoader()
143 m_resource->removeClient(this);
146 void DocumentThreadableLoader::cancel()
148 RefPtr<DocumentThreadableLoader> protect(this);
150 // Cancel can re-enter and m_resource might be null here as a result.
151 if (m_client && m_resource) {
152 // FIXME: This error is sent to the client in didFail(), so it should not be an internal one. Use FrameLoaderClient::cancelledError() instead.
153 ResourceError error(errorDomainWebKitInternal, 0, m_resource->url(), "Load cancelled");
154 error.setIsCancellation(true);
155 didFail(m_resource->identifier(), error);
161 void DocumentThreadableLoader::setDefersLoading(bool value)
164 m_resource->setDefersLoading(value);
167 void DocumentThreadableLoader::clearResource()
169 // Script can cancel and restart a request reentrantly within removeClient(),
170 // which could lead to calling CachedResource::removeClient() multiple times for
171 // this DocumentThreadableLoader. Save off a copy of m_resource and clear it to
172 // prevent the reentrancy.
173 if (CachedResourceHandle<CachedRawResource> resource = m_resource) {
175 resource->removeClient(this);
179 void DocumentThreadableLoader::redirectReceived(CachedResource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
182 ASSERT_UNUSED(resource, resource == m_resource);
184 RefPtr<DocumentThreadableLoader> protect(this);
185 // Allow same origin requests to continue after allowing clients to audit the redirect.
186 if (isAllowedRedirect(request.url())) {
187 if (m_client->isDocumentThreadableLoaderClient())
188 static_cast<DocumentThreadableLoaderClient*>(m_client)->willSendRequest(request, redirectResponse);
192 // When using access control, only simple cross origin requests are allowed to redirect. The new request URL must have a supported
193 // scheme and not contain the userinfo production. In addition, the redirect response must pass the access control check.
194 if (m_options.crossOriginRequestPolicy == UseAccessControl) {
195 bool allowRedirect = false;
196 if (m_simpleRequest) {
197 String accessControlErrorDescription;
198 allowRedirect = SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol())
199 && request.url().user().isEmpty()
200 && request.url().pass().isEmpty()
201 && passesAccessControlCheck(redirectResponse, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription);
208 RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::createFromString(redirectResponse.url());
209 RefPtr<SecurityOrigin> requestOrigin = SecurityOrigin::createFromString(request.url());
210 // If the request URL origin is not same origin with the original URL origin, set source origin to a globally unique identifier.
211 if (!originalOrigin->isSameSchemeHostPort(requestOrigin.get()))
212 m_options.securityOrigin = SecurityOrigin::createUnique();
213 // Force any subsequent requests to use these checks.
214 m_sameOriginRequest = false;
216 // Remove any headers that may have been added by the network layer that cause access control to fail.
217 request.clearHTTPContentType();
218 request.clearHTTPReferrer();
219 request.clearHTTPOrigin();
220 request.clearHTTPUserAgent();
221 request.clearHTTPAccept();
222 makeCrossOriginAccessRequest(request);
227 m_client->didFailRedirectCheck();
228 request = ResourceRequest();
231 void DocumentThreadableLoader::dataSent(CachedResource* resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
234 ASSERT_UNUSED(resource, resource == m_resource);
235 m_client->didSendData(bytesSent, totalBytesToBeSent);
238 void DocumentThreadableLoader::responseReceived(CachedResource* resource, const ResourceResponse& response)
240 ASSERT_UNUSED(resource, resource == m_resource);
241 didReceiveResponse(m_resource->identifier(), response);
244 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
248 String accessControlErrorDescription;
249 if (m_actualRequest) {
250 #if ENABLE(INSPECTOR)
251 DocumentLoader* loader = m_document->frame()->loader()->documentLoader();
252 InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_document->frame(), identifier, response);
253 InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, loader, response, 0);
256 if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
257 preflightFailure(identifier, response.url(), accessControlErrorDescription);
261 OwnPtr<CrossOriginPreflightResultCacheItem> preflightResult = adoptPtr(new CrossOriginPreflightResultCacheItem(m_options.allowCredentials));
262 if (!preflightResult->parse(response, accessControlErrorDescription)
263 || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod(), accessControlErrorDescription)
264 || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeaderFields(), accessControlErrorDescription)) {
265 preflightFailure(identifier, response.url(), accessControlErrorDescription);
269 CrossOriginPreflightResultCache::shared().appendEntry(securityOrigin()->toString(), m_actualRequest->url(), preflightResult.release());
271 if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessControl) {
272 if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
273 m_client->didFailAccessControlCheck(ResourceError(errorDomainWebKitInternal, 0, response.url().string(), accessControlErrorDescription));
278 m_client->didReceiveResponse(identifier, response);
282 void DocumentThreadableLoader::dataReceived(CachedResource* resource, const char* data, int dataLength)
284 ASSERT_UNUSED(resource, resource == m_resource);
285 didReceiveData(m_resource->identifier(), data, dataLength);
288 void DocumentThreadableLoader::didReceiveData(unsigned long identifier, const char* data, int dataLength)
292 // Preflight data should be invisible to clients.
293 if (m_actualRequest) {
294 #if ENABLE(INSPECTOR)
295 InspectorInstrumentation::didReceiveData(m_document->frame(), identifier, 0, 0, dataLength);
300 m_client->didReceiveData(data, dataLength);
303 void DocumentThreadableLoader::notifyFinished(CachedResource* resource)
306 ASSERT_UNUSED(resource, resource == m_resource);
308 if (m_resource->errorOccurred())
309 didFail(m_resource->identifier(), m_resource->resourceError());
311 didFinishLoading(m_resource->identifier(), m_resource->loadFinishTime());
314 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
316 if (m_actualRequest) {
317 #if ENABLE(INSPECTOR)
318 InspectorInstrumentation::didFinishLoading(m_document->frame(), m_document->frame()->loader()->documentLoader(), identifier, finishTime);
320 ASSERT(!m_sameOriginRequest);
321 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
324 m_client->didFinishLoading(identifier, finishTime);
327 void DocumentThreadableLoader::didFail(unsigned long identifier, const ResourceError& error)
329 #if ENABLE(INSPECTOR)
331 InspectorInstrumentation::didFailLoading(m_document->frame(), m_document->frame()->loader()->documentLoader(), identifier, error);
334 m_client->didFail(error);
337 void DocumentThreadableLoader::preflightSuccess()
339 OwnPtr<ResourceRequest> actualRequest;
340 actualRequest.swap(m_actualRequest);
342 actualRequest->setHTTPOrigin(securityOrigin()->toString());
346 // It should be ok to skip the security check since we already asked about the preflight request.
347 loadRequest(*actualRequest, SkipSecurityCheck);
350 void DocumentThreadableLoader::preflightFailure(unsigned long identifier, const String& url, const String& errorDescription)
352 ResourceError error(errorDomainWebKitInternal, 0, url, errorDescription);
353 #if ENABLE(INSPECTOR)
355 InspectorInstrumentation::didFailLoading(m_document->frame(), m_document->frame()->loader()->documentLoader(), identifier, error);
357 m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
358 m_client->didFailAccessControlCheck(error);
361 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, SecurityCheckPolicy securityCheck)
363 // Any credential should have been removed from the cross-site requests.
364 const KURL& requestURL = request.url();
365 m_options.securityCheck = securityCheck;
366 ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
367 ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
370 ThreadableLoaderOptions options = m_options;
371 options.clientCredentialPolicy = DoNotAskClientForCrossOriginCredentials;
372 if (m_actualRequest) {
373 // Don't sniff content or send load callbacks for the preflight request.
374 options.sendLoadCallbacks = DoNotSendCallbacks;
375 options.sniffContent = DoNotSniffContent;
376 // Keep buffering the data for the preflight request.
377 options.dataBufferingPolicy = BufferData;
380 CachedResourceRequest newRequest(request, options);
381 #if ENABLE(RESOURCE_TIMING)
382 newRequest.setInitiator(m_options.initiator);
385 m_resource = m_document->cachedResourceLoader()->requestRawResource(newRequest);
387 #if ENABLE(INSPECTOR)
388 if (m_resource->loader()) {
389 unsigned long identifier = m_resource->loader()->identifier();
390 InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
393 m_resource->addClient(this);
398 // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
401 ResourceResponse response;
402 unsigned long identifier = std::numeric_limits<unsigned long>::max();
403 if (m_document->frame())
404 identifier = m_document->frame()->loader()->loadResourceSynchronously(request, m_options.allowCredentials, m_options.clientCredentialPolicy, error, response, data);
406 InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
408 // No exception for file:/// resources, see <rdar://problem/4962298>.
409 // Also, if we have an HTTP response, then it wasn't a network error in fact.
410 if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
411 m_client->didFail(error);
415 // FIXME: FrameLoader::loadSynchronously() does not tell us whether a redirect happened or not, so we guess by comparing the
416 // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
417 // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
418 if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
419 m_client->didFailRedirectCheck();
423 didReceiveResponse(identifier, response);
425 const char* bytes = static_cast<const char*>(data.data());
426 int len = static_cast<int>(data.size());
427 didReceiveData(identifier, bytes, len);
429 didFinishLoading(identifier, 0.0);
432 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url)
434 if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
437 return m_sameOriginRequest && securityOrigin()->canRequest(url);
440 SecurityOrigin* DocumentThreadableLoader::securityOrigin() const
442 return m_options.securityOrigin ? m_options.securityOrigin.get() : m_document->securityOrigin();
445 } // namespace WebCore