Blink roll 25b6bd3a7a131ffe68d809546ad1a20707915cdc:3a503f41ae42e5b79cfcd2ff10e65afde...
[chromium-blink-merge.git] / content / browser / loader / resource_loader.cc
blob8c11b808682f9122471843a9104a72e6badc5878
1 // Copyright (c) 2012 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 #include "content/browser/loader/resource_loader.h"
7 #include "base/command_line.h"
8 #include "base/message_loop/message_loop.h"
9 #include "base/metrics/histogram.h"
10 #include "base/profiler/scoped_tracker.h"
11 #include "base/time/time.h"
12 #include "content/browser/appcache/appcache_interceptor.h"
13 #include "content/browser/child_process_security_policy_impl.h"
14 #include "content/browser/loader/cross_site_resource_handler.h"
15 #include "content/browser/loader/detachable_resource_handler.h"
16 #include "content/browser/loader/resource_loader_delegate.h"
17 #include "content/browser/loader/resource_request_info_impl.h"
18 #include "content/browser/service_worker/service_worker_request_handler.h"
19 #include "content/browser/ssl/ssl_client_auth_handler.h"
20 #include "content/browser/ssl/ssl_manager.h"
21 #include "content/common/ssl_status_serialization.h"
22 #include "content/public/browser/cert_store.h"
23 #include "content/public/browser/resource_context.h"
24 #include "content/public/browser/resource_dispatcher_host_login_delegate.h"
25 #include "content/public/browser/signed_certificate_timestamp_store.h"
26 #include "content/public/common/content_client.h"
27 #include "content/public/common/content_switches.h"
28 #include "content/public/common/process_type.h"
29 #include "content/public/common/resource_response.h"
30 #include "net/base/io_buffer.h"
31 #include "net/base/load_flags.h"
32 #include "net/http/http_response_headers.h"
33 #include "net/ssl/client_cert_store.h"
34 #include "net/url_request/redirect_info.h"
35 #include "net/url_request/url_request_status.h"
37 using base::TimeDelta;
38 using base::TimeTicks;
40 namespace content {
41 namespace {
43 void PopulateResourceResponse(ResourceRequestInfoImpl* info,
44 net::URLRequest* request,
45 ResourceResponse* response) {
46 response->head.request_time = request->request_time();
47 response->head.response_time = request->response_time();
48 response->head.headers = request->response_headers();
49 request->GetCharset(&response->head.charset);
50 response->head.content_length = request->GetExpectedContentSize();
51 request->GetMimeType(&response->head.mime_type);
52 net::HttpResponseInfo response_info = request->response_info();
53 response->head.was_fetched_via_spdy = response_info.was_fetched_via_spdy;
54 response->head.was_npn_negotiated = response_info.was_npn_negotiated;
55 response->head.npn_negotiated_protocol =
56 response_info.npn_negotiated_protocol;
57 response->head.connection_info = response_info.connection_info;
58 response->head.was_fetched_via_proxy = request->was_fetched_via_proxy();
59 response->head.proxy_server = response_info.proxy_server;
60 response->head.socket_address = request->GetSocketAddress();
61 if (ServiceWorkerRequestHandler* handler =
62 ServiceWorkerRequestHandler::GetHandler(request)) {
63 handler->GetExtraResponseInfo(
64 &response->head.was_fetched_via_service_worker,
65 &response->head.was_fallback_required_by_service_worker,
66 &response->head.original_url_via_service_worker,
67 &response->head.response_type_via_service_worker,
68 &response->head.service_worker_fetch_start,
69 &response->head.service_worker_fetch_ready,
70 &response->head.service_worker_fetch_end);
72 AppCacheInterceptor::GetExtraResponseInfo(
73 request,
74 &response->head.appcache_id,
75 &response->head.appcache_manifest_url);
76 if (info->is_load_timing_enabled())
77 request->GetLoadTimingInfo(&response->head.load_timing);
80 } // namespace
82 ResourceLoader::ResourceLoader(scoped_ptr<net::URLRequest> request,
83 scoped_ptr<ResourceHandler> handler,
84 ResourceLoaderDelegate* delegate)
85 : deferred_stage_(DEFERRED_NONE),
86 request_(request.Pass()),
87 handler_(handler.Pass()),
88 delegate_(delegate),
89 last_upload_position_(0),
90 waiting_for_upload_progress_ack_(false),
91 is_transferring_(false),
92 weak_ptr_factory_(this) {
93 request_->set_delegate(this);
94 handler_->SetController(this);
97 ResourceLoader::~ResourceLoader() {
98 if (login_delegate_.get())
99 login_delegate_->OnRequestCancelled();
100 ssl_client_auth_handler_.reset();
102 // Run ResourceHandler destructor before we tear-down the rest of our state
103 // as the ResourceHandler may want to inspect the URLRequest and other state.
104 handler_.reset();
107 void ResourceLoader::StartRequest() {
108 if (delegate_->HandleExternalProtocol(this, request_->url())) {
109 CancelAndIgnore();
110 return;
113 // Give the handler a chance to delay the URLRequest from being started.
114 bool defer_start = false;
116 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
117 tracked_objects::ScopedTracker tracking_profile(
118 FROM_HERE_WITH_EXPLICIT_FUNCTION(
119 "423948 ResourceLoader::StartRequest"));
121 if (!handler_->OnWillStart(request_->url(), &defer_start)) {
122 Cancel();
123 return;
127 if (defer_start) {
128 deferred_stage_ = DEFERRED_START;
129 } else {
130 StartRequestInternal();
134 void ResourceLoader::CancelRequest(bool from_renderer) {
135 CancelRequestInternal(net::ERR_ABORTED, from_renderer);
138 void ResourceLoader::CancelAndIgnore() {
139 ResourceRequestInfoImpl* info = GetRequestInfo();
140 info->set_was_ignored_by_handler(true);
141 CancelRequest(false);
144 void ResourceLoader::CancelWithError(int error_code) {
145 CancelRequestInternal(error_code, false);
148 void ResourceLoader::ReportUploadProgress() {
149 if (waiting_for_upload_progress_ack_)
150 return; // Send one progress event at a time.
152 net::UploadProgress progress = request_->GetUploadProgress();
153 if (!progress.size())
154 return; // Nothing to upload.
156 if (progress.position() == last_upload_position_)
157 return; // No progress made since last time.
159 const uint64 kHalfPercentIncrements = 200;
160 const TimeDelta kOneSecond = TimeDelta::FromMilliseconds(1000);
162 uint64 amt_since_last = progress.position() - last_upload_position_;
163 TimeDelta time_since_last = TimeTicks::Now() - last_upload_ticks_;
165 bool is_finished = (progress.size() == progress.position());
166 bool enough_new_progress =
167 (amt_since_last > (progress.size() / kHalfPercentIncrements));
168 bool too_much_time_passed = time_since_last > kOneSecond;
170 if (is_finished || enough_new_progress || too_much_time_passed) {
171 ResourceRequestInfoImpl* info = GetRequestInfo();
172 if (info->is_upload_progress_enabled()) {
173 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is
174 // fixed.
175 tracked_objects::ScopedTracker tracking_profile(
176 FROM_HERE_WITH_EXPLICIT_FUNCTION(
177 "423948 ResourceLoader::ReportUploadProgress"));
179 handler_->OnUploadProgress(progress.position(), progress.size());
180 waiting_for_upload_progress_ack_ = true;
182 last_upload_ticks_ = TimeTicks::Now();
183 last_upload_position_ = progress.position();
187 void ResourceLoader::MarkAsTransferring() {
188 CHECK(IsResourceTypeFrame(GetRequestInfo()->GetResourceType()))
189 << "Can only transfer for navigations";
190 is_transferring_ = true;
193 void ResourceLoader::CompleteTransfer() {
194 // Although CrossSiteResourceHandler defers at OnResponseStarted
195 // (DEFERRED_READ), it may be seeing a replay of events via
196 // BufferedResourceHandler, and so the request itself is actually deferred at
197 // a later read stage.
198 DCHECK(DEFERRED_READ == deferred_stage_ ||
199 DEFERRED_RESPONSE_COMPLETE == deferred_stage_);
201 is_transferring_ = false;
202 GetRequestInfo()->cross_site_handler()->ResumeResponse();
205 ResourceRequestInfoImpl* ResourceLoader::GetRequestInfo() {
206 return ResourceRequestInfoImpl::ForRequest(request_.get());
209 void ResourceLoader::ClearLoginDelegate() {
210 login_delegate_ = NULL;
213 void ResourceLoader::OnUploadProgressACK() {
214 waiting_for_upload_progress_ack_ = false;
217 void ResourceLoader::OnReceivedRedirect(net::URLRequest* unused,
218 const net::RedirectInfo& redirect_info,
219 bool* defer) {
220 DCHECK_EQ(request_.get(), unused);
222 VLOG(1) << "OnReceivedRedirect: " << request_->url().spec();
223 DCHECK(request_->status().is_success());
225 ResourceRequestInfoImpl* info = GetRequestInfo();
227 if (info->GetProcessType() != PROCESS_TYPE_PLUGIN &&
228 !ChildProcessSecurityPolicyImpl::GetInstance()->
229 CanRequestURL(info->GetChildID(), redirect_info.new_url)) {
230 VLOG(1) << "Denied unauthorized request for "
231 << redirect_info.new_url.possibly_invalid_spec();
233 // Tell the renderer that this request was disallowed.
234 Cancel();
235 return;
238 delegate_->DidReceiveRedirect(this, redirect_info.new_url);
240 if (delegate_->HandleExternalProtocol(this, redirect_info.new_url)) {
241 // The request is complete so we can remove it.
242 CancelAndIgnore();
243 return;
246 scoped_refptr<ResourceResponse> response(new ResourceResponse());
247 PopulateResourceResponse(info, request_.get(), response.get());
249 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
250 tracked_objects::ScopedTracker tracking_profile(
251 FROM_HERE_WITH_EXPLICIT_FUNCTION(
252 "423948 ResourceLoader::OnReceivedRedirect"));
254 if (!handler_->OnRequestRedirected(redirect_info, response.get(), defer)) {
255 Cancel();
256 } else if (*defer) {
257 deferred_stage_ = DEFERRED_REDIRECT; // Follow redirect when resumed.
261 void ResourceLoader::OnAuthRequired(net::URLRequest* unused,
262 net::AuthChallengeInfo* auth_info) {
263 DCHECK_EQ(request_.get(), unused);
265 if (request_->load_flags() & net::LOAD_DO_NOT_PROMPT_FOR_LOGIN) {
266 request_->CancelAuth();
267 return;
270 // Create a login dialog on the UI thread to get authentication data, or pull
271 // from cache and continue on the IO thread.
273 DCHECK(!login_delegate_.get())
274 << "OnAuthRequired called with login_delegate pending";
275 login_delegate_ = delegate_->CreateLoginDelegate(this, auth_info);
276 if (!login_delegate_.get())
277 request_->CancelAuth();
280 void ResourceLoader::OnCertificateRequested(
281 net::URLRequest* unused,
282 net::SSLCertRequestInfo* cert_info) {
283 DCHECK_EQ(request_.get(), unused);
285 if (request_->load_flags() & net::LOAD_PREFETCH) {
286 request_->Cancel();
287 return;
290 DCHECK(!ssl_client_auth_handler_)
291 << "OnCertificateRequested called with ssl_client_auth_handler pending";
292 ssl_client_auth_handler_.reset(new SSLClientAuthHandler(
293 GetRequestInfo()->GetContext()->CreateClientCertStore(),
294 request_.get(),
295 cert_info,
296 base::Bind(&ResourceLoader::ContinueWithCertificate,
297 weak_ptr_factory_.GetWeakPtr())));
298 ssl_client_auth_handler_->SelectCertificate();
301 void ResourceLoader::OnSSLCertificateError(net::URLRequest* request,
302 const net::SSLInfo& ssl_info,
303 bool fatal) {
304 ResourceRequestInfoImpl* info = GetRequestInfo();
306 int render_process_id;
307 int render_frame_id;
308 if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_id))
309 NOTREACHED();
311 SSLManager::OnSSLCertificateError(
312 weak_ptr_factory_.GetWeakPtr(),
313 info->GetResourceType(),
314 request_->url(),
315 render_process_id,
316 render_frame_id,
317 ssl_info,
318 fatal);
321 void ResourceLoader::OnBeforeNetworkStart(net::URLRequest* unused,
322 bool* defer) {
323 DCHECK_EQ(request_.get(), unused);
325 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
326 tracked_objects::ScopedTracker tracking_profile(
327 FROM_HERE_WITH_EXPLICIT_FUNCTION(
328 "423948 ResourceLoader::OnBeforeNetworkStart"));
330 // Give the handler a chance to delay the URLRequest from using the network.
331 if (!handler_->OnBeforeNetworkStart(request_->url(), defer)) {
332 Cancel();
333 return;
334 } else if (*defer) {
335 deferred_stage_ = DEFERRED_NETWORK_START;
339 void ResourceLoader::OnResponseStarted(net::URLRequest* unused) {
340 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
341 tracked_objects::ScopedTracker tracking_profile(
342 FROM_HERE_WITH_EXPLICIT_FUNCTION(
343 "423948 ResourceLoader::OnResponseStarted"));
345 DCHECK_EQ(request_.get(), unused);
347 VLOG(1) << "OnResponseStarted: " << request_->url().spec();
349 // The CanLoadPage check should take place after any server redirects have
350 // finished, at the point in time that we know a page will commit in the
351 // renderer process.
352 ResourceRequestInfoImpl* info = GetRequestInfo();
353 ChildProcessSecurityPolicyImpl* policy =
354 ChildProcessSecurityPolicyImpl::GetInstance();
355 if (!policy->CanLoadPage(info->GetChildID(),
356 request_->url(),
357 info->GetResourceType())) {
358 Cancel();
359 return;
362 if (!request_->status().is_success()) {
363 ResponseCompleted();
364 return;
367 // We want to send a final upload progress message prior to sending the
368 // response complete message even if we're waiting for an ack to to a
369 // previous upload progress message.
370 waiting_for_upload_progress_ack_ = false;
371 ReportUploadProgress();
373 CompleteResponseStarted();
375 if (is_deferred())
376 return;
378 if (request_->status().is_success()) {
379 StartReading(false); // Read the first chunk.
380 } else {
381 ResponseCompleted();
385 void ResourceLoader::OnReadCompleted(net::URLRequest* unused, int bytes_read) {
386 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
387 tracked_objects::ScopedTracker tracking_profile(
388 FROM_HERE_WITH_EXPLICIT_FUNCTION(
389 "423948 ResourceLoader::OnReadCompleted"));
391 DCHECK_EQ(request_.get(), unused);
392 VLOG(1) << "OnReadCompleted: \"" << request_->url().spec() << "\""
393 << " bytes_read = " << bytes_read;
395 // bytes_read == -1 always implies an error.
396 if (bytes_read == -1 || !request_->status().is_success()) {
397 ResponseCompleted();
398 return;
401 CompleteRead(bytes_read);
403 // If the handler cancelled or deferred the request, do not continue
404 // processing the read. If cancelled, the URLRequest has already been
405 // cancelled and will schedule an erroring OnReadCompleted later. If deferred,
406 // do nothing until resumed.
408 // Note: if bytes_read is 0 (EOF) and the handler defers, resumption will call
409 // ResponseCompleted().
410 if (is_deferred() || !request_->status().is_success())
411 return;
413 if (bytes_read > 0) {
414 StartReading(true); // Read the next chunk.
415 } else {
416 // URLRequest reported an EOF. Call ResponseCompleted.
417 DCHECK_EQ(0, bytes_read);
418 ResponseCompleted();
422 void ResourceLoader::CancelSSLRequest(int error,
423 const net::SSLInfo* ssl_info) {
424 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
426 // The request can be NULL if it was cancelled by the renderer (as the
427 // request of the user navigating to a new page from the location bar).
428 if (!request_->is_pending())
429 return;
430 DVLOG(1) << "CancelSSLRequest() url: " << request_->url().spec();
432 if (ssl_info) {
433 request_->CancelWithSSLError(error, *ssl_info);
434 } else {
435 request_->CancelWithError(error);
439 void ResourceLoader::ContinueSSLRequest() {
440 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
442 DVLOG(1) << "ContinueSSLRequest() url: " << request_->url().spec();
444 request_->ContinueDespiteLastError();
447 void ResourceLoader::Resume() {
448 DCHECK(!is_transferring_);
450 DeferredStage stage = deferred_stage_;
451 deferred_stage_ = DEFERRED_NONE;
452 switch (stage) {
453 case DEFERRED_NONE:
454 NOTREACHED();
455 break;
456 case DEFERRED_START:
457 StartRequestInternal();
458 break;
459 case DEFERRED_NETWORK_START:
460 request_->ResumeNetworkStart();
461 break;
462 case DEFERRED_REDIRECT:
463 request_->FollowDeferredRedirect();
464 break;
465 case DEFERRED_READ:
466 base::MessageLoop::current()->PostTask(
467 FROM_HERE,
468 base::Bind(&ResourceLoader::ResumeReading,
469 weak_ptr_factory_.GetWeakPtr()));
470 break;
471 case DEFERRED_RESPONSE_COMPLETE:
472 base::MessageLoop::current()->PostTask(
473 FROM_HERE,
474 base::Bind(&ResourceLoader::ResponseCompleted,
475 weak_ptr_factory_.GetWeakPtr()));
476 break;
477 case DEFERRED_FINISH:
478 // Delay self-destruction since we don't know how we were reached.
479 base::MessageLoop::current()->PostTask(
480 FROM_HERE,
481 base::Bind(&ResourceLoader::CallDidFinishLoading,
482 weak_ptr_factory_.GetWeakPtr()));
483 break;
487 void ResourceLoader::Cancel() {
488 CancelRequest(false);
491 void ResourceLoader::StartRequestInternal() {
492 DCHECK(!request_->is_pending());
494 if (!request_->status().is_success()) {
495 return;
498 request_->Start();
500 delegate_->DidStartRequest(this);
503 void ResourceLoader::CancelRequestInternal(int error, bool from_renderer) {
504 VLOG(1) << "CancelRequestInternal: " << request_->url().spec();
506 ResourceRequestInfoImpl* info = GetRequestInfo();
508 // WebKit will send us a cancel for downloads since it no longer handles
509 // them. In this case, ignore the cancel since we handle downloads in the
510 // browser.
511 if (from_renderer && (info->IsDownload() || info->is_stream()))
512 return;
514 if (from_renderer && info->detachable_handler()) {
515 // TODO(davidben): Fix Blink handling of prefetches so they are not
516 // cancelled on navigate away and end up in the local cache.
517 info->detachable_handler()->Detach();
518 return;
521 // TODO(darin): Perhaps we should really be looking to see if the status is
522 // IO_PENDING?
523 bool was_pending = request_->is_pending();
525 if (login_delegate_.get()) {
526 login_delegate_->OnRequestCancelled();
527 login_delegate_ = NULL;
529 ssl_client_auth_handler_.reset();
531 request_->CancelWithError(error);
533 if (!was_pending) {
534 // If the request isn't in flight, then we won't get an asynchronous
535 // notification from the request, so we have to signal ourselves to finish
536 // this request.
537 base::MessageLoop::current()->PostTask(
538 FROM_HERE,
539 base::Bind(&ResourceLoader::ResponseCompleted,
540 weak_ptr_factory_.GetWeakPtr()));
544 void ResourceLoader::StoreSignedCertificateTimestamps(
545 const net::SignedCertificateTimestampAndStatusList& sct_list,
546 int process_id,
547 SignedCertificateTimestampIDStatusList* sct_ids) {
548 SignedCertificateTimestampStore* sct_store(
549 SignedCertificateTimestampStore::GetInstance());
551 for (net::SignedCertificateTimestampAndStatusList::const_iterator iter =
552 sct_list.begin(); iter != sct_list.end(); ++iter) {
553 const int sct_id(sct_store->Store(iter->sct.get(), process_id));
554 sct_ids->push_back(
555 SignedCertificateTimestampIDAndStatus(sct_id, iter->status));
559 void ResourceLoader::CompleteResponseStarted() {
560 ResourceRequestInfoImpl* info = GetRequestInfo();
562 scoped_refptr<ResourceResponse> response(new ResourceResponse());
563 PopulateResourceResponse(info, request_.get(), response.get());
565 if (request_->ssl_info().cert.get()) {
566 int cert_id = CertStore::GetInstance()->StoreCert(
567 request_->ssl_info().cert.get(), info->GetChildID());
569 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
570 StoreSignedCertificateTimestamps(
571 request_->ssl_info().signed_certificate_timestamps,
572 info->GetChildID(),
573 &signed_certificate_timestamp_ids);
575 response->head.security_info = SerializeSecurityInfo(
576 cert_id,
577 request_->ssl_info().cert_status,
578 request_->ssl_info().security_bits,
579 request_->ssl_info().connection_status,
580 signed_certificate_timestamp_ids);
581 } else {
582 // We should not have any SSL state.
583 DCHECK(!request_->ssl_info().cert_status &&
584 request_->ssl_info().security_bits == -1 &&
585 !request_->ssl_info().connection_status);
588 delegate_->DidReceiveResponse(this);
590 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
591 tracked_objects::ScopedTracker tracking_profile(
592 FROM_HERE_WITH_EXPLICIT_FUNCTION(
593 "423948 ResourceLoader::CompleteResponseStarted"));
595 bool defer = false;
596 if (!handler_->OnResponseStarted(response.get(), &defer)) {
597 Cancel();
598 } else if (defer) {
599 read_deferral_start_time_ = base::TimeTicks::Now();
600 deferred_stage_ = DEFERRED_READ; // Read first chunk when resumed.
604 void ResourceLoader::StartReading(bool is_continuation) {
605 int bytes_read = 0;
606 ReadMore(&bytes_read);
608 // If IO is pending, wait for the URLRequest to call OnReadCompleted.
609 if (request_->status().is_io_pending())
610 return;
612 if (!is_continuation || bytes_read <= 0) {
613 OnReadCompleted(request_.get(), bytes_read);
614 } else {
615 // Else, trigger OnReadCompleted asynchronously to avoid starving the IO
616 // thread in case the URLRequest can provide data synchronously.
617 base::MessageLoop::current()->PostTask(
618 FROM_HERE,
619 base::Bind(&ResourceLoader::OnReadCompleted,
620 weak_ptr_factory_.GetWeakPtr(),
621 request_.get(),
622 bytes_read));
626 void ResourceLoader::ResumeReading() {
627 DCHECK(!is_deferred());
629 if (!read_deferral_start_time_.is_null()) {
630 UMA_HISTOGRAM_TIMES("Net.ResourceLoader.ReadDeferral",
631 base::TimeTicks::Now() - read_deferral_start_time_);
632 read_deferral_start_time_ = base::TimeTicks();
634 if (request_->status().is_success()) {
635 StartReading(false); // Read the next chunk (OK to complete synchronously).
636 } else {
637 ResponseCompleted();
641 void ResourceLoader::ReadMore(int* bytes_read) {
642 DCHECK(!is_deferred());
644 // Make sure we track the buffer in at least one place. This ensures it gets
645 // deleted even in the case the request has already finished its job and
646 // doesn't use the buffer.
647 scoped_refptr<net::IOBuffer> buf;
648 int buf_size;
650 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
651 tracked_objects::ScopedTracker tracking_profile(
652 FROM_HERE_WITH_EXPLICIT_FUNCTION("423948 ResourceLoader::ReadMore"));
654 if (!handler_->OnWillRead(&buf, &buf_size, -1)) {
655 Cancel();
656 return;
660 DCHECK(buf.get());
661 DCHECK(buf_size > 0);
663 request_->Read(buf.get(), buf_size, bytes_read);
665 // No need to check the return value here as we'll detect errors by
666 // inspecting the URLRequest's status.
669 void ResourceLoader::CompleteRead(int bytes_read) {
670 DCHECK(bytes_read >= 0);
671 DCHECK(request_->status().is_success());
673 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
674 tracked_objects::ScopedTracker tracking_profile(
675 FROM_HERE_WITH_EXPLICIT_FUNCTION("423948 ResourceLoader::CompleteRead"));
677 bool defer = false;
678 if (!handler_->OnReadCompleted(bytes_read, &defer)) {
679 Cancel();
680 } else if (defer) {
681 deferred_stage_ =
682 bytes_read > 0 ? DEFERRED_READ : DEFERRED_RESPONSE_COMPLETE;
685 // Note: the request may still have been cancelled while OnReadCompleted
686 // returns true if OnReadCompleted caused request to get cancelled
687 // out-of-band. (In AwResourceDispatcherHostDelegate::DownloadStarting, for
688 // instance.)
691 void ResourceLoader::ResponseCompleted() {
692 VLOG(1) << "ResponseCompleted: " << request_->url().spec();
693 RecordHistograms();
694 ResourceRequestInfoImpl* info = GetRequestInfo();
696 std::string security_info;
697 const net::SSLInfo& ssl_info = request_->ssl_info();
698 if (ssl_info.cert.get() != NULL) {
699 int cert_id = CertStore::GetInstance()->StoreCert(ssl_info.cert.get(),
700 info->GetChildID());
701 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids;
702 StoreSignedCertificateTimestamps(ssl_info.signed_certificate_timestamps,
703 info->GetChildID(),
704 &signed_certificate_timestamp_ids);
706 security_info = SerializeSecurityInfo(
707 cert_id, ssl_info.cert_status, ssl_info.security_bits,
708 ssl_info.connection_status, signed_certificate_timestamp_ids);
711 bool defer = false;
713 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
714 tracked_objects::ScopedTracker tracking_profile(
715 FROM_HERE_WITH_EXPLICIT_FUNCTION(
716 "423948 ResourceLoader::ResponseCompleted"));
718 handler_->OnResponseCompleted(request_->status(), security_info, &defer);
720 if (defer) {
721 // The handler is not ready to die yet. We will call DidFinishLoading when
722 // we resume.
723 deferred_stage_ = DEFERRED_FINISH;
724 } else {
725 // This will result in our destruction.
726 CallDidFinishLoading();
730 void ResourceLoader::CallDidFinishLoading() {
731 delegate_->DidFinishLoading(this);
734 void ResourceLoader::RecordHistograms() {
735 ResourceRequestInfoImpl* info = GetRequestInfo();
737 if (info->GetResourceType() == RESOURCE_TYPE_PREFETCH) {
738 PrefetchStatus status = STATUS_UNDEFINED;
739 TimeDelta total_time = base::TimeTicks::Now() - request_->creation_time();
741 switch (request_->status().status()) {
742 case net::URLRequestStatus::SUCCESS:
743 if (request_->was_cached()) {
744 status = STATUS_SUCCESS_FROM_CACHE;
745 UMA_HISTOGRAM_TIMES("Net.Prefetch.TimeSpentPrefetchingFromCache",
746 total_time);
747 } else {
748 status = STATUS_SUCCESS_FROM_NETWORK;
749 UMA_HISTOGRAM_TIMES("Net.Prefetch.TimeSpentPrefetchingFromNetwork",
750 total_time);
752 break;
753 case net::URLRequestStatus::CANCELED:
754 status = STATUS_CANCELED;
755 UMA_HISTOGRAM_TIMES("Net.Prefetch.TimeBeforeCancel", total_time);
756 break;
757 case net::URLRequestStatus::IO_PENDING:
758 case net::URLRequestStatus::FAILED:
759 status = STATUS_UNDEFINED;
760 break;
763 UMA_HISTOGRAM_ENUMERATION("Net.Prefetch.Pattern", status, STATUS_MAX);
767 void ResourceLoader::ContinueWithCertificate(net::X509Certificate* cert) {
768 ssl_client_auth_handler_.reset();
769 request_->ContinueWithCertificate(cert);
772 } // namespace content