Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / content / child / web_url_loader_impl.cc
blobba560b65593dff68bbdce1f7e24b8028acd8cb12
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"
9 #include "base/bind.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"
44 using base::Time;
45 using base::TimeTicks;
46 using blink::WebData;
47 using blink::WebHTTPBody;
48 using blink::WebHTTPHeaderVisitor;
49 using blink::WebHTTPLoadInfo;
50 using blink::WebReferrerPolicy;
51 using blink::WebSecurityPolicy;
52 using blink::WebString;
53 using blink::WebURL;
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;
62 namespace content {
64 // Utilities ------------------------------------------------------------------
66 namespace {
68 const char kThrottledErrorDescription[] =
69 "Request throttled. Visit http://dev.chromium.org/throttling for more "
70 "information.";
72 class HeaderFlattener : public WebHTTPHeaderVisitor {
73 public:
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"))
84 return;
86 if (LowerCaseEqualsASCII(name_latin1, "accept"))
87 has_accept_header_ = true;
89 if (!buffer_.empty())
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_) {
98 if (!buffer_.empty())
99 buffer_.append("\r\n");
100 buffer_.append("Accept: */*");
101 has_accept_header_ = true;
103 return buffer_;
106 private:
107 std::string buffer_;
108 bool has_accept_header_;
111 // Extracts the information from a data: url.
112 bool GetInfoFromDataURL(const GURL& url,
113 ResourceResponseInfo* info,
114 std::string* data,
115 int* error_code) {
116 std::string mime_type;
117 std::string charset;
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;
133 return true;
136 *error_code = net::ERR_INVALID_URL;
137 return false;
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) {
177 switch (priority) {
178 case WebURLRequest::PriorityVeryHigh:
179 return net::HIGHEST;
181 case WebURLRequest::PriorityHigh:
182 return net::MEDIUM;
184 case WebURLRequest::PriorityMedium:
185 return net::LOW;
187 case WebURLRequest::PriorityLow:
188 return net::LOWEST;
190 case WebURLRequest::PriorityVeryLow:
191 return net::IDLE;
193 case WebURLRequest::PriorityUnresolved:
194 default:
195 NOTREACHED();
196 return net::LOW;
200 } // namespace
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>,
208 public RequestPeer {
209 public:
210 Context(WebURLLoaderImpl* loader, ResourceDispatcher* resource_dispatcher);
212 WebURLLoaderClient* client() const { return client_; }
213 void set_client(WebURLLoaderClient* client) { client_ = client; }
215 void Cancel();
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,
231 int data_length,
232 int encoded_data_length) OVERRIDE;
233 virtual void OnReceivedCachedMetadata(const char* data, int len) OVERRIDE;
234 virtual void OnCompletedRequest(
235 int error_code,
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;
242 private:
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)
263 : loader_(loader),
264 client_(NULL),
265 resource_dispatcher_(resource_dispatcher),
266 referrer_policy_(blink::WebReferrerPolicyDefault) {
269 void WebURLLoaderImpl::Context::Cancel() {
270 if (bridge_) {
271 bridge_->Cancel();
272 bridge_.reset();
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.
284 client_ = NULL;
285 loader_ = NULL;
288 void WebURLLoaderImpl::Context::SetDefersLoading(bool value) {
289 if (bridge_)
290 bridge_->SetDefersLoading(value);
293 void WebURLLoaderImpl::Context::DidChangePriority(
294 WebURLRequest::Priority new_priority, int intra_priority_value) {
295 if (bridge_)
296 bridge_->DidChangePriority(
297 ConvertWebKitPriorityToNetPriority(new_priority), intra_priority_value);
300 bool WebURLLoaderImpl::Context::AttachThreadedDataReceiver(
301 blink::WebThreadedDataReceiver* threaded_data_receiver) {
302 if (bridge_)
303 return bridge_->AttachThreadedDataReceiver(threaded_data_receiver);
305 return false;
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;
319 std::string data;
320 GetInfoFromDataURL(sync_load_response->url, sync_load_response,
321 &sync_load_response->data,
322 &sync_load_response->error_code);
323 } else {
324 base::MessageLoop::current()->PostTask(
325 FROM_HERE, base::Bind(&Context::HandleDataURL, this));
327 return;
330 GURL referrer_url(
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;
339 break;
340 case WebURLRequest::ReloadBypassingCache:
341 load_flags |= net::LOAD_BYPASS_CACHE;
342 break;
343 case WebURLRequest::ReturnCacheDataElseLoad:
344 load_flags |= net::LOAD_PREFERRING_CACHE;
345 break;
346 case WebURLRequest::ReturnCacheDataDontLoad:
347 load_flags |= net::LOAD_ONLY_FROM_CACHE;
348 break;
349 case WebURLRequest::UseProtocolCachePolicy:
350 break;
351 default:
352 NOTREACHED();
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();
407 size_t i = 0;
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()));
419 break;
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());
425 } else {
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));
432 break;
433 case WebHTTPBody::Element::TypeFileSystemURL: {
434 GURL file_system_url = element.fileSystemURL;
435 DCHECK(file_system_url.SchemeIsFileSystem());
436 request_body->AppendFileSystemFileRange(
437 file_system_url,
438 static_cast<uint64>(element.fileStart),
439 static_cast<uint64>(element.fileLength),
440 base::Time::FromDoubleT(element.modificationTime));
441 break;
443 case WebHTTPBody::Element::TypeBlob:
444 request_body->AppendBlob(element.blobUUID.utf8());
445 break;
446 default:
447 NOTREACHED();
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);
456 return;
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))
463 bridge_.reset();
466 void WebURLLoaderImpl::Context::OnUploadProgress(uint64 position, uint64 size) {
467 if (client_)
468 client_->didSendData(loader_, position, size);
471 bool WebURLLoaderImpl::Context::OnReceivedRedirect(
472 const net::RedirectInfo& redirect_info,
473 const ResourceResponseInfo& info) {
474 if (!client_)
475 return false;
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),
489 referrer_policy_);
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());
509 return true;
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());
515 return false;
518 void WebURLLoaderImpl::Context::OnReceivedResponse(
519 const ResourceResponseInfo& info) {
520 if (!client_)
521 return;
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");
539 } else {
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
547 // it.
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.
553 if (!client_)
554 return;
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;
563 std::string charset;
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" &&
577 !show_raw_listing) {
578 ftp_listing_delegate_.reset(
579 new FtpDirectoryListingResponseDelegate(client_, loader_, response));
583 void WebURLLoaderImpl::Context::OnDownloadedData(int len,
584 int encoded_data_length) {
585 if (client_)
586 client_->didDownloadData(loader_, len, encoded_data_length);
589 void WebURLLoaderImpl::Context::OnReceivedData(const char* data,
590 int data_length,
591 int encoded_data_length) {
592 if (!client_)
593 return;
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);
609 } else {
610 client_->didReceiveData(loader_, data, data_length, encoded_data_length);
614 void WebURLLoaderImpl::Context::OnReceivedCachedMetadata(
615 const char* data, int len) {
616 if (client_)
617 client_->didReceiveCachedMetadata(loader_, data, len);
620 void WebURLLoaderImpl::Context::OnCompletedRequest(
621 int error_code,
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_);
646 if (client_) {
647 if (error_code != net::OK) {
648 client_->didFail(loader_, CreateError(request_.url(),
649 stale_copy_in_cache,
650 error_code));
651 } else {
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
664 // download.
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://
672 // to the browser.
673 if (request_.frameType() == WebURLRequest::FrameTypeTopLevel)
674 return false;
675 #endif
677 if (request_.frameType() != WebURLRequest::FrameTypeTopLevel &&
678 request_.frameType() != WebURLRequest::FrameTypeNested)
679 return true;
681 std::string mime_type, unused_charset;
682 if (net::DataURL::Parse(url, &mime_type, &unused_charset, NULL) &&
683 net::IsSupportedMimeType(mime_type))
684 return true;
686 return false;
689 void WebURLLoaderImpl::Context::HandleDataURL() {
690 ResourceResponseInfo info;
691 int error_code;
692 std::string data;
694 if (GetInfoFromDataURL(request_.url(), &info, &data, &error_code)) {
695 OnReceivedResponse(info);
696 if (!data.empty())
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() {
711 cancel();
714 WebURLError WebURLLoaderImpl::CreateError(const WebURL& unreachable_url,
715 bool stale_copy_in_cache,
716 int reason) {
717 WebURLError error;
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);
727 } else {
728 error.localizedDescription = WebString::fromUTF8(
729 net::ErrorToString(reason));
731 return error;
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();
802 if (!headers)
803 return;
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.
820 std::string value;
821 headers->EnumerateHeader(NULL, "content-disposition", &value);
822 response->setSuggestedFileName(
823 net::GetSuggestedFilename(url,
824 value,
825 std::string(), // referrer_charset
826 std::string(), // suggested_name
827 std::string(), // mime_type
828 std::string())); // default_name
830 Time time_val;
831 if (headers->GetLastModifiedValue(&time_val))
832 response->setLastModifiedDate(time_val.ToDoubleT());
834 // Build up the header map.
835 void* iter = NULL;
836 std::string name;
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,
845 WebURLError& error,
846 WebData& data) {
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;
860 return;
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() {
878 context_->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