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/child/web_url_request_util.h"
22 #include "content/child/weburlresponse_extradata_impl.h"
23 #include "content/common/resource_request_body.h"
24 #include "content/public/child/request_peer.h"
25 #include "net/base/data_url.h"
26 #include "net/base/filename_util.h"
27 #include "net/base/load_flags.h"
28 #include "net/base/mime_util.h"
29 #include "net/base/net_errors.h"
30 #include "net/http/http_response_headers.h"
31 #include "net/http/http_util.h"
32 #include "net/url_request/redirect_info.h"
33 #include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
34 #include "third_party/WebKit/public/platform/WebHTTPLoadInfo.h"
35 #include "third_party/WebKit/public/platform/WebURL.h"
36 #include "third_party/WebKit/public/platform/WebURLError.h"
37 #include "third_party/WebKit/public/platform/WebURLLoadTiming.h"
38 #include "third_party/WebKit/public/platform/WebURLLoaderClient.h"
39 #include "third_party/WebKit/public/platform/WebURLRequest.h"
40 #include "third_party/WebKit/public/platform/WebURLResponse.h"
41 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
42 #include "webkit/child/resource_loader_bridge.h"
45 using base::TimeTicks
;
47 using blink::WebHTTPBody
;
48 using blink::WebHTTPHeaderVisitor
;
49 using blink::WebHTTPLoadInfo
;
50 using blink::WebReferrerPolicy
;
51 using blink::WebSecurityPolicy
;
52 using blink::WebString
;
54 using blink::WebURLError
;
55 using blink::WebURLLoadTiming
;
56 using blink::WebURLLoader
;
57 using blink::WebURLLoaderClient
;
58 using blink::WebURLRequest
;
59 using blink::WebURLResponse
;
60 using webkit_glue::ResourceLoaderBridge
;
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 net::RedirectInfo
& redirect_info
,
227 const ResourceResponseInfo
& info
) OVERRIDE
;
228 virtual void OnReceivedResponse(const ResourceResponseInfo
& info
) OVERRIDE
;
229 virtual void OnDownloadedData(int len
, int encoded_data_length
) OVERRIDE
;
230 virtual void OnReceivedData(const char* data
,
232 int encoded_data_length
) OVERRIDE
;
233 virtual void OnReceivedCachedMetadata(const char* data
, int len
) OVERRIDE
;
234 virtual void OnCompletedRequest(
236 bool was_ignored_by_handler
,
237 bool stale_copy_in_cache
,
238 const std::string
& security_info
,
239 const base::TimeTicks
& completion_time
,
240 int64 total_transfer_size
) OVERRIDE
;
243 friend class base::RefCounted
<Context
>;
244 virtual ~Context() {}
246 // We can optimize the handling of data URLs in most cases.
247 bool CanHandleDataURL(const GURL
& url
) const;
248 void HandleDataURL();
250 WebURLLoaderImpl
* loader_
;
251 WebURLRequest request_
;
252 WebURLLoaderClient
* client_
;
253 ResourceDispatcher
* resource_dispatcher_
;
254 WebReferrerPolicy referrer_policy_
;
255 scoped_ptr
<ResourceLoaderBridge
> bridge_
;
256 scoped_ptr
<FtpDirectoryListingResponseDelegate
> ftp_listing_delegate_
;
257 scoped_ptr
<MultipartResponseDelegate
> multipart_delegate_
;
258 scoped_ptr
<ResourceLoaderBridge
> completed_bridge_
;
261 WebURLLoaderImpl::Context::Context(WebURLLoaderImpl
* loader
,
262 ResourceDispatcher
* resource_dispatcher
)
265 resource_dispatcher_(resource_dispatcher
),
266 referrer_policy_(blink::WebReferrerPolicyDefault
) {
269 void WebURLLoaderImpl::Context::Cancel() {
275 // Ensure that we do not notify the multipart delegate anymore as it has
276 // its own pointer to the client.
277 if (multipart_delegate_
)
278 multipart_delegate_
->Cancel();
279 // Ditto for the ftp delegate.
280 if (ftp_listing_delegate_
)
281 ftp_listing_delegate_
->Cancel();
283 // Do not make any further calls to the client.
288 void WebURLLoaderImpl::Context::SetDefersLoading(bool value
) {
290 bridge_
->SetDefersLoading(value
);
293 void WebURLLoaderImpl::Context::DidChangePriority(
294 WebURLRequest::Priority new_priority
, int intra_priority_value
) {
296 bridge_
->DidChangePriority(
297 ConvertWebKitPriorityToNetPriority(new_priority
), intra_priority_value
);
300 bool WebURLLoaderImpl::Context::AttachThreadedDataReceiver(
301 blink::WebThreadedDataReceiver
* threaded_data_receiver
) {
303 return bridge_
->AttachThreadedDataReceiver(threaded_data_receiver
);
308 void WebURLLoaderImpl::Context::Start(const WebURLRequest
& request
,
309 SyncLoadResponse
* sync_load_response
) {
310 DCHECK(!bridge_
.get());
312 request_
= request
; // Save the request.
314 GURL url
= request
.url();
315 if (url
.SchemeIs("data") && CanHandleDataURL(url
)) {
316 if (sync_load_response
) {
317 // This is a sync load. Do the work now.
318 sync_load_response
->url
= url
;
320 GetInfoFromDataURL(sync_load_response
->url
, sync_load_response
,
321 &sync_load_response
->data
,
322 &sync_load_response
->error_code
);
324 base::MessageLoop::current()->PostTask(
325 FROM_HERE
, base::Bind(&Context::HandleDataURL
, this));
331 request
.httpHeaderField(WebString::fromUTF8("Referer")).latin1());
332 const std::string
& method
= request
.httpMethod().latin1();
334 int load_flags
= net::LOAD_NORMAL
;
335 switch (request
.cachePolicy()) {
336 case WebURLRequest::ReloadIgnoringCacheData
:
337 // Required by LayoutTests/http/tests/misc/refresh-headers.php
338 load_flags
|= net::LOAD_VALIDATE_CACHE
;
340 case WebURLRequest::ReloadBypassingCache
:
341 load_flags
|= net::LOAD_BYPASS_CACHE
;
343 case WebURLRequest::ReturnCacheDataElseLoad
:
344 load_flags
|= net::LOAD_PREFERRING_CACHE
;
346 case WebURLRequest::ReturnCacheDataDontLoad
:
347 load_flags
|= net::LOAD_ONLY_FROM_CACHE
;
349 case WebURLRequest::UseProtocolCachePolicy
:
355 if (request
.reportUploadProgress())
356 load_flags
|= net::LOAD_ENABLE_UPLOAD_PROGRESS
;
357 if (request
.reportRawHeaders())
358 load_flags
|= net::LOAD_REPORT_RAW_HEADERS
;
360 if (!request
.allowStoredCredentials()) {
361 load_flags
|= net::LOAD_DO_NOT_SAVE_COOKIES
;
362 load_flags
|= net::LOAD_DO_NOT_SEND_COOKIES
;
365 if (!request
.allowStoredCredentials())
366 load_flags
|= net::LOAD_DO_NOT_SEND_AUTH_DATA
;
368 if (request
.requestContext() == WebURLRequest::RequestContextXMLHttpRequest
&&
369 (url
.has_username() || url
.has_password())) {
370 load_flags
|= net::LOAD_DO_NOT_PROMPT_FOR_LOGIN
;
373 HeaderFlattener flattener
;
374 request
.visitHTTPHeaderFields(&flattener
);
376 // TODO(brettw) this should take parameter encoding into account when
377 // creating the GURLs.
379 RequestInfo request_info
;
380 request_info
.method
= method
;
381 request_info
.url
= url
;
382 request_info
.first_party_for_cookies
= request
.firstPartyForCookies();
383 request_info
.referrer
= referrer_url
;
384 request_info
.headers
= flattener
.GetBuffer();
385 request_info
.load_flags
= load_flags
;
386 request_info
.enable_load_timing
= true;
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
= WebURLRequestToResourceType(request
);
392 request_info
.priority
=
393 ConvertWebKitPriorityToNetPriority(request
.priority());
394 request_info
.appcache_host_id
= request
.appCacheHostID();
395 request_info
.routing_id
= request
.requestorID();
396 request_info
.download_to_file
= request
.downloadToFile();
397 request_info
.has_user_gesture
= request
.hasUserGesture();
398 request_info
.extra_data
= request
.extraData();
399 referrer_policy_
= request
.referrerPolicy();
400 request_info
.referrer_policy
= request
.referrerPolicy();
401 bridge_
.reset(resource_dispatcher_
->CreateBridge(request_info
));
403 if (!request
.httpBody().isNull()) {
404 // GET and HEAD requests shouldn't have http bodies.
405 DCHECK(method
!= "GET" && method
!= "HEAD");
406 const WebHTTPBody
& httpBody
= request
.httpBody();
408 WebHTTPBody::Element element
;
409 scoped_refptr
<ResourceRequestBody
> request_body
= new ResourceRequestBody
;
410 while (httpBody
.elementAt(i
++, element
)) {
411 switch (element
.type
) {
412 case WebHTTPBody::Element::TypeData
:
413 if (!element
.data
.isEmpty()) {
414 // WebKit sometimes gives up empty data to append. These aren't
415 // necessary so we just optimize those out here.
416 request_body
->AppendBytes(
417 element
.data
.data(), static_cast<int>(element
.data
.size()));
420 case WebHTTPBody::Element::TypeFile
:
421 if (element
.fileLength
== -1) {
422 request_body
->AppendFileRange(
423 base::FilePath::FromUTF16Unsafe(element
.filePath
),
424 0, kuint64max
, base::Time());
426 request_body
->AppendFileRange(
427 base::FilePath::FromUTF16Unsafe(element
.filePath
),
428 static_cast<uint64
>(element
.fileStart
),
429 static_cast<uint64
>(element
.fileLength
),
430 base::Time::FromDoubleT(element
.modificationTime
));
433 case WebHTTPBody::Element::TypeFileSystemURL
: {
434 GURL file_system_url
= element
.fileSystemURL
;
435 DCHECK(file_system_url
.SchemeIsFileSystem());
436 request_body
->AppendFileSystemFileRange(
438 static_cast<uint64
>(element
.fileStart
),
439 static_cast<uint64
>(element
.fileLength
),
440 base::Time::FromDoubleT(element
.modificationTime
));
443 case WebHTTPBody::Element::TypeBlob
:
444 request_body
->AppendBlob(element
.blobUUID
.utf8());
450 request_body
->set_identifier(request
.httpBody().identifier());
451 bridge_
->SetRequestBody(request_body
.get());
454 if (sync_load_response
) {
455 bridge_
->SyncLoad(sync_load_response
);
459 // TODO(mmenke): This case probably never happens, anyways. Probably should
460 // not handle this case at all. If it's worth handling, this code currently
461 // results in the request just hanging, which should be fixed.
462 if (!bridge_
->Start(this))
466 void WebURLLoaderImpl::Context::OnUploadProgress(uint64 position
, uint64 size
) {
468 client_
->didSendData(loader_
, position
, size
);
471 bool WebURLLoaderImpl::Context::OnReceivedRedirect(
472 const net::RedirectInfo
& redirect_info
,
473 const ResourceResponseInfo
& info
) {
477 WebURLResponse response
;
478 response
.initialize();
479 PopulateURLResponse(request_
.url(), info
, &response
);
481 // TODO(darin): We lack sufficient information to construct the actual
482 // request that resulted from the redirect.
483 WebURLRequest
new_request(redirect_info
.new_url
);
484 new_request
.setFirstPartyForCookies(
485 redirect_info
.new_first_party_for_cookies
);
486 new_request
.setDownloadToFile(request_
.downloadToFile());
488 new_request
.setHTTPReferrer(WebString::fromUTF8(redirect_info
.new_referrer
),
491 std::string old_method
= request_
.httpMethod().utf8();
492 new_request
.setHTTPMethod(WebString::fromUTF8(redirect_info
.new_method
));
493 if (redirect_info
.new_method
== old_method
)
494 new_request
.setHTTPBody(request_
.httpBody());
496 // Protect from deletion during call to willSendRequest.
497 scoped_refptr
<Context
> protect(this);
499 client_
->willSendRequest(loader_
, new_request
, response
);
500 request_
= new_request
;
502 // Only follow the redirect if WebKit left the URL unmodified.
503 if (redirect_info
.new_url
== GURL(new_request
.url())) {
504 // First-party cookie logic moved from DocumentLoader in Blink to
505 // net::URLRequest in the browser. Assert that Blink didn't try to change it
506 // to something else.
507 DCHECK_EQ(redirect_info
.new_first_party_for_cookies
.spec(),
508 request_
.firstPartyForCookies().string().utf8());
512 // We assume that WebKit only changes the URL to suppress a redirect, and we
513 // assume that it does so by setting it to be invalid.
514 DCHECK(!new_request
.url().isValid());
518 void WebURLLoaderImpl::Context::OnReceivedResponse(
519 const ResourceResponseInfo
& info
) {
523 WebURLResponse response
;
524 response
.initialize();
525 // Updates the request url if the response was fetched by a ServiceWorker,
526 // and it was not generated inside the ServiceWorker.
527 if (info
.was_fetched_via_service_worker
&&
528 !info
.original_url_via_service_worker
.is_empty()) {
529 request_
.setURL(info
.original_url_via_service_worker
);
531 PopulateURLResponse(request_
.url(), info
, &response
);
533 bool show_raw_listing
= (GURL(request_
.url()).query() == "raw");
535 if (info
.mime_type
== "text/vnd.chromium.ftp-dir") {
536 if (show_raw_listing
) {
537 // Set the MIME type to plain text to prevent any active content.
538 response
.setMIMEType("text/plain");
540 // We're going to produce a parsed listing in HTML.
541 response
.setMIMEType("text/html");
545 // Prevent |this| from being destroyed if the client destroys the loader,
546 // ether in didReceiveResponse, or when the multipart/ftp delegate calls into
548 scoped_refptr
<Context
> protect(this);
549 client_
->didReceiveResponse(loader_
, response
);
551 // We may have been cancelled after didReceiveResponse, which would leave us
552 // without a client and therefore without much need to do further handling.
556 DCHECK(!ftp_listing_delegate_
.get());
557 DCHECK(!multipart_delegate_
.get());
558 if (info
.headers
.get() && info
.mime_type
== "multipart/x-mixed-replace") {
559 std::string content_type
;
560 info
.headers
->EnumerateHeader(NULL
, "content-type", &content_type
);
562 std::string mime_type
;
564 bool had_charset
= false;
565 std::string boundary
;
566 net::HttpUtil::ParseContentType(content_type
, &mime_type
, &charset
,
567 &had_charset
, &boundary
);
568 base::TrimString(boundary
, " \"", &boundary
);
570 // If there's no boundary, just handle the request normally. In the gecko
571 // code, nsMultiMixedConv::OnStartRequest throws an exception.
572 if (!boundary
.empty()) {
573 multipart_delegate_
.reset(
574 new MultipartResponseDelegate(client_
, loader_
, response
, boundary
));
576 } else if (info
.mime_type
== "text/vnd.chromium.ftp-dir" &&
578 ftp_listing_delegate_
.reset(
579 new FtpDirectoryListingResponseDelegate(client_
, loader_
, response
));
583 void WebURLLoaderImpl::Context::OnDownloadedData(int len
,
584 int encoded_data_length
) {
586 client_
->didDownloadData(loader_
, len
, encoded_data_length
);
589 void WebURLLoaderImpl::Context::OnReceivedData(const char* data
,
591 int encoded_data_length
) {
595 if (ftp_listing_delegate_
) {
596 // The FTP listing delegate will make the appropriate calls to
597 // client_->didReceiveData and client_->didReceiveResponse. Since the
598 // delegate may want to do work after sending data to the delegate, keep
599 // |this| and the delegate alive until it's finished handling the data.
600 scoped_refptr
<Context
> protect(this);
601 ftp_listing_delegate_
->OnReceivedData(data
, data_length
);
602 } else if (multipart_delegate_
) {
603 // The multipart delegate will make the appropriate calls to
604 // client_->didReceiveData and client_->didReceiveResponse. Since the
605 // delegate may want to do work after sending data to the delegate, keep
606 // |this| and the delegate alive until it's finished handling the data.
607 scoped_refptr
<Context
> protect(this);
608 multipart_delegate_
->OnReceivedData(data
, data_length
, encoded_data_length
);
610 client_
->didReceiveData(loader_
, data
, data_length
, encoded_data_length
);
614 void WebURLLoaderImpl::Context::OnReceivedCachedMetadata(
615 const char* data
, int len
) {
617 client_
->didReceiveCachedMetadata(loader_
, data
, len
);
620 void WebURLLoaderImpl::Context::OnCompletedRequest(
622 bool was_ignored_by_handler
,
623 bool stale_copy_in_cache
,
624 const std::string
& security_info
,
625 const base::TimeTicks
& completion_time
,
626 int64 total_transfer_size
) {
627 // The WebURLLoaderImpl may be deleted in any of the calls to the client or
628 // the delegates below (As they also may call in to the client). Keep |this|
629 // alive in that case, to avoid a crash. If that happens, the request will be
630 // cancelled and |client_| will be set to NULL.
631 scoped_refptr
<Context
> protect(this);
633 if (ftp_listing_delegate_
) {
634 ftp_listing_delegate_
->OnCompletedRequest();
635 ftp_listing_delegate_
.reset(NULL
);
636 } else if (multipart_delegate_
) {
637 multipart_delegate_
->OnCompletedRequest();
638 multipart_delegate_
.reset(NULL
);
641 // Prevent any further IPC to the browser now that we're complete, but
642 // don't delete it to keep any downloaded temp files alive.
643 DCHECK(!completed_bridge_
.get());
644 completed_bridge_
.swap(bridge_
);
647 if (error_code
!= net::OK
) {
648 client_
->didFail(loader_
, CreateError(request_
.url(),
652 client_
->didFinishLoading(
653 loader_
, (completion_time
- TimeTicks()).InSecondsF(),
654 total_transfer_size
);
659 bool WebURLLoaderImpl::Context::CanHandleDataURL(const GURL
& url
) const {
660 DCHECK(url
.SchemeIs("data"));
662 // Optimize for the case where we can handle a data URL locally. We must
663 // skip this for data URLs targetted at frames since those could trigger a
666 // NOTE: We special case MIME types we can render both for performance
667 // reasons as well as to support unit tests, which do not have an underlying
668 // ResourceLoaderBridge implementation.
670 #if defined(OS_ANDROID)
671 // For compatibility reasons on Android we need to expose top-level data://
673 if (request_
.frameType() == WebURLRequest::FrameTypeTopLevel
)
677 if (request_
.frameType() != WebURLRequest::FrameTypeTopLevel
&&
678 request_
.frameType() != WebURLRequest::FrameTypeNested
)
681 std::string mime_type
, unused_charset
;
682 if (net::DataURL::Parse(url
, &mime_type
, &unused_charset
, NULL
) &&
683 net::IsSupportedMimeType(mime_type
))
689 void WebURLLoaderImpl::Context::HandleDataURL() {
690 ResourceResponseInfo info
;
694 if (GetInfoFromDataURL(request_
.url(), &info
, &data
, &error_code
)) {
695 OnReceivedResponse(info
);
697 OnReceivedData(data
.data(), data
.size(), 0);
700 OnCompletedRequest(error_code
, false, false, info
.security_info
,
701 base::TimeTicks::Now(), 0);
704 // WebURLLoaderImpl -----------------------------------------------------------
706 WebURLLoaderImpl::WebURLLoaderImpl(ResourceDispatcher
* resource_dispatcher
)
707 : context_(new Context(this, resource_dispatcher
)) {
710 WebURLLoaderImpl::~WebURLLoaderImpl() {
714 WebURLError
WebURLLoaderImpl::CreateError(const WebURL
& unreachable_url
,
715 bool stale_copy_in_cache
,
718 error
.domain
= WebString::fromUTF8(net::kErrorDomain
);
719 error
.reason
= reason
;
720 error
.unreachableURL
= unreachable_url
;
721 error
.staleCopyInCache
= stale_copy_in_cache
;
722 if (reason
== net::ERR_ABORTED
) {
723 error
.isCancellation
= true;
724 } else if (reason
== net::ERR_TEMPORARILY_THROTTLED
) {
725 error
.localizedDescription
= WebString::fromUTF8(
726 kThrottledErrorDescription
);
728 error
.localizedDescription
= WebString::fromUTF8(
729 net::ErrorToString(reason
));
734 void WebURLLoaderImpl::PopulateURLResponse(const GURL
& url
,
735 const ResourceResponseInfo
& info
,
736 WebURLResponse
* response
) {
737 response
->setURL(url
);
738 response
->setResponseTime(info
.response_time
.ToDoubleT());
739 response
->setMIMEType(WebString::fromUTF8(info
.mime_type
));
740 response
->setTextEncodingName(WebString::fromUTF8(info
.charset
));
741 response
->setExpectedContentLength(info
.content_length
);
742 response
->setSecurityInfo(info
.security_info
);
743 response
->setAppCacheID(info
.appcache_id
);
744 response
->setAppCacheManifestURL(info
.appcache_manifest_url
);
745 response
->setWasCached(!info
.load_timing
.request_start_time
.is_null() &&
746 info
.response_time
< info
.load_timing
.request_start_time
);
747 response
->setRemoteIPAddress(
748 WebString::fromUTF8(info
.socket_address
.host()));
749 response
->setRemotePort(info
.socket_address
.port());
750 response
->setConnectionID(info
.load_timing
.socket_log_id
);
751 response
->setConnectionReused(info
.load_timing
.socket_reused
);
752 response
->setDownloadFilePath(info
.download_file_path
.AsUTF16Unsafe());
753 response
->setWasFetchedViaServiceWorker(info
.was_fetched_via_service_worker
);
754 WebURLResponseExtraDataImpl
* extra_data
=
755 new WebURLResponseExtraDataImpl(info
.npn_negotiated_protocol
);
756 response
->setExtraData(extra_data
);
757 extra_data
->set_was_fetched_via_spdy(info
.was_fetched_via_spdy
);
758 extra_data
->set_was_npn_negotiated(info
.was_npn_negotiated
);
759 extra_data
->set_was_alternate_protocol_available(
760 info
.was_alternate_protocol_available
);
761 extra_data
->set_connection_info(info
.connection_info
);
762 extra_data
->set_was_fetched_via_proxy(info
.was_fetched_via_proxy
);
764 // If there's no received headers end time, don't set load timing. This is
765 // the case for non-HTTP requests, requests that don't go over the wire, and
766 // certain error cases.
767 if (!info
.load_timing
.receive_headers_end
.is_null()) {
768 WebURLLoadTiming timing
;
769 PopulateURLLoadTiming(info
.load_timing
, &timing
);
770 response
->setLoadTiming(timing
);
773 if (info
.devtools_info
.get()) {
774 WebHTTPLoadInfo load_info
;
776 load_info
.setHTTPStatusCode(info
.devtools_info
->http_status_code
);
777 load_info
.setHTTPStatusText(WebString::fromLatin1(
778 info
.devtools_info
->http_status_text
));
779 load_info
.setEncodedDataLength(info
.encoded_data_length
);
781 load_info
.setRequestHeadersText(WebString::fromLatin1(
782 info
.devtools_info
->request_headers_text
));
783 load_info
.setResponseHeadersText(WebString::fromLatin1(
784 info
.devtools_info
->response_headers_text
));
785 const HeadersVector
& request_headers
= info
.devtools_info
->request_headers
;
786 for (HeadersVector::const_iterator it
= request_headers
.begin();
787 it
!= request_headers
.end(); ++it
) {
788 load_info
.addRequestHeader(WebString::fromLatin1(it
->first
),
789 WebString::fromLatin1(it
->second
));
791 const HeadersVector
& response_headers
=
792 info
.devtools_info
->response_headers
;
793 for (HeadersVector::const_iterator it
= response_headers
.begin();
794 it
!= response_headers
.end(); ++it
) {
795 load_info
.addResponseHeader(WebString::fromLatin1(it
->first
),
796 WebString::fromLatin1(it
->second
));
798 response
->setHTTPLoadInfo(load_info
);
801 const net::HttpResponseHeaders
* headers
= info
.headers
.get();
805 WebURLResponse::HTTPVersion version
= WebURLResponse::Unknown
;
806 if (headers
->GetHttpVersion() == net::HttpVersion(0, 9))
807 version
= WebURLResponse::HTTP_0_9
;
808 else if (headers
->GetHttpVersion() == net::HttpVersion(1, 0))
809 version
= WebURLResponse::HTTP_1_0
;
810 else if (headers
->GetHttpVersion() == net::HttpVersion(1, 1))
811 version
= WebURLResponse::HTTP_1_1
;
812 response
->setHTTPVersion(version
);
813 response
->setHTTPStatusCode(headers
->response_code());
814 response
->setHTTPStatusText(WebString::fromLatin1(headers
->GetStatusText()));
816 // TODO(darin): We should leverage HttpResponseHeaders for this, and this
817 // should be using the same code as ResourceDispatcherHost.
818 // TODO(jungshik): Figure out the actual value of the referrer charset and
819 // pass it to GetSuggestedFilename.
821 headers
->EnumerateHeader(NULL
, "content-disposition", &value
);
822 response
->setSuggestedFileName(
823 net::GetSuggestedFilename(url
,
825 std::string(), // referrer_charset
826 std::string(), // suggested_name
827 std::string(), // mime_type
828 std::string())); // default_name
831 if (headers
->GetLastModifiedValue(&time_val
))
832 response
->setLastModifiedDate(time_val
.ToDoubleT());
834 // Build up the header map.
837 while (headers
->EnumerateHeaderLines(&iter
, &name
, &value
)) {
838 response
->addHTTPHeaderField(WebString::fromLatin1(name
),
839 WebString::fromLatin1(value
));
843 void WebURLLoaderImpl::loadSynchronously(const WebURLRequest
& request
,
844 WebURLResponse
& response
,
847 SyncLoadResponse sync_load_response
;
848 context_
->Start(request
, &sync_load_response
);
850 const GURL
& final_url
= sync_load_response
.url
;
852 // TODO(tc): For file loads, we may want to include a more descriptive
853 // status code or status text.
854 int error_code
= sync_load_response
.error_code
;
855 if (error_code
!= net::OK
) {
856 response
.setURL(final_url
);
857 error
.domain
= WebString::fromUTF8(net::kErrorDomain
);
858 error
.reason
= error_code
;
859 error
.unreachableURL
= final_url
;
863 PopulateURLResponse(final_url
, sync_load_response
, &response
);
865 data
.assign(sync_load_response
.data
.data(),
866 sync_load_response
.data
.size());
869 void WebURLLoaderImpl::loadAsynchronously(const WebURLRequest
& request
,
870 WebURLLoaderClient
* client
) {
871 DCHECK(!context_
->client());
873 context_
->set_client(client
);
874 context_
->Start(request
, NULL
);
877 void WebURLLoaderImpl::cancel() {
881 void WebURLLoaderImpl::setDefersLoading(bool value
) {
882 context_
->SetDefersLoading(value
);
885 void WebURLLoaderImpl::didChangePriority(WebURLRequest::Priority new_priority
,
886 int intra_priority_value
) {
887 context_
->DidChangePriority(new_priority
, intra_priority_value
);
890 bool WebURLLoaderImpl::attachThreadedDataReceiver(
891 blink::WebThreadedDataReceiver
* threaded_data_receiver
) {
892 return context_
->AttachThreadedDataReceiver(threaded_data_receiver
);
895 } // namespace content