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>
51 void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
53 // The loader will be deleted as soon as this function exits.
54 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, &client, LoadSynchronously, request, options, String()));
55 ASSERT(loader->hasOneRef());
58 PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options, const String& optionalOutgoingReferrer)
60 RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options, optionalOutgoingReferrer));
61 if (!loader->m_loader)
63 return loader.release();
66 DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options, const String& optionalOutgoingReferrer)
68 , m_document(document)
70 , m_optionalOutgoingReferrer(optionalOutgoingReferrer)
71 , m_sameOriginRequest(document->securityOrigin()->canRequest(request.url()))
72 , m_async(blockingBehavior == LoadAsynchronously)
76 // Setting an outgoing referer is only supported in the async code path.
77 ASSERT(m_async || m_optionalOutgoingReferrer.isEmpty());
79 if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
80 loadRequest(request, DoSecurityCheck);
84 if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
85 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are not supported."));
89 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
91 OwnPtr<ResourceRequest> crossOriginRequest = adoptPtr(new ResourceRequest(request));
92 crossOriginRequest->removeCredentials();
93 crossOriginRequest->setAllowCookies(m_options.allowCredentials);
95 if (!m_options.forcePreflight && isSimpleCrossOriginAccessRequest(crossOriginRequest->httpMethod(), crossOriginRequest->httpHeaderFields()))
96 makeSimpleCrossOriginAccessRequest(*crossOriginRequest);
98 m_actualRequest = crossOriginRequest.release();
100 if (CrossOriginPreflightResultCache::shared().canSkipPreflight(document->securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials, m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
103 makeCrossOriginAccessRequestWithPreflight(*m_actualRequest);
107 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const ResourceRequest& request)
109 ASSERT(isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
111 // 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.
112 if (!request.url().protocolInHTTPFamily()) {
113 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are only supported for HTTP."));
117 // Make a copy of the passed request so that we can modify some details.
118 ResourceRequest crossOriginRequest(request);
119 crossOriginRequest.setHTTPOrigin(m_document->securityOrigin()->toString());
121 loadRequest(crossOriginRequest, DoSecurityCheck);
124 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
126 ResourceRequest preflightRequest(request.url());
127 preflightRequest.removeCredentials();
128 preflightRequest.setHTTPOrigin(m_document->securityOrigin()->toString());
129 preflightRequest.setAllowCookies(m_options.allowCredentials);
130 preflightRequest.setHTTPMethod("OPTIONS");
131 preflightRequest.setHTTPHeaderField("Access-Control-Request-Method", request.httpMethod());
133 const HTTPHeaderMap& requestHeaderFields = request.httpHeaderFields();
135 if (requestHeaderFields.size() > 0) {
136 Vector<UChar> headerBuffer;
137 HTTPHeaderMap::const_iterator it = requestHeaderFields.begin();
138 append(headerBuffer, it->first);
141 HTTPHeaderMap::const_iterator end = requestHeaderFields.end();
142 for (; it != end; ++it) {
143 headerBuffer.append(',');
144 headerBuffer.append(' ');
145 append(headerBuffer, it->first);
148 preflightRequest.setHTTPHeaderField("Access-Control-Request-Headers", String::adopt(headerBuffer));
151 preflightRequest.setPriority(request.priority());
153 loadRequest(preflightRequest, DoSecurityCheck);
156 DocumentThreadableLoader::~DocumentThreadableLoader()
159 m_loader->clearClient();
162 void DocumentThreadableLoader::cancel()
168 m_loader->clearClient();
173 void DocumentThreadableLoader::setDefersLoading(bool value)
176 m_loader->setDefersLoading(value);
179 void DocumentThreadableLoader::willSendRequest(SubresourceLoader* loader, ResourceRequest& request, const ResourceResponse& redirectResponse)
182 ASSERT_UNUSED(loader, loader == m_loader);
184 if (!isAllowedRedirect(request.url())) {
185 RefPtr<DocumentThreadableLoader> protect(this);
186 m_client->didFailRedirectCheck();
187 request = ResourceRequest();
189 if (m_client->isDocumentThreadableLoaderClient())
190 static_cast<DocumentThreadableLoaderClient*>(m_client)->willSendRequest(request, redirectResponse);
194 void DocumentThreadableLoader::didSendData(SubresourceLoader* loader, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
197 ASSERT_UNUSED(loader, loader == m_loader);
199 m_client->didSendData(bytesSent, totalBytesToBeSent);
202 void DocumentThreadableLoader::didReceiveResponse(SubresourceLoader* loader, const ResourceResponse& response)
205 ASSERT_UNUSED(loader, loader == m_loader);
207 String accessControlErrorDescription;
208 if (m_actualRequest) {
209 if (!passesAccessControlCheck(response, m_options.allowCredentials, m_document->securityOrigin(), accessControlErrorDescription)) {
210 preflightFailure(response.url(), accessControlErrorDescription);
214 OwnPtr<CrossOriginPreflightResultCacheItem> preflightResult = adoptPtr(new CrossOriginPreflightResultCacheItem(m_options.allowCredentials));
215 if (!preflightResult->parse(response, accessControlErrorDescription)
216 || !preflightResult->allowsCrossOriginMethod(m_actualRequest->httpMethod(), accessControlErrorDescription)
217 || !preflightResult->allowsCrossOriginHeaders(m_actualRequest->httpHeaderFields(), accessControlErrorDescription)) {
218 preflightFailure(response.url(), accessControlErrorDescription);
222 CrossOriginPreflightResultCache::shared().appendEntry(m_document->securityOrigin()->toString(), m_actualRequest->url(), preflightResult.release());
224 if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessControl) {
225 if (!passesAccessControlCheck(response, m_options.allowCredentials, m_document->securityOrigin(), accessControlErrorDescription)) {
226 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, response.url().string(), accessControlErrorDescription));
231 m_client->didReceiveResponse(response);
235 void DocumentThreadableLoader::didReceiveData(SubresourceLoader* loader, const char* data, int dataLength)
238 ASSERT_UNUSED(loader, loader == m_loader);
240 // Preflight data should be invisible to clients.
244 m_client->didReceiveData(data, dataLength);
247 void DocumentThreadableLoader::didReceiveCachedMetadata(SubresourceLoader* loader, const char* data, int dataLength)
250 ASSERT_UNUSED(loader, loader == m_loader);
252 // Preflight data should be invisible to clients.
256 m_client->didReceiveCachedMetadata(data, dataLength);
259 void DocumentThreadableLoader::didFinishLoading(SubresourceLoader* loader, double finishTime)
261 ASSERT(loader == m_loader);
263 didFinishLoading(loader->identifier(), finishTime);
266 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
268 if (m_actualRequest) {
269 ASSERT(!m_sameOriginRequest);
270 ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
273 m_client->didFinishLoading(identifier, finishTime);
276 void DocumentThreadableLoader::didFail(SubresourceLoader* loader, const ResourceError& error)
279 // m_loader may be null if we arrive here via SubresourceLoader::create in the ctor
280 ASSERT_UNUSED(loader, loader == m_loader || !m_loader);
282 m_client->didFail(error);
285 bool DocumentThreadableLoader::getShouldUseCredentialStorage(SubresourceLoader* loader, bool& shouldUseCredentialStorage)
287 ASSERT_UNUSED(loader, loader == m_loader || !m_loader);
289 if (!m_options.allowCredentials) {
290 shouldUseCredentialStorage = false;
294 return false; // Only FrameLoaderClient can ultimately permit credential use.
297 void DocumentThreadableLoader::didReceiveAuthenticationChallenge(SubresourceLoader* loader, const AuthenticationChallenge& challenge)
299 ASSERT(loader == m_loader);
300 // Users are not prompted for credentials for cross-origin requests.
301 if (!m_sameOriginRequest) {
302 #if PLATFORM(MAC) || USE(CFNETWORK) || USE(CURL)
303 loader->handle()->receivedRequestToContinueWithoutCredential(challenge);
305 // These platforms don't provide a way to continue without credentials, cancel the load altogether.
306 UNUSED_PARAM(challenge);
307 RefPtr<DocumentThreadableLoader> protect(this);
308 m_client->didFail(loader->blockedError());
314 void DocumentThreadableLoader::receivedCancellation(SubresourceLoader* loader, const AuthenticationChallenge& challenge)
317 ASSERT_UNUSED(loader, loader == m_loader);
318 m_client->didReceiveAuthenticationCancellation(challenge.failureResponse());
321 void DocumentThreadableLoader::preflightSuccess()
323 OwnPtr<ResourceRequest> actualRequest;
324 actualRequest.swap(m_actualRequest);
326 actualRequest->setHTTPOrigin(m_document->securityOrigin()->toString());
328 // It should be ok to skip the security check since we already asked about the preflight request.
329 loadRequest(*actualRequest, SkipSecurityCheck);
332 void DocumentThreadableLoader::preflightFailure(const String& url, const String& errorDescription)
334 m_actualRequest = 0; // Prevent didFinishLoading() from bypassing access check.
335 m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, url, errorDescription));
338 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, SecurityCheckPolicy securityCheck)
340 // Any credential should have been removed from the cross-site requests.
341 const KURL& requestURL = request.url();
342 ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
343 ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
346 // Don't sniff content or send load callbacks for the preflight request.
347 bool sendLoadCallbacks = m_options.sendLoadCallbacks && !m_actualRequest;
348 bool sniffContent = m_options.sniffContent && !m_actualRequest;
350 // Clear the loader so that any callbacks from SubresourceLoader::create will not have the old loader.
352 m_loader = resourceLoadScheduler()->scheduleSubresourceLoad(m_document->frame(), this, request, ResourceLoadPriorityMedium, securityCheck, sendLoadCallbacks,
353 sniffContent, m_optionalOutgoingReferrer);
357 // FIXME: ThreadableLoaderOptions.sniffContent is not supported for synchronous requests.
358 StoredCredentials storedCredentials = m_options.allowCredentials ? AllowStoredCredentials : DoNotAllowStoredCredentials;
362 ResourceResponse response;
363 unsigned long identifier = std::numeric_limits<unsigned long>::max();
364 if (m_document->frame())
365 identifier = m_document->frame()->loader()->loadResourceSynchronously(request, storedCredentials, error, response, data);
367 // No exception for file:/// resources, see <rdar://problem/4962298>.
368 // Also, if we have an HTTP response, then it wasn't a network error in fact.
369 if (!error.isNull() && !requestURL.isLocalFile() && response.httpStatusCode() <= 0) {
370 m_client->didFail(error);
374 // FIXME: FrameLoader::loadSynchronously() does not tell us whether a redirect happened or not, so we guess by comparing the
375 // request and response URLs. This isn't a perfect test though, since a server can serve a redirect to the same URL that was
376 // requested. Also comparing the request and response URLs as strings will fail if the requestURL still has its credentials.
377 if (requestURL != response.url() && !isAllowedRedirect(response.url())) {
378 m_client->didFailRedirectCheck();
382 didReceiveResponse(0, response);
384 const char* bytes = static_cast<const char*>(data.data());
385 int len = static_cast<int>(data.size());
386 didReceiveData(0, bytes, len);
388 didFinishLoading(identifier, 0.0);
391 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url)
393 if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
396 // FIXME: We need to implement access control for each redirect. This will require some refactoring though, because the code
397 // that processes redirects doesn't know about access control and expects a synchronous answer from its client about whether
398 // a redirect should proceed.
399 return m_sameOriginRequest && m_document->securityOrigin()->canRequest(url);
402 } // namespace WebCore