Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / loader / DocumentThreadableLoader.cpp
1 /*
2  * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
3  * Copyright (C) 2013, Intel Corporation
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
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
14  * distribution.
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.
18  *
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.
30  */
31
32 #include "config.h"
33 #include "core/loader/DocumentThreadableLoader.h"
34
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"
52
53 namespace WebCore {
54
55 void DocumentThreadableLoader::loadResourceSynchronously(Document* document, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
56 {
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());
60 }
61
62 PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
63 {
64     RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
65     if (!loader->resource())
66         loader = 0;
67     return loader.release();
68 }
69
70 DocumentThreadableLoader::DocumentThreadableLoader(Document* document, ThreadableLoaderClient* client, BlockingBehavior blockingBehavior, const ResourceRequest& request, const ThreadableLoaderOptions& options)
71     : m_client(client)
72     , m_document(document)
73     , m_options(options)
74     , m_sameOriginRequest(securityOrigin()->canRequest(request.url()))
75     , m_simpleRequest(true)
76     , m_async(blockingBehavior == LoadAsynchronously)
77     , m_timeoutTimer(this, &DocumentThreadableLoader::didTimeout)
78 {
79     ASSERT(document);
80     ASSERT(client);
81     // Setting an outgoing referer is only supported in the async code path.
82     ASSERT(m_async || request.httpReferrer().isEmpty());
83
84     if (m_sameOriginRequest || m_options.crossOriginRequestPolicy == AllowCrossOriginRequests) {
85         loadRequest(request);
86         return;
87     }
88
89     if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
90         m_client->didFail(ResourceError(errorDomainBlinkInternal, 0, request.url().string(), "Cross origin requests are not supported."));
91         return;
92     }
93
94     makeCrossOriginAccessRequest(request);
95 }
96
97 void DocumentThreadableLoader::makeCrossOriginAccessRequest(const ResourceRequest& request)
98 {
99     ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
100
101     OwnPtr<ResourceRequest> crossOriginRequest = adoptPtr(new ResourceRequest(request));
102
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);
106     } else {
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();
111
112         if (CrossOriginPreflightResultCache::shared().canSkipPreflight(securityOrigin()->toString(), m_actualRequest->url(), m_options.allowCredentials, m_actualRequest->httpMethod(), m_actualRequest->httpHeaderFields()))
113             preflightSuccess();
114         else
115             makeCrossOriginAccessRequestWithPreflight(*m_actualRequest);
116     }
117 }
118
119 void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const ResourceRequest& request)
120 {
121     ASSERT(m_options.preflightPolicy != ForcePreflight);
122     ASSERT(m_options.preflightPolicy == PreventPreflight || isSimpleCrossOriginAccessRequest(request.httpMethod(), request.httpHeaderFields()));
123
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."));
127         return;
128     }
129
130     loadRequest(request);
131 }
132
133 void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const ResourceRequest& request)
134 {
135     ResourceRequest preflightRequest = createAccessControlPreflightRequest(request, securityOrigin());
136     loadRequest(preflightRequest);
137 }
138
139 DocumentThreadableLoader::~DocumentThreadableLoader()
140 {
141 }
142
143 void DocumentThreadableLoader::cancel()
144 {
145     cancelWithError(ResourceError());
146 }
147
148 void DocumentThreadableLoader::cancelWithError(const ResourceError& error)
149 {
150     RefPtr<DocumentThreadableLoader> protect(this);
151
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);
159         }
160         m_client->didFail(errorForCallback);
161     }
162     clearResource();
163     m_client = 0;
164 }
165
166 void DocumentThreadableLoader::setDefersLoading(bool value)
167 {
168     if (resource())
169         resource()->setDefersLoading(value);
170 }
171
172 void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
173 {
174     ASSERT(m_client);
175     ASSERT_UNUSED(resource, resource == this->resource());
176
177     RefPtr<DocumentThreadableLoader> protect(this);
178     if (!isAllowedByPolicy(request.url())) {
179         m_client->didFailRedirectCheck();
180         request = ResourceRequest();
181         return;
182     }
183
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);
188         return;
189     }
190
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) {
195
196         InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document->frame(), resource->identifier(), m_document->frame()->loader().documentLoader(), redirectResponse, 0);
197
198         bool allowRedirect = false;
199         String accessControlErrorDescription;
200
201         if (m_simpleRequest) {
202             allowRedirect = CrossOriginAccessControl::isLegalRedirectLocation(request.url(), accessControlErrorDescription)
203                             && (m_sameOriginRequest || passesAccessControlCheck(redirectResponse, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription));
204         } else {
205             accessControlErrorDescription = "The request was redirected to '"+ request.url().string() + "', which is disallowed for cross-origin requests that require preflight.";
206         }
207
208         if (allowRedirect) {
209             // FIXME: consider combining this with CORS redirect handling performed by
210             // CrossOriginAccessControl::handleRedirect().
211             clearResource();
212
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;
222
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;
227
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);
235             return;
236         }
237
238         ResourceError error(errorDomainBlinkInternal, 0, redirectResponse.url().string(), accessControlErrorDescription);
239         m_client->didFailAccessControlCheck(error);
240     } else {
241         m_client->didFailRedirectCheck();
242     }
243     request = ResourceRequest();
244 }
245
246 void DocumentThreadableLoader::dataSent(Resource* resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
247 {
248     ASSERT(m_client);
249     ASSERT_UNUSED(resource, resource == this->resource());
250     m_client->didSendData(bytesSent, totalBytesToBeSent);
251 }
252
253 void DocumentThreadableLoader::dataDownloaded(Resource* resource, int dataLength)
254 {
255     ASSERT(m_client);
256     ASSERT_UNUSED(resource, resource == this->resource());
257     ASSERT(!m_actualRequest);
258
259     m_client->didDownloadData(dataLength);
260 }
261
262 void DocumentThreadableLoader::responseReceived(Resource* resource, const ResourceResponse& response)
263 {
264     ASSERT_UNUSED(resource, resource == this->resource());
265     didReceiveResponse(resource->identifier(), response);
266 }
267
268 void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
269 {
270     ASSERT(m_client);
271
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);
280
281         if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
282             preflightFailure(response.url().string(), accessControlErrorDescription);
283             return;
284         }
285
286         if (!passesPreflightStatusCheck(response, accessControlErrorDescription)) {
287             preflightFailure(response.url().string(), accessControlErrorDescription);
288             return;
289         }
290
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);
296             return;
297         }
298
299         CrossOriginPreflightResultCache::shared().appendEntry(securityOrigin()->toString(), m_actualRequest->url(), preflightResult.release());
300     } else {
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));
304                 return;
305             }
306         }
307
308         m_client->didReceiveResponse(identifier, response);
309     }
310 }
311
312 void DocumentThreadableLoader::dataReceived(Resource* resource, const char* data, int dataLength)
313 {
314     ASSERT_UNUSED(resource, resource == this->resource());
315     didReceiveData(data, dataLength);
316 }
317
318 void DocumentThreadableLoader::didReceiveData(const char* data, int dataLength)
319 {
320     ASSERT(m_client);
321     // Preflight data should be invisible to clients.
322     if (!m_actualRequest)
323         m_client->didReceiveData(data, dataLength);
324 }
325
326 void DocumentThreadableLoader::notifyFinished(Resource* resource)
327 {
328     ASSERT(m_client);
329     ASSERT(resource == this->resource());
330
331     m_timeoutTimer.stop();
332
333     if (resource->errorOccurred())
334         m_client->didFail(resource->resourceError());
335     else
336         didFinishLoading(resource->identifier(), resource->loadFinishTime());
337 }
338
339 void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
340 {
341     if (m_actualRequest) {
342         ASSERT(!m_sameOriginRequest);
343         ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
344         preflightSuccess();
345     } else
346         m_client->didFinishLoading(identifier, finishTime);
347 }
348
349 void DocumentThreadableLoader::didTimeout(Timer<DocumentThreadableLoader>* timer)
350 {
351     ASSERT_UNUSED(timer, timer == &m_timeoutTimer);
352
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);
359 }
360
361 void DocumentThreadableLoader::preflightSuccess()
362 {
363     OwnPtr<ResourceRequest> actualRequest;
364     actualRequest.swap(m_actualRequest);
365
366     actualRequest->setHTTPOrigin(securityOrigin()->toAtomicString());
367
368     clearResource();
369
370     loadRequest(*actualRequest);
371 }
372
373 void DocumentThreadableLoader::preflightFailure(const String& url, const String& errorDescription)
374 {
375     ResourceError error(errorDomainBlinkInternal, 0, url, errorDescription);
376     m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
377     m_client->didFailAccessControlCheck(error);
378 }
379
380 void DocumentThreadableLoader::loadRequest(const ResourceRequest& request)
381 {
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());
386
387     ThreadableLoaderOptions options = m_options;
388     if (m_async) {
389         if (m_actualRequest) {
390             options.sniffContent = DoNotSniffContent;
391             options.dataBufferingPolicy = BufferData;
392         }
393
394         if (m_options.timeoutMilliseconds > 0)
395             m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0);
396
397         FetchRequest newRequest(request, m_options.initiator, options);
398         ASSERT(!resource());
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);
403         }
404         return;
405     }
406
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();
412
413     InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
414
415     if (!resource) {
416         m_client->didFail(error);
417         return;
418     }
419
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);
424         return;
425     }
426
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();
432         return;
433     }
434
435     didReceiveResponse(identifier, response);
436
437     SharedBuffer* data = resource->resourceBuffer();
438     if (data)
439         didReceiveData(data->data(), data->size());
440
441     didFinishLoading(identifier, 0.0);
442 }
443
444 bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url) const
445 {
446     if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
447         return true;
448
449     return m_sameOriginRequest && securityOrigin()->canRequest(url);
450 }
451
452 bool DocumentThreadableLoader::isAllowedByPolicy(const KURL& url) const
453 {
454     if (m_options.contentSecurityPolicyEnforcement != EnforceConnectSrcDirective)
455         return true;
456     return m_document->contentSecurityPolicy()->allowConnectToSource(url);
457 }
458
459 SecurityOrigin* DocumentThreadableLoader::securityOrigin() const
460 {
461     return m_options.securityOrigin ? m_options.securityOrigin.get() : m_document->securityOrigin();
462 }
463
464 } // namespace WebCore