1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // An implementation of WebURLLoader in terms of ResourceLoaderBridge.
7 #include "content/child/web_url_loader_impl.h"
10 #include "base/files/file_path.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/strings/string_util.h"
14 #include "base/time/time.h"
15 #include "content/child/ftp_directory_listing_response_delegate.h"
16 #include "content/child/multipart_response_delegate.h"
17 #include "content/child/request_extra_data.h"
18 #include "content/child/request_info.h"
19 #include "content/child/resource_dispatcher.h"
20 #include "content/child/sync_load_response.h"
21 #include "content/common/resource_request_body.h"
22 #include "content/public/child/request_peer.h"
23 #include "net/base/data_url.h"
24 #include "net/base/filename_util.h"
25 #include "net/base/load_flags.h"
26 #include "net/base/mime_util.h"
27 #include "net/base/net_errors.h"
28 #include "net/http/http_response_headers.h"
29 #include "net/http/http_util.h"
30 #include "net/url_request/url_request.h"
31 #include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
32 #include "third_party/WebKit/public/platform/WebHTTPLoadInfo.h"
33 #include "third_party/WebKit/public/platform/WebURL.h"
34 #include "third_party/WebKit/public/platform/WebURLError.h"
35 #include "third_party/WebKit/public/platform/WebURLLoadTiming.h"
36 #include "third_party/WebKit/public/platform/WebURLLoaderClient.h"
37 #include "third_party/WebKit/public/platform/WebURLRequest.h"
38 #include "third_party/WebKit/public/platform/WebURLResponse.h"
39 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
40 #include "webkit/child/resource_loader_bridge.h"
41 #include "webkit/child/weburlresponse_extradata_impl.h"
44 using base::TimeTicks
;
46 using blink::WebHTTPBody
;
47 using blink::WebHTTPHeaderVisitor
;
48 using blink::WebHTTPLoadInfo
;
49 using blink::WebReferrerPolicy
;
50 using blink::WebSecurityPolicy
;
51 using blink::WebString
;
53 using blink::WebURLError
;
54 using blink::WebURLLoadTiming
;
55 using blink::WebURLLoader
;
56 using blink::WebURLLoaderClient
;
57 using blink::WebURLRequest
;
58 using blink::WebURLResponse
;
59 using webkit_glue::ResourceLoaderBridge
;
60 using webkit_glue::WebURLResponseExtraDataImpl
;
64 // Utilities ------------------------------------------------------------------
68 const char kThrottledErrorDescription
[] =
69 "Request throttled. Visit http://dev.chromium.org/throttling for more "
72 class HeaderFlattener
: public WebHTTPHeaderVisitor
{
74 HeaderFlattener() : has_accept_header_(false) {}
76 virtual void visitHeader(const WebString
& name
, const WebString
& value
) {
77 // Headers are latin1.
78 const std::string
& name_latin1
= name
.latin1();
79 const std::string
& value_latin1
= value
.latin1();
81 // Skip over referrer headers found in the header map because we already
82 // pulled it out as a separate parameter.
83 if (LowerCaseEqualsASCII(name_latin1
, "referer"))
86 if (LowerCaseEqualsASCII(name_latin1
, "accept"))
87 has_accept_header_
= true;
90 buffer_
.append("\r\n");
91 buffer_
.append(name_latin1
+ ": " + value_latin1
);
94 const std::string
& GetBuffer() {
95 // In some cases, WebKit doesn't add an Accept header, but not having the
96 // header confuses some web servers. See bug 808613.
97 if (!has_accept_header_
) {
99 buffer_
.append("\r\n");
100 buffer_
.append("Accept: */*");
101 has_accept_header_
= true;
108 bool has_accept_header_
;
111 // Extracts the information from a data: url.
112 bool GetInfoFromDataURL(const GURL
& url
,
113 ResourceResponseInfo
* info
,
116 std::string mime_type
;
118 if (net::DataURL::Parse(url
, &mime_type
, &charset
, data
)) {
119 *error_code
= net::OK
;
120 // Assure same time for all time fields of data: URLs.
121 Time now
= Time::Now();
122 info
->load_timing
.request_start
= TimeTicks::Now();
123 info
->load_timing
.request_start_time
= now
;
124 info
->request_time
= now
;
125 info
->response_time
= now
;
126 info
->headers
= NULL
;
127 info
->mime_type
.swap(mime_type
);
128 info
->charset
.swap(charset
);
129 info
->security_info
.clear();
130 info
->content_length
= data
->length();
131 info
->encoded_data_length
= 0;
136 *error_code
= net::ERR_INVALID_URL
;
140 typedef ResourceDevToolsInfo::HeadersVector HeadersVector
;
142 // Converts timing data from |load_timing| to the format used by WebKit.
143 void PopulateURLLoadTiming(const net::LoadTimingInfo
& load_timing
,
144 WebURLLoadTiming
* url_timing
) {
145 DCHECK(!load_timing
.request_start
.is_null());
147 const TimeTicks kNullTicks
;
148 url_timing
->initialize();
149 url_timing
->setRequestTime(
150 (load_timing
.request_start
- kNullTicks
).InSecondsF());
151 url_timing
->setProxyStart(
152 (load_timing
.proxy_resolve_start
- kNullTicks
).InSecondsF());
153 url_timing
->setProxyEnd(
154 (load_timing
.proxy_resolve_end
- kNullTicks
).InSecondsF());
155 url_timing
->setDNSStart(
156 (load_timing
.connect_timing
.dns_start
- kNullTicks
).InSecondsF());
157 url_timing
->setDNSEnd(
158 (load_timing
.connect_timing
.dns_end
- kNullTicks
).InSecondsF());
159 url_timing
->setConnectStart(
160 (load_timing
.connect_timing
.connect_start
- kNullTicks
).InSecondsF());
161 url_timing
->setConnectEnd(
162 (load_timing
.connect_timing
.connect_end
- kNullTicks
).InSecondsF());
163 url_timing
->setSSLStart(
164 (load_timing
.connect_timing
.ssl_start
- kNullTicks
).InSecondsF());
165 url_timing
->setSSLEnd(
166 (load_timing
.connect_timing
.ssl_end
- kNullTicks
).InSecondsF());
167 url_timing
->setSendStart(
168 (load_timing
.send_start
- kNullTicks
).InSecondsF());
169 url_timing
->setSendEnd(
170 (load_timing
.send_end
- kNullTicks
).InSecondsF());
171 url_timing
->setReceiveHeadersEnd(
172 (load_timing
.receive_headers_end
- kNullTicks
).InSecondsF());
175 net::RequestPriority
ConvertWebKitPriorityToNetPriority(
176 const WebURLRequest::Priority
& priority
) {
178 case WebURLRequest::PriorityVeryHigh
:
181 case WebURLRequest::PriorityHigh
:
184 case WebURLRequest::PriorityMedium
:
187 case WebURLRequest::PriorityLow
:
190 case WebURLRequest::PriorityVeryLow
:
193 case WebURLRequest::PriorityUnresolved
:
202 // WebURLLoaderImpl::Context --------------------------------------------------
204 // This inner class exists since the WebURLLoader may be deleted while inside a
205 // call to WebURLLoaderClient. Refcounting is to keep the context from being
206 // deleted if it may have work to do after calling into the client.
207 class WebURLLoaderImpl::Context
: public base::RefCounted
<Context
>,
210 Context(WebURLLoaderImpl
* loader
, ResourceDispatcher
* resource_dispatcher
);
212 WebURLLoaderClient
* client() const { return client_
; }
213 void set_client(WebURLLoaderClient
* client
) { client_
= client
; }
216 void SetDefersLoading(bool value
);
217 void DidChangePriority(WebURLRequest::Priority new_priority
,
218 int intra_priority_value
);
219 bool AttachThreadedDataReceiver(
220 blink::WebThreadedDataReceiver
* threaded_data_receiver
);
221 void Start(const WebURLRequest
& request
,
222 SyncLoadResponse
* sync_load_response
);
224 // RequestPeer methods:
225 virtual void OnUploadProgress(uint64 position
, uint64 size
) OVERRIDE
;
226 virtual bool OnReceivedRedirect(const GURL
& new_url
,
227 const GURL
& new_first_party_for_cookies
,
228 const ResourceResponseInfo
& info
) OVERRIDE
;
229 virtual void OnReceivedResponse(const ResourceResponseInfo
& info
) OVERRIDE
;
230 virtual void OnDownloadedData(int len
, int encoded_data_length
) OVERRIDE
;
231 virtual void OnReceivedData(const char* data
,
233 int encoded_data_length
) OVERRIDE
;
234 virtual void OnReceivedCachedMetadata(const char* data
, int len
) OVERRIDE
;
235 virtual void OnCompletedRequest(
237 bool was_ignored_by_handler
,
238 bool stale_copy_in_cache
,
239 const std::string
& security_info
,
240 const base::TimeTicks
& completion_time
,
241 int64 total_transfer_size
) OVERRIDE
;
244 friend class base::RefCounted
<Context
>;
245 virtual ~Context() {}
247 // We can optimize the handling of data URLs in most cases.
248 bool CanHandleDataURL(const GURL
& url
) const;
249 void HandleDataURL();
251 WebURLLoaderImpl
* loader_
;
252 WebURLRequest request_
;
253 WebURLLoaderClient
* client_
;
254 ResourceDispatcher
* resource_dispatcher_
;
255 WebReferrerPolicy referrer_policy_
;
256 scoped_ptr
<ResourceLoaderBridge
> bridge_
;
257 scoped_ptr
<FtpDirectoryListingResponseDelegate
> ftp_listing_delegate_
;
258 scoped_ptr
<MultipartResponseDelegate
> multipart_delegate_
;
259 scoped_ptr
<ResourceLoaderBridge
> completed_bridge_
;
262 WebURLLoaderImpl::Context::Context(WebURLLoaderImpl
* loader
,
263 ResourceDispatcher
* resource_dispatcher
)
266 resource_dispatcher_(resource_dispatcher
),
267 referrer_policy_(blink::WebReferrerPolicyDefault
) {
270 void WebURLLoaderImpl::Context::Cancel() {
276 // Ensure that we do not notify the multipart delegate anymore as it has
277 // its own pointer to the client.
278 if (multipart_delegate_
)
279 multipart_delegate_
->Cancel();
280 // Ditto for the ftp delegate.
281 if (ftp_listing_delegate_
)
282 ftp_listing_delegate_
->Cancel();
284 // Do not make any further calls to the client.
289 void WebURLLoaderImpl::Context::SetDefersLoading(bool value
) {
291 bridge_
->SetDefersLoading(value
);
294 void WebURLLoaderImpl::Context::DidChangePriority(
295 WebURLRequest::Priority new_priority
, int intra_priority_value
) {
297 bridge_
->DidChangePriority(
298 ConvertWebKitPriorityToNetPriority(new_priority
), intra_priority_value
);
301 bool WebURLLoaderImpl::Context::AttachThreadedDataReceiver(
302 blink::WebThreadedDataReceiver
* threaded_data_receiver
) {
304 return bridge_
->AttachThreadedDataReceiver(threaded_data_receiver
);
309 void WebURLLoaderImpl::Context::Start(const WebURLRequest
& request
,
310 SyncLoadResponse
* sync_load_response
) {
311 DCHECK(!bridge_
.get());
313 request_
= request
; // Save the request.
315 GURL url
= request
.url();
316 if (url
.SchemeIs("data") && CanHandleDataURL(url
)) {
317 if (sync_load_response
) {
318 // This is a sync load. Do the work now.
319 sync_load_response
->url
= url
;
321 GetInfoFromDataURL(sync_load_response
->url
, sync_load_response
,
322 &sync_load_response
->data
,
323 &sync_load_response
->error_code
);
325 base::MessageLoop::current()->PostTask(
326 FROM_HERE
, base::Bind(&Context::HandleDataURL
, this));
332 request
.httpHeaderField(WebString::fromUTF8("Referer")).latin1());
333 const std::string
& method
= request
.httpMethod().latin1();
335 int load_flags
= net::LOAD_NORMAL
| net::LOAD_ENABLE_LOAD_TIMING
;
336 switch (request
.cachePolicy()) {
337 case WebURLRequest::ReloadIgnoringCacheData
:
338 // Required by LayoutTests/http/tests/misc/refresh-headers.php
339 load_flags
|= net::LOAD_VALIDATE_CACHE
;
341 case WebURLRequest::ReloadBypassingCache
:
342 load_flags
|= net::LOAD_BYPASS_CACHE
;
344 case WebURLRequest::ReturnCacheDataElseLoad
:
345 load_flags
|= net::LOAD_PREFERRING_CACHE
;
347 case WebURLRequest::ReturnCacheDataDontLoad
:
348 load_flags
|= net::LOAD_ONLY_FROM_CACHE
;
350 case WebURLRequest::UseProtocolCachePolicy
:
356 if (request
.reportUploadProgress())
357 load_flags
|= net::LOAD_ENABLE_UPLOAD_PROGRESS
;
358 if (request
.reportRawHeaders())
359 load_flags
|= net::LOAD_REPORT_RAW_HEADERS
;
361 if (!request
.allowStoredCredentials()) {
362 load_flags
|= net::LOAD_DO_NOT_SAVE_COOKIES
;
363 load_flags
|= net::LOAD_DO_NOT_SEND_COOKIES
;
366 if (!request
.allowStoredCredentials())
367 load_flags
|= net::LOAD_DO_NOT_SEND_AUTH_DATA
;
369 if (request
.targetType() == WebURLRequest::TargetIsXHR
&&
370 (url
.has_username() || url
.has_password())) {
371 load_flags
|= net::LOAD_DO_NOT_PROMPT_FOR_LOGIN
;
374 HeaderFlattener flattener
;
375 request
.visitHTTPHeaderFields(&flattener
);
377 // TODO(brettw) this should take parameter encoding into account when
378 // creating the GURLs.
380 RequestInfo request_info
;
381 request_info
.method
= method
;
382 request_info
.url
= url
;
383 request_info
.first_party_for_cookies
= request
.firstPartyForCookies();
384 request_info
.referrer
= referrer_url
;
385 request_info
.headers
= flattener
.GetBuffer();
386 request_info
.load_flags
= load_flags
;
387 // requestor_pid only needs to be non-zero if the request originates outside
388 // the render process, so we can use requestorProcessID even for requests
389 // from in-process plugins.
390 request_info
.requestor_pid
= request
.requestorProcessID();
391 request_info
.request_type
=
392 ResourceType::FromTargetType(request
.targetType());
393 request_info
.priority
=
394 ConvertWebKitPriorityToNetPriority(request
.priority());
395 request_info
.appcache_host_id
= request
.appCacheHostID();
396 request_info
.routing_id
= request
.requestorID();
397 request_info
.download_to_file
= request
.downloadToFile();
398 request_info
.has_user_gesture
= request
.hasUserGesture();
399 request_info
.extra_data
= request
.extraData();
400 referrer_policy_
= request
.referrerPolicy();
401 request_info
.referrer_policy
= request
.referrerPolicy();
402 bridge_
.reset(resource_dispatcher_
->CreateBridge(request_info
));
404 if (!request
.httpBody().isNull()) {
405 // GET and HEAD requests shouldn't have http bodies.
406 DCHECK(method
!= "GET" && method
!= "HEAD");
407 const WebHTTPBody
& httpBody
= request
.httpBody();
409 WebHTTPBody::Element element
;
410 scoped_refptr
<ResourceRequestBody
> request_body
= new ResourceRequestBody
;
411 while (httpBody
.elementAt(i
++, element
)) {
412 switch (element
.type
) {
413 case WebHTTPBody::Element::TypeData
:
414 if (!element
.data
.isEmpty()) {
415 // WebKit sometimes gives up empty data to append. These aren't
416 // necessary so we just optimize those out here.
417 request_body
->AppendBytes(
418 element
.data
.data(), static_cast<int>(element
.data
.size()));
421 case WebHTTPBody::Element::TypeFile
:
422 if (element
.fileLength
== -1) {
423 request_body
->AppendFileRange(
424 base::FilePath::FromUTF16Unsafe(element
.filePath
),
425 0, kuint64max
, base::Time());
427 request_body
->AppendFileRange(
428 base::FilePath::FromUTF16Unsafe(element
.filePath
),
429 static_cast<uint64
>(element
.fileStart
),
430 static_cast<uint64
>(element
.fileLength
),
431 base::Time::FromDoubleT(element
.modificationTime
));
434 case WebHTTPBody::Element::TypeFileSystemURL
: {
435 GURL file_system_url
= element
.fileSystemURL
;
436 DCHECK(file_system_url
.SchemeIsFileSystem());
437 request_body
->AppendFileSystemFileRange(
439 static_cast<uint64
>(element
.fileStart
),
440 static_cast<uint64
>(element
.fileLength
),
441 base::Time::FromDoubleT(element
.modificationTime
));
444 case WebHTTPBody::Element::TypeBlob
:
445 request_body
->AppendBlob(element
.blobUUID
.utf8());
451 request_body
->set_identifier(request
.httpBody().identifier());
452 bridge_
->SetRequestBody(request_body
.get());
455 if (sync_load_response
) {
456 bridge_
->SyncLoad(sync_load_response
);
460 // TODO(mmenke): This case probably never happens, anyways. Probably should
461 // not handle this case at all. If it's worth handling, this code currently
462 // results in the request just hanging, which should be fixed.
463 if (!bridge_
->Start(this))
467 void WebURLLoaderImpl::Context::OnUploadProgress(uint64 position
, uint64 size
) {
469 client_
->didSendData(loader_
, position
, size
);
472 bool WebURLLoaderImpl::Context::OnReceivedRedirect(
474 const GURL
& new_first_party_for_cookies
,
475 const ResourceResponseInfo
& info
) {
479 WebURLResponse response
;
480 response
.initialize();
481 PopulateURLResponse(request_
.url(), info
, &response
);
483 // TODO(darin): We lack sufficient information to construct the actual
484 // request that resulted from the redirect.
485 WebURLRequest
new_request(new_url
);
486 new_request
.setFirstPartyForCookies(new_first_party_for_cookies
);
487 new_request
.setDownloadToFile(request_
.downloadToFile());
489 WebString referrer_string
= WebString::fromUTF8("Referer");
490 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
493 request_
.httpHeaderField(referrer_string
));
494 if (!referrer
.isEmpty())
495 new_request
.setHTTPReferrer(referrer
, referrer_policy_
);
497 std::string method
= request_
.httpMethod().utf8();
498 std::string new_method
= net::URLRequest::ComputeMethodForRedirect(
499 method
, response
.httpStatusCode());
500 new_request
.setHTTPMethod(WebString::fromUTF8(new_method
));
501 if (new_method
== method
)
502 new_request
.setHTTPBody(request_
.httpBody());
504 // Protect from deletion during call to willSendRequest.
505 scoped_refptr
<Context
> protect(this);
507 client_
->willSendRequest(loader_
, new_request
, response
);
508 request_
= new_request
;
510 // Only follow the redirect if WebKit left the URL unmodified.
511 if (new_url
== GURL(new_request
.url())) {
512 // First-party cookie logic moved from DocumentLoader in Blink to
513 // CrossSiteResourceHandler in the browser. Assert that Blink didn't try to
514 // change it to something else.
515 DCHECK_EQ(new_first_party_for_cookies
.spec(),
516 request_
.firstPartyForCookies().string().utf8());
520 // We assume that WebKit only changes the URL to suppress a redirect, and we
521 // assume that it does so by setting it to be invalid.
522 DCHECK(!new_request
.url().isValid());
526 void WebURLLoaderImpl::Context::OnReceivedResponse(
527 const ResourceResponseInfo
& info
) {
531 WebURLResponse response
;
532 response
.initialize();
533 PopulateURLResponse(request_
.url(), info
, &response
);
535 bool show_raw_listing
= (GURL(request_
.url()).query() == "raw");
537 if (info
.mime_type
== "text/vnd.chromium.ftp-dir") {
538 if (show_raw_listing
) {
539 // Set the MIME type to plain text to prevent any active content.
540 response
.setMIMEType("text/plain");
542 // We're going to produce a parsed listing in HTML.
543 response
.setMIMEType("text/html");
547 // Prevent |this| from being destroyed if the client destroys the loader,
548 // ether in didReceiveResponse, or when the multipart/ftp delegate calls into
550 scoped_refptr
<Context
> protect(this);
551 client_
->didReceiveResponse(loader_
, response
);
553 // We may have been cancelled after didReceiveResponse, which would leave us
554 // without a client and therefore without much need to do further handling.
558 DCHECK(!ftp_listing_delegate_
.get());
559 DCHECK(!multipart_delegate_
.get());
560 if (info
.headers
.get() && info
.mime_type
== "multipart/x-mixed-replace") {
561 std::string content_type
;
562 info
.headers
->EnumerateHeader(NULL
, "content-type", &content_type
);
564 std::string mime_type
;
566 bool had_charset
= false;
567 std::string boundary
;
568 net::HttpUtil::ParseContentType(content_type
, &mime_type
, &charset
,
569 &had_charset
, &boundary
);
570 base::TrimString(boundary
, " \"", &boundary
);
572 // If there's no boundary, just handle the request normally. In the gecko
573 // code, nsMultiMixedConv::OnStartRequest throws an exception.
574 if (!boundary
.empty()) {
575 multipart_delegate_
.reset(
576 new MultipartResponseDelegate(client_
, loader_
, response
, boundary
));
578 } else if (info
.mime_type
== "text/vnd.chromium.ftp-dir" &&
580 ftp_listing_delegate_
.reset(
581 new FtpDirectoryListingResponseDelegate(client_
, loader_
, response
));
585 void WebURLLoaderImpl::Context::OnDownloadedData(int len
,
586 int encoded_data_length
) {
588 client_
->didDownloadData(loader_
, len
, encoded_data_length
);
591 void WebURLLoaderImpl::Context::OnReceivedData(const char* data
,
593 int encoded_data_length
) {
597 if (ftp_listing_delegate_
) {
598 // The FTP listing delegate will make the appropriate calls to
599 // client_->didReceiveData and client_->didReceiveResponse. Since the
600 // delegate may want to do work after sending data to the delegate, keep
601 // |this| and the delegate alive until it's finished handling the data.
602 scoped_refptr
<Context
> protect(this);
603 ftp_listing_delegate_
->OnReceivedData(data
, data_length
);
604 } else if (multipart_delegate_
) {
605 // The multipart delegate will make the appropriate calls to
606 // client_->didReceiveData and client_->didReceiveResponse. Since the
607 // delegate may want to do work after sending data to the delegate, keep
608 // |this| and the delegate alive until it's finished handling the data.
609 scoped_refptr
<Context
> protect(this);
610 multipart_delegate_
->OnReceivedData(data
, data_length
, encoded_data_length
);
612 client_
->didReceiveData(loader_
, data
, data_length
, encoded_data_length
);
616 void WebURLLoaderImpl::Context::OnReceivedCachedMetadata(
617 const char* data
, int len
) {
619 client_
->didReceiveCachedMetadata(loader_
, data
, len
);
622 void WebURLLoaderImpl::Context::OnCompletedRequest(
624 bool was_ignored_by_handler
,
625 bool stale_copy_in_cache
,
626 const std::string
& security_info
,
627 const base::TimeTicks
& completion_time
,
628 int64 total_transfer_size
) {
629 // The WebURLLoaderImpl may be deleted in any of the calls to the client or
630 // the delegates below (As they also may call in to the client). Keep |this|
631 // alive in that case, to avoid a crash. If that happens, the request will be
632 // cancelled and |client_| will be set to NULL.
633 scoped_refptr
<Context
> protect(this);
635 if (ftp_listing_delegate_
) {
636 ftp_listing_delegate_
->OnCompletedRequest();
637 ftp_listing_delegate_
.reset(NULL
);
638 } else if (multipart_delegate_
) {
639 multipart_delegate_
->OnCompletedRequest();
640 multipart_delegate_
.reset(NULL
);
643 // Prevent any further IPC to the browser now that we're complete, but
644 // don't delete it to keep any downloaded temp files alive.
645 DCHECK(!completed_bridge_
.get());
646 completed_bridge_
.swap(bridge_
);
649 if (error_code
!= net::OK
) {
650 client_
->didFail(loader_
, CreateError(request_
.url(),
654 client_
->didFinishLoading(
655 loader_
, (completion_time
- TimeTicks()).InSecondsF(),
656 total_transfer_size
);
661 bool WebURLLoaderImpl::Context::CanHandleDataURL(const GURL
& url
) const {
662 DCHECK(url
.SchemeIs("data"));
664 // Optimize for the case where we can handle a data URL locally. We must
665 // skip this for data URLs targetted at frames since those could trigger a
668 // NOTE: We special case MIME types we can render both for performance
669 // reasons as well as to support unit tests, which do not have an underlying
670 // ResourceLoaderBridge implementation.
672 #if defined(OS_ANDROID)
673 // For compatibility reasons on Android we need to expose top-level data://
675 if (request_
.targetType() == WebURLRequest::TargetIsMainFrame
)
679 if (request_
.targetType() != WebURLRequest::TargetIsMainFrame
&&
680 request_
.targetType() != WebURLRequest::TargetIsSubframe
)
683 std::string mime_type
, unused_charset
;
684 if (net::DataURL::Parse(url
, &mime_type
, &unused_charset
, NULL
) &&
685 net::IsSupportedMimeType(mime_type
))
691 void WebURLLoaderImpl::Context::HandleDataURL() {
692 ResourceResponseInfo info
;
696 if (GetInfoFromDataURL(request_
.url(), &info
, &data
, &error_code
)) {
697 OnReceivedResponse(info
);
699 OnReceivedData(data
.data(), data
.size(), 0);
702 OnCompletedRequest(error_code
, false, false, info
.security_info
,
703 base::TimeTicks::Now(), 0);
706 // WebURLLoaderImpl -----------------------------------------------------------
708 WebURLLoaderImpl::WebURLLoaderImpl(ResourceDispatcher
* resource_dispatcher
)
709 : context_(new Context(this, resource_dispatcher
)) {
712 WebURLLoaderImpl::~WebURLLoaderImpl() {
716 WebURLError
WebURLLoaderImpl::CreateError(const WebURL
& unreachable_url
,
717 bool stale_copy_in_cache
,
720 error
.domain
= WebString::fromUTF8(net::kErrorDomain
);
721 error
.reason
= reason
;
722 error
.unreachableURL
= unreachable_url
;
723 error
.staleCopyInCache
= stale_copy_in_cache
;
724 if (reason
== net::ERR_ABORTED
) {
725 error
.isCancellation
= true;
726 } else if (reason
== net::ERR_TEMPORARILY_THROTTLED
) {
727 error
.localizedDescription
= WebString::fromUTF8(
728 kThrottledErrorDescription
);
730 error
.localizedDescription
= WebString::fromUTF8(
731 net::ErrorToString(reason
));
736 void WebURLLoaderImpl::PopulateURLResponse(const GURL
& url
,
737 const ResourceResponseInfo
& info
,
738 WebURLResponse
* response
) {
739 response
->setURL(url
);
740 response
->setResponseTime(info
.response_time
.ToDoubleT());
741 response
->setMIMEType(WebString::fromUTF8(info
.mime_type
));
742 response
->setTextEncodingName(WebString::fromUTF8(info
.charset
));
743 response
->setExpectedContentLength(info
.content_length
);
744 response
->setSecurityInfo(info
.security_info
);
745 response
->setAppCacheID(info
.appcache_id
);
746 response
->setAppCacheManifestURL(info
.appcache_manifest_url
);
747 response
->setWasCached(!info
.load_timing
.request_start_time
.is_null() &&
748 info
.response_time
< info
.load_timing
.request_start_time
);
749 response
->setRemoteIPAddress(
750 WebString::fromUTF8(info
.socket_address
.host()));
751 response
->setRemotePort(info
.socket_address
.port());
752 response
->setConnectionID(info
.load_timing
.socket_log_id
);
753 response
->setConnectionReused(info
.load_timing
.socket_reused
);
754 response
->setDownloadFilePath(info
.download_file_path
.AsUTF16Unsafe());
755 WebURLResponseExtraDataImpl
* extra_data
=
756 new WebURLResponseExtraDataImpl(info
.npn_negotiated_protocol
);
757 response
->setExtraData(extra_data
);
758 extra_data
->set_was_fetched_via_spdy(info
.was_fetched_via_spdy
);
759 extra_data
->set_was_npn_negotiated(info
.was_npn_negotiated
);
760 extra_data
->set_was_alternate_protocol_available(
761 info
.was_alternate_protocol_available
);
762 extra_data
->set_connection_info(info
.connection_info
);
763 extra_data
->set_was_fetched_via_proxy(info
.was_fetched_via_proxy
);
765 // If there's no received headers end time, don't set load timing. This is
766 // the case for non-HTTP requests, requests that don't go over the wire, and
767 // certain error cases.
768 if (!info
.load_timing
.receive_headers_end
.is_null()) {
769 WebURLLoadTiming timing
;
770 PopulateURLLoadTiming(info
.load_timing
, &timing
);
771 response
->setLoadTiming(timing
);
774 if (info
.devtools_info
.get()) {
775 WebHTTPLoadInfo load_info
;
777 load_info
.setHTTPStatusCode(info
.devtools_info
->http_status_code
);
778 load_info
.setHTTPStatusText(WebString::fromLatin1(
779 info
.devtools_info
->http_status_text
));
780 load_info
.setEncodedDataLength(info
.encoded_data_length
);
782 load_info
.setRequestHeadersText(WebString::fromLatin1(
783 info
.devtools_info
->request_headers_text
));
784 load_info
.setResponseHeadersText(WebString::fromLatin1(
785 info
.devtools_info
->response_headers_text
));
786 const HeadersVector
& request_headers
= info
.devtools_info
->request_headers
;
787 for (HeadersVector::const_iterator it
= request_headers
.begin();
788 it
!= request_headers
.end(); ++it
) {
789 load_info
.addRequestHeader(WebString::fromLatin1(it
->first
),
790 WebString::fromLatin1(it
->second
));
792 const HeadersVector
& response_headers
=
793 info
.devtools_info
->response_headers
;
794 for (HeadersVector::const_iterator it
= response_headers
.begin();
795 it
!= response_headers
.end(); ++it
) {
796 load_info
.addResponseHeader(WebString::fromLatin1(it
->first
),
797 WebString::fromLatin1(it
->second
));
799 response
->setHTTPLoadInfo(load_info
);
802 const net::HttpResponseHeaders
* headers
= info
.headers
.get();
806 WebURLResponse::HTTPVersion version
= WebURLResponse::Unknown
;
807 if (headers
->GetHttpVersion() == net::HttpVersion(0, 9))
808 version
= WebURLResponse::HTTP_0_9
;
809 else if (headers
->GetHttpVersion() == net::HttpVersion(1, 0))
810 version
= WebURLResponse::HTTP_1_0
;
811 else if (headers
->GetHttpVersion() == net::HttpVersion(1, 1))
812 version
= WebURLResponse::HTTP_1_1
;
813 response
->setHTTPVersion(version
);
814 response
->setHTTPStatusCode(headers
->response_code());
815 response
->setHTTPStatusText(WebString::fromLatin1(headers
->GetStatusText()));
817 // TODO(darin): We should leverage HttpResponseHeaders for this, and this
818 // should be using the same code as ResourceDispatcherHost.
819 // TODO(jungshik): Figure out the actual value of the referrer charset and
820 // pass it to GetSuggestedFilename.
822 headers
->EnumerateHeader(NULL
, "content-disposition", &value
);
823 response
->setSuggestedFileName(
824 net::GetSuggestedFilename(url
,
826 std::string(), // referrer_charset
827 std::string(), // suggested_name
828 std::string(), // mime_type
829 std::string())); // default_name
832 if (headers
->GetLastModifiedValue(&time_val
))
833 response
->setLastModifiedDate(time_val
.ToDoubleT());
835 // Build up the header map.
838 while (headers
->EnumerateHeaderLines(&iter
, &name
, &value
)) {
839 response
->addHTTPHeaderField(WebString::fromLatin1(name
),
840 WebString::fromLatin1(value
));
844 void WebURLLoaderImpl::loadSynchronously(const WebURLRequest
& request
,
845 WebURLResponse
& response
,
848 SyncLoadResponse sync_load_response
;
849 context_
->Start(request
, &sync_load_response
);
851 const GURL
& final_url
= sync_load_response
.url
;
853 // TODO(tc): For file loads, we may want to include a more descriptive
854 // status code or status text.
855 int error_code
= sync_load_response
.error_code
;
856 if (error_code
!= net::OK
) {
857 response
.setURL(final_url
);
858 error
.domain
= WebString::fromUTF8(net::kErrorDomain
);
859 error
.reason
= error_code
;
860 error
.unreachableURL
= final_url
;
864 PopulateURLResponse(final_url
, sync_load_response
, &response
);
866 data
.assign(sync_load_response
.data
.data(),
867 sync_load_response
.data
.size());
870 void WebURLLoaderImpl::loadAsynchronously(const WebURLRequest
& request
,
871 WebURLLoaderClient
* client
) {
872 DCHECK(!context_
->client());
874 context_
->set_client(client
);
875 context_
->Start(request
, NULL
);
878 void WebURLLoaderImpl::cancel() {
882 void WebURLLoaderImpl::setDefersLoading(bool value
) {
883 context_
->SetDefersLoading(value
);
886 void WebURLLoaderImpl::didChangePriority(WebURLRequest::Priority new_priority
,
887 int intra_priority_value
) {
888 context_
->DidChangePriority(new_priority
, intra_priority_value
);
891 bool WebURLLoaderImpl::attachThreadedDataReceiver(
892 blink::WebThreadedDataReceiver
* threaded_data_receiver
) {
893 return context_
->AttachThreadedDataReceiver(threaded_data_receiver
);
896 } // namespace content