2 * Copyright (C) 2010, 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 "AssociatedURLLoader.h"
34 #include "WebApplicationCacheHost.h"
35 #include "WebDataSource.h"
36 #include "WebFrameImpl.h"
37 #include "core/fetch/CrossOriginAccessControl.h"
38 #include "core/loader/DocumentThreadableLoader.h"
39 #include "core/loader/DocumentThreadableLoaderClient.h"
40 #include "core/xml/XMLHttpRequest.h"
41 #include "platform/Timer.h"
42 #include "platform/exported/WrappedResourceRequest.h"
43 #include "platform/exported/WrappedResourceResponse.h"
44 #include "platform/network/HTTPParsers.h"
45 #include "platform/network/ResourceError.h"
46 #include "public/platform/WebHTTPHeaderVisitor.h"
47 #include "public/platform/WebString.h"
48 #include "public/platform/WebURLError.h"
49 #include "public/platform/WebURLLoaderClient.h"
50 #include "public/platform/WebURLRequest.h"
51 #include "wtf/HashSet.h"
52 #include "wtf/text/WTFString.h"
54 using namespace WebCore;
61 class HTTPRequestHeaderValidator : public WebHTTPHeaderVisitor {
62 WTF_MAKE_NONCOPYABLE(HTTPRequestHeaderValidator);
64 HTTPRequestHeaderValidator() : m_isSafe(true) { }
66 void visitHeader(const WebString& name, const WebString& value);
67 bool isSafe() const { return m_isSafe; }
73 typedef HashSet<String, CaseFoldingHash> HTTPHeaderSet;
75 void HTTPRequestHeaderValidator::visitHeader(const WebString& name, const WebString& value)
77 m_isSafe = m_isSafe && isValidHTTPToken(name) && XMLHttpRequest::isAllowedHTTPHeader(name) && isValidHTTPHeaderValue(value);
80 // FIXME: Remove this and use WebCore code that does the same thing.
81 class HTTPResponseHeaderValidator : public WebHTTPHeaderVisitor {
82 WTF_MAKE_NONCOPYABLE(HTTPResponseHeaderValidator);
84 HTTPResponseHeaderValidator(bool usingAccessControl) : m_usingAccessControl(usingAccessControl) { }
86 void visitHeader(const WebString& name, const WebString& value);
87 const HTTPHeaderSet& blockedHeaders();
90 HTTPHeaderSet m_exposedHeaders;
91 HTTPHeaderSet m_blockedHeaders;
92 bool m_usingAccessControl;
95 void HTTPResponseHeaderValidator::visitHeader(const WebString& name, const WebString& value)
97 String headerName(name);
98 if (m_usingAccessControl) {
99 if (equalIgnoringCase(headerName, "access-control-expose-headers"))
100 parseAccessControlExposeHeadersAllowList(value, m_exposedHeaders);
101 else if (!isOnAccessControlResponseHeaderWhitelist(headerName))
102 m_blockedHeaders.add(name);
106 const HTTPHeaderSet& HTTPResponseHeaderValidator::blockedHeaders()
108 // Remove exposed headers from the blocked set.
109 if (!m_exposedHeaders.isEmpty()) {
110 // Don't allow Set-Cookie headers to be exposed.
111 m_exposedHeaders.remove("set-cookie");
112 m_exposedHeaders.remove("set-cookie2");
113 // Block Access-Control-Expose-Header itself. It could be exposed later.
114 m_blockedHeaders.add("access-control-expose-headers");
115 HTTPHeaderSet::const_iterator end = m_exposedHeaders.end();
116 for (HTTPHeaderSet::const_iterator it = m_exposedHeaders.begin(); it != end; ++it)
117 m_blockedHeaders.remove(*it);
120 return m_blockedHeaders;
125 // This class bridges the interface differences between WebCore and WebKit loader clients.
126 // It forwards its ThreadableLoaderClient notifications to a WebURLLoaderClient.
127 class AssociatedURLLoader::ClientAdapter FINAL : public DocumentThreadableLoaderClient {
128 WTF_MAKE_NONCOPYABLE(ClientAdapter);
130 static PassOwnPtr<ClientAdapter> create(AssociatedURLLoader*, WebURLLoaderClient*, const WebURLLoaderOptions&);
132 virtual void didSendData(unsigned long long /*bytesSent*/, unsigned long long /*totalBytesToBeSent*/) OVERRIDE;
133 virtual void willSendRequest(ResourceRequest& /*newRequest*/, const ResourceResponse& /*redirectResponse*/) OVERRIDE;
135 virtual void didReceiveResponse(unsigned long, const ResourceResponse&) OVERRIDE;
136 virtual void didDownloadData(int /*dataLength*/) OVERRIDE;
137 virtual void didReceiveData(const char*, int /*dataLength*/) OVERRIDE;
138 virtual void didReceiveCachedMetadata(const char*, int /*dataLength*/) OVERRIDE;
139 virtual void didFinishLoading(unsigned long /*identifier*/, double /*finishTime*/) OVERRIDE;
140 virtual void didFail(const ResourceError&) OVERRIDE;
141 virtual void didFailRedirectCheck() OVERRIDE;
143 // Sets an error to be reported back to the client, asychronously.
144 void setDelayedError(const ResourceError&);
146 // Enables forwarding of error notifications to the WebURLLoaderClient. These must be
147 // deferred until after the call to AssociatedURLLoader::loadAsynchronously() completes.
148 void enableErrorNotifications();
150 // Stops loading and releases the DocumentThreadableLoader as early as possible.
151 void clearClient() { m_client = 0; }
154 ClientAdapter(AssociatedURLLoader*, WebURLLoaderClient*, const WebURLLoaderOptions&);
156 void notifyError(Timer<ClientAdapter>*);
158 AssociatedURLLoader* m_loader;
159 WebURLLoaderClient* m_client;
160 WebURLLoaderOptions m_options;
163 Timer<ClientAdapter> m_errorTimer;
164 bool m_enableErrorNotifications;
168 PassOwnPtr<AssociatedURLLoader::ClientAdapter> AssociatedURLLoader::ClientAdapter::create(AssociatedURLLoader* loader, WebURLLoaderClient* client, const WebURLLoaderOptions& options)
170 return adoptPtr(new ClientAdapter(loader, client, options));
173 AssociatedURLLoader::ClientAdapter::ClientAdapter(AssociatedURLLoader* loader, WebURLLoaderClient* client, const WebURLLoaderOptions& options)
177 , m_errorTimer(this, &ClientAdapter::notifyError)
178 , m_enableErrorNotifications(false)
185 void AssociatedURLLoader::ClientAdapter::willSendRequest(ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
190 WrappedResourceRequest wrappedNewRequest(newRequest);
191 WrappedResourceResponse wrappedRedirectResponse(redirectResponse);
192 m_client->willSendRequest(m_loader, wrappedNewRequest, wrappedRedirectResponse);
195 void AssociatedURLLoader::ClientAdapter::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
200 m_client->didSendData(m_loader, bytesSent, totalBytesToBeSent);
203 void AssociatedURLLoader::ClientAdapter::didReceiveResponse(unsigned long, const ResourceResponse& response)
205 // Try to use the original ResourceResponse if possible.
206 WebURLResponse validatedResponse = WrappedResourceResponse(response);
207 HTTPResponseHeaderValidator validator(m_options.crossOriginRequestPolicy == WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl);
208 if (!m_options.exposeAllResponseHeaders)
209 validatedResponse.visitHTTPHeaderFields(&validator);
211 // If there are blocked headers, copy the response so we can remove them.
212 const HTTPHeaderSet& blockedHeaders = validator.blockedHeaders();
213 if (!blockedHeaders.isEmpty()) {
214 validatedResponse = WebURLResponse(validatedResponse);
215 HTTPHeaderSet::const_iterator end = blockedHeaders.end();
216 for (HTTPHeaderSet::const_iterator it = blockedHeaders.begin(); it != end; ++it)
217 validatedResponse.clearHTTPHeaderField(*it);
219 m_client->didReceiveResponse(m_loader, validatedResponse);
222 void AssociatedURLLoader::ClientAdapter::didDownloadData(int dataLength)
227 m_client->didDownloadData(m_loader, dataLength, -1);
230 void AssociatedURLLoader::ClientAdapter::didReceiveData(const char* data, int dataLength)
235 m_client->didReceiveData(m_loader, data, dataLength, -1);
238 void AssociatedURLLoader::ClientAdapter::didReceiveCachedMetadata(const char* data, int dataLength)
243 m_client->didReceiveCachedMetadata(m_loader, data, dataLength);
246 void AssociatedURLLoader::ClientAdapter::didFinishLoading(unsigned long identifier, double finishTime)
251 m_client->didFinishLoading(m_loader, finishTime, WebURLLoaderClient::kUnknownEncodedDataLength);
254 void AssociatedURLLoader::ClientAdapter::didFail(const ResourceError& error)
260 m_error = WebURLError(error);
261 if (m_enableErrorNotifications)
262 notifyError(&m_errorTimer);
265 void AssociatedURLLoader::ClientAdapter::didFailRedirectCheck()
270 void AssociatedURLLoader::ClientAdapter::setDelayedError(const ResourceError& error)
275 void AssociatedURLLoader::ClientAdapter::enableErrorNotifications()
277 m_enableErrorNotifications = true;
278 // If an error has already been received, start a timer to report it to the client
279 // after AssociatedURLLoader::loadAsynchronously has returned to the caller.
281 m_errorTimer.startOneShot(0);
284 void AssociatedURLLoader::ClientAdapter::notifyError(Timer<ClientAdapter>* timer)
286 ASSERT_UNUSED(timer, timer == &m_errorTimer);
288 m_client->didFail(m_loader, m_error);
291 AssociatedURLLoader::AssociatedURLLoader(PassRefPtr<WebFrameImpl> frameImpl, const WebURLLoaderOptions& options)
292 : m_frameImpl(frameImpl)
299 AssociatedURLLoader::~AssociatedURLLoader()
304 #define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, webcore_name) \
305 COMPILE_ASSERT(static_cast<int>(blink::webkit_name) == static_cast<int>(WebCore::webcore_name), mismatching_enums)
307 COMPILE_ASSERT_MATCHING_ENUM(WebURLLoaderOptions::CrossOriginRequestPolicyDeny, DenyCrossOriginRequests);
308 COMPILE_ASSERT_MATCHING_ENUM(WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl, UseAccessControl);
309 COMPILE_ASSERT_MATCHING_ENUM(WebURLLoaderOptions::CrossOriginRequestPolicyAllow, AllowCrossOriginRequests);
311 COMPILE_ASSERT_MATCHING_ENUM(WebURLLoaderOptions::ConsiderPreflight, ConsiderPreflight);
312 COMPILE_ASSERT_MATCHING_ENUM(WebURLLoaderOptions::ForcePreflight, ForcePreflight);
313 COMPILE_ASSERT_MATCHING_ENUM(WebURLLoaderOptions::PreventPreflight, PreventPreflight);
315 void AssociatedURLLoader::loadSynchronously(const WebURLRequest& request, WebURLResponse& response, WebURLError& error, WebData& data)
317 ASSERT(0); // Synchronous loading is not supported.
320 void AssociatedURLLoader::loadAsynchronously(const WebURLRequest& request, WebURLLoaderClient* client)
327 bool allowLoad = true;
328 WebURLRequest newRequest(request);
329 if (m_options.untrustedHTTP) {
330 WebString method = newRequest.httpMethod();
331 allowLoad = isValidHTTPToken(method) && XMLHttpRequest::isAllowedHTTPMethod(method);
333 newRequest.setHTTPMethod(XMLHttpRequest::uppercaseKnownHTTPMethod(method));
334 HTTPRequestHeaderValidator validator;
335 newRequest.visitHTTPHeaderFields(&validator);
336 allowLoad = validator.isSafe();
340 m_clientAdapter = ClientAdapter::create(this, m_client, m_options);
343 ThreadableLoaderOptions options;
344 options.sniffContent = m_options.sniffContent ? SniffContent : DoNotSniffContent;
345 options.allowCredentials = m_options.allowCredentials ? AllowStoredCredentials : DoNotAllowStoredCredentials;
346 options.preflightPolicy = static_cast<WebCore::PreflightPolicy>(m_options.preflightPolicy);
347 options.crossOriginRequestPolicy = static_cast<WebCore::CrossOriginRequestPolicy>(m_options.crossOriginRequestPolicy);
348 options.dataBufferingPolicy = DoNotBufferData;
350 const ResourceRequest& webcoreRequest = newRequest.toResourceRequest();
351 Document* webcoreDocument = m_frameImpl->frame()->document();
352 m_loader = DocumentThreadableLoader::create(webcoreDocument, m_clientAdapter.get(), webcoreRequest, options);
354 // FIXME: return meaningful error codes.
355 m_clientAdapter->setDelayedError(ResourceError());
357 m_clientAdapter->enableErrorNotifications();
360 void AssociatedURLLoader::cancel()
363 m_clientAdapter->clearClient();
368 void AssociatedURLLoader::setDefersLoading(bool defersLoading)
371 m_loader->setDefersLoading(defersLoading);