Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / content / browser / loader / resource_dispatcher_host_impl.cc
blob5600a23455fc80f8f2a6592077a78be2babcb165
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 // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading
7 #include "content/browser/loader/resource_dispatcher_host_impl.h"
9 #include <algorithm>
10 #include <set>
11 #include <vector>
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/debug/alias.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/memory/shared_memory.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/metrics/sparse_histogram.h"
24 #include "base/profiler/scoped_tracker.h"
25 #include "base/stl_util.h"
26 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
27 #include "base/time/time.h"
28 #include "content/browser/appcache/appcache_interceptor.h"
29 #include "content/browser/appcache/chrome_appcache_service.h"
30 #include "content/browser/bad_message.h"
31 #include "content/browser/cert_store_impl.h"
32 #include "content/browser/child_process_security_policy_impl.h"
33 #include "content/browser/download/download_resource_handler.h"
34 #include "content/browser/download/save_file_manager.h"
35 #include "content/browser/download/save_file_resource_handler.h"
36 #include "content/browser/fileapi/chrome_blob_storage_context.h"
37 #include "content/browser/frame_host/navigation_request_info.h"
38 #include "content/browser/frame_host/navigator.h"
39 #include "content/browser/loader/async_resource_handler.h"
40 #include "content/browser/loader/cross_site_resource_handler.h"
41 #include "content/browser/loader/detachable_resource_handler.h"
42 #include "content/browser/loader/mime_type_resource_handler.h"
43 #include "content/browser/loader/navigation_resource_handler.h"
44 #include "content/browser/loader/navigation_url_loader_impl_core.h"
45 #include "content/browser/loader/power_save_block_resource_throttle.h"
46 #include "content/browser/loader/redirect_to_file_resource_handler.h"
47 #include "content/browser/loader/resource_message_filter.h"
48 #include "content/browser/loader/resource_request_info_impl.h"
49 #include "content/browser/loader/stream_resource_handler.h"
50 #include "content/browser/loader/sync_resource_handler.h"
51 #include "content/browser/loader/throttling_resource_handler.h"
52 #include "content/browser/loader/upload_data_stream_builder.h"
53 #include "content/browser/renderer_host/render_view_host_delegate.h"
54 #include "content/browser/renderer_host/render_view_host_impl.h"
55 #include "content/browser/resource_context_impl.h"
56 #include "content/browser/service_worker/service_worker_request_handler.h"
57 #include "content/browser/streams/stream.h"
58 #include "content/browser/streams/stream_context.h"
59 #include "content/browser/streams/stream_registry.h"
60 #include "content/browser/web_contents/web_contents_impl.h"
61 #include "content/common/appcache_interfaces.h"
62 #include "content/common/navigation_params.h"
63 #include "content/common/resource_messages.h"
64 #include "content/common/site_isolation_policy.h"
65 #include "content/common/ssl_status_serialization.h"
66 #include "content/common/view_messages.h"
67 #include "content/public/browser/browser_thread.h"
68 #include "content/public/browser/content_browser_client.h"
69 #include "content/public/browser/download_manager.h"
70 #include "content/public/browser/download_url_parameters.h"
71 #include "content/public/browser/global_request_id.h"
72 #include "content/public/browser/plugin_service.h"
73 #include "content/public/browser/resource_dispatcher_host_delegate.h"
74 #include "content/public/browser/resource_request_details.h"
75 #include "content/public/browser/resource_throttle.h"
76 #include "content/public/browser/stream_handle.h"
77 #include "content/public/browser/stream_info.h"
78 #include "content/public/browser/user_metrics.h"
79 #include "content/public/common/content_switches.h"
80 #include "content/public/common/process_type.h"
81 #include "ipc/ipc_message_macros.h"
82 #include "ipc/ipc_message_start.h"
83 #include "net/base/auth.h"
84 #include "net/base/load_flags.h"
85 #include "net/base/mime_util.h"
86 #include "net/base/net_errors.h"
87 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
88 #include "net/base/request_priority.h"
89 #include "net/base/upload_data_stream.h"
90 #include "net/cert/cert_status_flags.h"
91 #include "net/cookies/cookie_monster.h"
92 #include "net/http/http_response_headers.h"
93 #include "net/http/http_response_info.h"
94 #include "net/ssl/ssl_cert_request_info.h"
95 #include "net/url_request/url_request.h"
96 #include "net/url_request/url_request_context.h"
97 #include "net/url_request/url_request_job_factory.h"
98 #include "storage/browser/blob/blob_data_handle.h"
99 #include "storage/browser/blob/blob_storage_context.h"
100 #include "storage/browser/blob/blob_url_request_job_factory.h"
101 #include "storage/browser/blob/shareable_file_reference.h"
102 #include "storage/browser/fileapi/file_permission_policy.h"
103 #include "storage/browser/fileapi/file_system_context.h"
104 #include "url/url_constants.h"
106 using base::Time;
107 using base::TimeDelta;
108 using base::TimeTicks;
109 using storage::ShareableFileReference;
111 // ----------------------------------------------------------------------------
113 namespace content {
115 namespace {
117 static ResourceDispatcherHostImpl* g_resource_dispatcher_host;
119 // The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates
120 const int kUpdateLoadStatesIntervalMsec = 250;
122 // Maximum byte "cost" of all the outstanding requests for a renderer.
123 // See delcaration of |max_outstanding_requests_cost_per_process_| for details.
124 // This bound is 25MB, which allows for around 6000 outstanding requests.
125 const int kMaxOutstandingRequestsCostPerProcess = 26214400;
127 // The number of milliseconds after noting a user gesture that we will
128 // tag newly-created URLRequest objects with the
129 // net::LOAD_MAYBE_USER_GESTURE load flag. This is a fairly arbitrary
130 // guess at how long to expect direct impact from a user gesture, but
131 // this should be OK as the load flag is a best-effort thing only,
132 // rather than being intended as fully accurate.
133 const int kUserGestureWindowMs = 3500;
135 // Ratio of |max_num_in_flight_requests_| that any one renderer is allowed to
136 // use. Arbitrarily chosen.
137 const double kMaxRequestsPerProcessRatio = 0.45;
139 // TODO(jkarlin): The value is high to reduce the chance of the detachable
140 // request timing out, forcing a blocked second request to open a new connection
141 // and start over. Reduce this value once we have a better idea of what it
142 // should be and once we stop blocking multiple simultaneous requests for the
143 // same resource (see bugs 46104 and 31014).
144 const int kDefaultDetachableCancelDelayMs = 30000;
146 enum SHA1HistogramTypes {
147 // SHA-1 is not present in the certificate chain.
148 SHA1_NOT_PRESENT = 0,
149 // SHA-1 is present in the certificate chain, and the leaf expires on or
150 // after January 1, 2017.
151 SHA1_EXPIRES_AFTER_JANUARY_2017 = 1,
152 // SHA-1 is present in the certificate chain, and the leaf expires on or
153 // after June 1, 2016.
154 SHA1_EXPIRES_AFTER_JUNE_2016 = 2,
155 // SHA-1 is present in the certificate chain, and the leaf expires on or
156 // after January 1, 2016.
157 SHA1_EXPIRES_AFTER_JANUARY_2016 = 3,
158 // SHA-1 is present in the certificate chain, but the leaf expires before
159 // January 1, 2016
160 SHA1_PRESENT = 4,
161 // Always keep this at the end.
162 SHA1_HISTOGRAM_TYPES_MAX,
165 void RecordCertificateHistograms(const net::SSLInfo& ssl_info,
166 ResourceType resource_type) {
167 // The internal representation of the dates for UI treatment of SHA-1.
168 // See http://crbug.com/401365 for details
169 static const int64_t kJanuary2017 = INT64_C(13127702400000000);
170 static const int64_t kJune2016 = INT64_C(13109213000000000);
171 static const int64_t kJanuary2016 = INT64_C(13096080000000000);
173 SHA1HistogramTypes sha1_histogram = SHA1_NOT_PRESENT;
174 if (ssl_info.cert_status & net::CERT_STATUS_SHA1_SIGNATURE_PRESENT) {
175 DCHECK(ssl_info.cert.get());
176 if (ssl_info.cert->valid_expiry() >=
177 base::Time::FromInternalValue(kJanuary2017)) {
178 sha1_histogram = SHA1_EXPIRES_AFTER_JANUARY_2017;
179 } else if (ssl_info.cert->valid_expiry() >=
180 base::Time::FromInternalValue(kJune2016)) {
181 sha1_histogram = SHA1_EXPIRES_AFTER_JUNE_2016;
182 } else if (ssl_info.cert->valid_expiry() >=
183 base::Time::FromInternalValue(kJanuary2016)) {
184 sha1_histogram = SHA1_EXPIRES_AFTER_JANUARY_2016;
185 } else {
186 sha1_histogram = SHA1_PRESENT;
189 if (resource_type == RESOURCE_TYPE_MAIN_FRAME) {
190 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.MainFrame",
191 sha1_histogram,
192 SHA1_HISTOGRAM_TYPES_MAX);
193 } else {
194 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.Subresource",
195 sha1_histogram,
196 SHA1_HISTOGRAM_TYPES_MAX);
200 bool IsDetachableResourceType(ResourceType type) {
201 switch (type) {
202 case RESOURCE_TYPE_PREFETCH:
203 case RESOURCE_TYPE_PING:
204 return true;
205 default:
206 return false;
210 // Aborts a request before an URLRequest has actually been created.
211 void AbortRequestBeforeItStarts(ResourceMessageFilter* filter,
212 IPC::Message* sync_result,
213 int request_id) {
214 if (sync_result) {
215 SyncLoadResult result;
216 result.error_code = net::ERR_ABORTED;
217 ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result, result);
218 filter->Send(sync_result);
219 } else {
220 // Tell the renderer that this request was disallowed.
221 ResourceMsg_RequestCompleteData request_complete_data;
222 request_complete_data.error_code = net::ERR_ABORTED;
223 request_complete_data.was_ignored_by_handler = false;
224 request_complete_data.exists_in_cache = false;
225 // No security info needed, connection not established.
226 request_complete_data.completion_time = base::TimeTicks();
227 request_complete_data.encoded_data_length = 0;
228 filter->Send(new ResourceMsg_RequestComplete(
229 request_id, request_complete_data));
233 void SetReferrerForRequest(net::URLRequest* request, const Referrer& referrer) {
234 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
235 if (!referrer.url.is_valid() ||
236 command_line->HasSwitch(switches::kNoReferrers)) {
237 request->SetReferrer(std::string());
238 } else {
239 request->SetReferrer(referrer.url.spec());
242 net::URLRequest::ReferrerPolicy net_referrer_policy =
243 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
244 switch (referrer.policy) {
245 case blink::WebReferrerPolicyAlways:
246 case blink::WebReferrerPolicyNever:
247 case blink::WebReferrerPolicyOrigin:
248 net_referrer_policy = net::URLRequest::NEVER_CLEAR_REFERRER;
249 break;
250 case blink::WebReferrerPolicyNoReferrerWhenDowngrade:
251 net_referrer_policy =
252 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
253 break;
254 case blink::WebReferrerPolicyOriginWhenCrossOrigin:
255 net_referrer_policy =
256 net::URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN;
257 break;
258 case blink::WebReferrerPolicyDefault:
259 default:
260 net_referrer_policy =
261 command_line->HasSwitch(switches::kReducedReferrerGranularity)
262 ? net::URLRequest::
263 REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
264 : net::URLRequest::
265 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
266 break;
268 request->set_referrer_policy(net_referrer_policy);
271 // Consults the RendererSecurity policy to determine whether the
272 // ResourceDispatcherHostImpl should service this request. A request might be
273 // disallowed if the renderer is not authorized to retrieve the request URL or
274 // if the renderer is attempting to upload an unauthorized file.
275 bool ShouldServiceRequest(int process_type,
276 int child_id,
277 const ResourceHostMsg_Request& request_data,
278 storage::FileSystemContext* file_system_context) {
279 if (process_type == PROCESS_TYPE_PLUGIN)
280 return true;
282 ChildProcessSecurityPolicyImpl* policy =
283 ChildProcessSecurityPolicyImpl::GetInstance();
285 // Check if the renderer is permitted to request the requested URL.
286 if (!policy->CanRequestURL(child_id, request_data.url)) {
287 VLOG(1) << "Denied unauthorized request for "
288 << request_data.url.possibly_invalid_spec();
289 return false;
292 // Check if the renderer is permitted to upload the requested files.
293 if (request_data.request_body.get()) {
294 const std::vector<ResourceRequestBody::Element>* uploads =
295 request_data.request_body->elements();
296 std::vector<ResourceRequestBody::Element>::const_iterator iter;
297 for (iter = uploads->begin(); iter != uploads->end(); ++iter) {
298 if (iter->type() == ResourceRequestBody::Element::TYPE_FILE &&
299 !policy->CanReadFile(child_id, iter->path())) {
300 NOTREACHED() << "Denied unauthorized upload of "
301 << iter->path().value();
302 return false;
304 if (iter->type() == ResourceRequestBody::Element::TYPE_FILE_FILESYSTEM) {
305 storage::FileSystemURL url =
306 file_system_context->CrackURL(iter->filesystem_url());
307 if (!policy->CanReadFileSystemFile(child_id, url)) {
308 NOTREACHED() << "Denied unauthorized upload of "
309 << iter->filesystem_url().spec();
310 return false;
316 return true;
319 void RemoveDownloadFileFromChildSecurityPolicy(int child_id,
320 const base::FilePath& path) {
321 ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile(
322 child_id, path);
325 DownloadInterruptReason CallbackAndReturn(
326 const DownloadUrlParameters::OnStartedCallback& started_cb,
327 DownloadInterruptReason interrupt_reason) {
328 if (started_cb.is_null())
329 return interrupt_reason;
330 BrowserThread::PostTask(
331 BrowserThread::UI,
332 FROM_HERE,
333 base::Bind(
334 started_cb, static_cast<DownloadItem*>(NULL), interrupt_reason));
336 return interrupt_reason;
339 int GetCertID(net::URLRequest* request, int child_id) {
340 if (request->ssl_info().cert.get()) {
341 return CertStore::GetInstance()->StoreCert(request->ssl_info().cert.get(),
342 child_id);
344 return 0;
347 void NotifyRedirectOnUI(int render_process_id,
348 int render_frame_host,
349 scoped_ptr<ResourceRedirectDetails> details) {
350 RenderFrameHostImpl* host =
351 RenderFrameHostImpl::FromID(render_process_id, render_frame_host);
352 WebContentsImpl* web_contents =
353 static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(host));
354 if (!web_contents)
355 return;
356 web_contents->DidGetRedirectForResourceRequest(host, *details.get());
359 void NotifyResponseOnUI(int render_process_id,
360 int render_frame_host,
361 scoped_ptr<ResourceRequestDetails> details) {
362 RenderFrameHostImpl* host =
363 RenderFrameHostImpl::FromID(render_process_id, render_frame_host);
364 WebContentsImpl* web_contents =
365 static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(host));
366 if (!web_contents)
367 return;
368 web_contents->DidGetResourceResponseStart(*details.get());
371 bool IsValidatedSCT(
372 const net::SignedCertificateTimestampAndStatus& sct_status) {
373 return sct_status.status == net::ct::SCT_STATUS_OK;
376 storage::BlobStorageContext* GetBlobStorageContext(
377 ChromeBlobStorageContext* blob_storage_context) {
378 if (!blob_storage_context)
379 return NULL;
380 return blob_storage_context->context();
383 void AttachRequestBodyBlobDataHandles(
384 ResourceRequestBody* body,
385 storage::BlobStorageContext* blob_context) {
386 DCHECK(blob_context);
387 for (size_t i = 0; i < body->elements()->size(); ++i) {
388 const ResourceRequestBody::Element& element = (*body->elements())[i];
389 if (element.type() != ResourceRequestBody::Element::TYPE_BLOB)
390 continue;
391 scoped_ptr<storage::BlobDataHandle> handle =
392 blob_context->GetBlobDataFromUUID(element.blob_uuid());
393 DCHECK(handle);
394 if (!handle)
395 continue;
396 // Ensure the blob and any attached shareable files survive until
397 // upload completion. The |body| takes ownership of |handle|.
398 const void* key = handle.get();
399 body->SetUserData(key, handle.release());
403 // PlzNavigate
404 // This method is called in the UI thread to send the timestamp of a resource
405 // request to the respective Navigator (for an UMA histogram).
406 void LogResourceRequestTimeOnUI(
407 base::TimeTicks timestamp,
408 int render_process_id,
409 int render_frame_id,
410 const GURL& url) {
411 DCHECK_CURRENTLY_ON(BrowserThread::UI);
412 RenderFrameHostImpl* host =
413 RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
414 if (host != NULL) {
415 DCHECK(host->frame_tree_node()->IsMainFrame());
416 host->frame_tree_node()->navigator()->LogResourceRequestTime(
417 timestamp, url);
421 } // namespace
423 // static
424 ResourceDispatcherHost* ResourceDispatcherHost::Get() {
425 return g_resource_dispatcher_host;
428 ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
429 : save_file_manager_(new SaveFileManager()),
430 request_id_(-1),
431 is_shutdown_(false),
432 num_in_flight_requests_(0),
433 max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()),
434 max_num_in_flight_requests_per_process_(
435 static_cast<int>(
436 max_num_in_flight_requests_ * kMaxRequestsPerProcessRatio)),
437 max_outstanding_requests_cost_per_process_(
438 kMaxOutstandingRequestsCostPerProcess),
439 filter_(NULL),
440 delegate_(NULL),
441 allow_cross_origin_auth_prompt_(false) {
442 DCHECK_CURRENTLY_ON(BrowserThread::UI);
443 DCHECK(!g_resource_dispatcher_host);
444 g_resource_dispatcher_host = this;
446 GetContentClient()->browser()->ResourceDispatcherHostCreated();
448 ANNOTATE_BENIGN_RACE(
449 &last_user_gesture_time_,
450 "We don't care about the precise value, see http://crbug.com/92889");
452 BrowserThread::PostTask(BrowserThread::IO,
453 FROM_HERE,
454 base::Bind(&ResourceDispatcherHostImpl::OnInit,
455 base::Unretained(this)));
457 update_load_states_timer_.reset(
458 new base::RepeatingTimer<ResourceDispatcherHostImpl>());
461 ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() {
462 DCHECK(outstanding_requests_stats_map_.empty());
463 DCHECK(g_resource_dispatcher_host);
464 g_resource_dispatcher_host = NULL;
467 // static
468 ResourceDispatcherHostImpl* ResourceDispatcherHostImpl::Get() {
469 return g_resource_dispatcher_host;
472 void ResourceDispatcherHostImpl::SetDelegate(
473 ResourceDispatcherHostDelegate* delegate) {
474 delegate_ = delegate;
477 void ResourceDispatcherHostImpl::SetAllowCrossOriginAuthPrompt(bool value) {
478 allow_cross_origin_auth_prompt_ = value;
481 void ResourceDispatcherHostImpl::AddResourceContext(ResourceContext* context) {
482 active_resource_contexts_.insert(context);
485 void ResourceDispatcherHostImpl::RemoveResourceContext(
486 ResourceContext* context) {
487 CHECK(ContainsKey(active_resource_contexts_, context));
488 active_resource_contexts_.erase(context);
491 void ResourceDispatcherHostImpl::CancelRequestsForContext(
492 ResourceContext* context) {
493 DCHECK_CURRENTLY_ON(BrowserThread::IO);
494 DCHECK(context);
496 CHECK(ContainsKey(active_resource_contexts_, context));
498 // Note that request cancellation has side effects. Therefore, we gather all
499 // the requests to cancel first, and then we start cancelling. We assert at
500 // the end that there are no more to cancel since the context is about to go
501 // away.
502 typedef std::vector<linked_ptr<ResourceLoader>> LoaderList;
503 LoaderList loaders_to_cancel;
505 for (LoaderMap::iterator i = pending_loaders_.begin();
506 i != pending_loaders_.end();) {
507 if (i->second->GetRequestInfo()->GetContext() == context) {
508 loaders_to_cancel.push_back(i->second);
509 IncrementOutstandingRequestsMemory(-1, *i->second->GetRequestInfo());
510 pending_loaders_.erase(i++);
511 } else {
512 ++i;
516 for (BlockedLoadersMap::iterator i = blocked_loaders_map_.begin();
517 i != blocked_loaders_map_.end();) {
518 BlockedLoadersList* loaders = i->second;
519 if (loaders->empty()) {
520 // This can happen if BlockRequestsForRoute() has been called for a route,
521 // but we haven't blocked any matching requests yet.
522 ++i;
523 continue;
525 ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo();
526 if (info->GetContext() == context) {
527 blocked_loaders_map_.erase(i++);
528 for (BlockedLoadersList::const_iterator it = loaders->begin();
529 it != loaders->end(); ++it) {
530 linked_ptr<ResourceLoader> loader = *it;
531 info = loader->GetRequestInfo();
532 // We make the assumption that all requests on the list have the same
533 // ResourceContext.
534 DCHECK_EQ(context, info->GetContext());
535 IncrementOutstandingRequestsMemory(-1, *info);
536 loaders_to_cancel.push_back(loader);
538 delete loaders;
539 } else {
540 ++i;
544 #ifndef NDEBUG
545 for (LoaderList::iterator i = loaders_to_cancel.begin();
546 i != loaders_to_cancel.end(); ++i) {
547 // There is no strict requirement that this be the case, but currently
548 // downloads, streams, detachable requests, transferred requests, and
549 // browser-owned requests are the only requests that aren't cancelled when
550 // the associated processes go away. It may be OK for this invariant to
551 // change in the future, but if this assertion fires without the invariant
552 // changing, then it's indicative of a leak.
553 DCHECK((*i)->GetRequestInfo()->IsDownload() ||
554 (*i)->GetRequestInfo()->is_stream() ||
555 ((*i)->GetRequestInfo()->detachable_handler() &&
556 (*i)->GetRequestInfo()->detachable_handler()->is_detached()) ||
557 (*i)->GetRequestInfo()->GetProcessType() == PROCESS_TYPE_BROWSER ||
558 (*i)->is_transferring());
560 #endif
562 loaders_to_cancel.clear();
564 // Validate that no more requests for this context were added.
565 for (LoaderMap::const_iterator i = pending_loaders_.begin();
566 i != pending_loaders_.end(); ++i) {
567 // http://crbug.com/90971
568 CHECK_NE(i->second->GetRequestInfo()->GetContext(), context);
571 for (BlockedLoadersMap::const_iterator i = blocked_loaders_map_.begin();
572 i != blocked_loaders_map_.end(); ++i) {
573 BlockedLoadersList* loaders = i->second;
574 if (!loaders->empty()) {
575 ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo();
576 // http://crbug.com/90971
577 CHECK_NE(info->GetContext(), context);
582 DownloadInterruptReason ResourceDispatcherHostImpl::BeginDownload(
583 scoped_ptr<net::URLRequest> request,
584 const Referrer& referrer,
585 bool is_content_initiated,
586 ResourceContext* context,
587 int child_id,
588 int route_id,
589 bool prefer_cache,
590 bool do_not_prompt_for_login,
591 scoped_ptr<DownloadSaveInfo> save_info,
592 uint32 download_id,
593 const DownloadStartedCallback& started_callback) {
594 if (is_shutdown_)
595 return CallbackAndReturn(started_callback,
596 DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN);
598 const GURL& url = request->original_url();
600 // http://crbug.com/90971
601 char url_buf[128];
602 base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
603 base::debug::Alias(url_buf);
604 CHECK(ContainsKey(active_resource_contexts_, context));
606 SetReferrerForRequest(request.get(), referrer);
608 int extra_load_flags = net::LOAD_NORMAL;
609 if (prefer_cache) {
610 // If there is upload data attached, only retrieve from cache because there
611 // is no current mechanism to prompt the user for their consent for a
612 // re-post. For GETs, try to retrieve data from the cache and skip
613 // validating the entry if present.
614 if (request->get_upload() != NULL)
615 extra_load_flags |= net::LOAD_ONLY_FROM_CACHE;
616 else
617 extra_load_flags |= net::LOAD_PREFERRING_CACHE;
618 } else {
619 extra_load_flags |= net::LOAD_DISABLE_CACHE;
621 request->SetLoadFlags(request->load_flags() | extra_load_flags);
623 // We treat a download as a main frame load, and thus update the policy URL on
624 // redirects.
626 // TODO(davidben): Is this correct? If this came from a
627 // ViewHostMsg_DownloadUrl in a frame, should it have first-party URL set
628 // appropriately?
629 request->set_first_party_url_policy(
630 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
632 // Check if the renderer is permitted to request the requested URL.
633 if (!ChildProcessSecurityPolicyImpl::GetInstance()->
634 CanRequestURL(child_id, url)) {
635 VLOG(1) << "Denied unauthorized download request for "
636 << url.possibly_invalid_spec();
637 return CallbackAndReturn(started_callback,
638 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST);
641 request_id_--;
643 const net::URLRequestContext* request_context = context->GetRequestContext();
644 if (!request_context->job_factory()->IsHandledURL(url)) {
645 VLOG(1) << "Download request for unsupported protocol: "
646 << url.possibly_invalid_spec();
647 return CallbackAndReturn(started_callback,
648 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST);
651 ResourceRequestInfoImpl* extra_info =
652 CreateRequestInfo(child_id, route_id, true, context);
653 extra_info->set_do_not_prompt_for_login(do_not_prompt_for_login);
654 extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
656 if (request->url().SchemeIs(url::kBlobScheme)) {
657 ChromeBlobStorageContext* blob_context =
658 GetChromeBlobStorageContextForResourceContext(context);
659 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
660 request.get(),
661 blob_context->context()->GetBlobDataFromPublicURL(request->url()));
664 // From this point forward, the |DownloadResourceHandler| is responsible for
665 // |started_callback|.
666 scoped_ptr<ResourceHandler> handler(
667 CreateResourceHandlerForDownload(request.get(), is_content_initiated,
668 true, download_id, save_info.Pass(),
669 started_callback));
671 BeginRequestInternal(request.Pass(), handler.Pass());
673 return DOWNLOAD_INTERRUPT_REASON_NONE;
676 void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest(
677 net::URLRequest* request) {
678 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
679 if (info) {
680 ResourceLoader* loader = GetLoader(info->GetGlobalRequestID());
681 if (loader)
682 loader->ClearLoginDelegate();
686 void ResourceDispatcherHostImpl::Shutdown() {
687 DCHECK_CURRENTLY_ON(BrowserThread::UI);
688 BrowserThread::PostTask(BrowserThread::IO,
689 FROM_HERE,
690 base::Bind(&ResourceDispatcherHostImpl::OnShutdown,
691 base::Unretained(this)));
694 scoped_ptr<ResourceHandler>
695 ResourceDispatcherHostImpl::CreateResourceHandlerForDownload(
696 net::URLRequest* request,
697 bool is_content_initiated,
698 bool must_download,
699 uint32 id,
700 scoped_ptr<DownloadSaveInfo> save_info,
701 const DownloadUrlParameters::OnStartedCallback& started_cb) {
702 scoped_ptr<ResourceHandler> handler(
703 new DownloadResourceHandler(id, request, started_cb, save_info.Pass()));
704 if (delegate_) {
705 const ResourceRequestInfo* request_info(
706 ResourceRequestInfo::ForRequest(request));
708 ScopedVector<ResourceThrottle> throttles;
709 delegate_->DownloadStarting(
710 request, request_info->GetContext(), request_info->GetChildID(),
711 request_info->GetRouteID(), request_info->GetRequestID(),
712 is_content_initiated, must_download, &throttles);
713 if (!throttles.empty()) {
714 handler.reset(
715 new ThrottlingResourceHandler(
716 handler.Pass(), request, throttles.Pass()));
719 return handler.Pass();
722 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::MaybeInterceptAsStream(
723 const base::FilePath& plugin_path,
724 net::URLRequest* request,
725 ResourceResponse* response,
726 std::string* payload) {
727 payload->clear();
728 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
729 const std::string& mime_type = response->head.mime_type;
731 GURL origin;
732 if (!delegate_ ||
733 !delegate_->ShouldInterceptResourceAsStream(
734 request, plugin_path, mime_type, &origin, payload)) {
735 return scoped_ptr<ResourceHandler>();
738 StreamContext* stream_context =
739 GetStreamContextForResourceContext(info->GetContext());
741 scoped_ptr<StreamResourceHandler> handler(
742 new StreamResourceHandler(request,
743 stream_context->registry(),
744 origin));
746 info->set_is_stream(true);
747 scoped_ptr<StreamInfo> stream_info(new StreamInfo);
748 stream_info->handle = handler->stream()->CreateHandle();
749 stream_info->original_url = request->url();
750 stream_info->mime_type = mime_type;
751 // Make a copy of the response headers so it is safe to pass across threads;
752 // the old handler (AsyncResourceHandler) may modify it in parallel via the
753 // ResourceDispatcherHostDelegate.
754 if (response->head.headers.get()) {
755 stream_info->response_headers =
756 new net::HttpResponseHeaders(response->head.headers->raw_headers());
758 delegate_->OnStreamCreated(request, stream_info.Pass());
759 return handler.Pass();
762 ResourceDispatcherHostLoginDelegate*
763 ResourceDispatcherHostImpl::CreateLoginDelegate(
764 ResourceLoader* loader,
765 net::AuthChallengeInfo* auth_info) {
766 if (!delegate_)
767 return NULL;
769 return delegate_->CreateLoginDelegate(auth_info, loader->request());
772 bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader* loader,
773 const GURL& url) {
774 if (!delegate_)
775 return false;
777 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
779 if (!IsResourceTypeFrame(info->GetResourceType()))
780 return false;
782 const net::URLRequestJobFactory* job_factory =
783 info->GetContext()->GetRequestContext()->job_factory();
784 if (job_factory->IsHandledURL(url))
785 return false;
787 return delegate_->HandleExternalProtocol(
788 url, info->GetChildID(), info->GetRouteID(), info->IsMainFrame(),
789 info->GetPageTransition(), info->HasUserGesture());
792 void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader* loader) {
793 // Make sure we have the load state monitor running.
794 if (!update_load_states_timer_->IsRunning() &&
795 scheduler_->HasLoadingClients()) {
796 update_load_states_timer_->Start(
797 FROM_HERE, TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec),
798 this, &ResourceDispatcherHostImpl::UpdateLoadInfo);
802 void ResourceDispatcherHostImpl::DidReceiveRedirect(ResourceLoader* loader,
803 const GURL& new_url) {
804 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
806 int render_process_id, render_frame_host;
807 if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host))
808 return;
810 // Notify the observers on the UI thread.
811 scoped_ptr<ResourceRedirectDetails> detail(new ResourceRedirectDetails(
812 loader->request(),
813 GetCertID(loader->request(), info->GetChildID()),
814 new_url));
815 BrowserThread::PostTask(
816 BrowserThread::UI, FROM_HERE,
817 base::Bind(
818 &NotifyRedirectOnUI,
819 render_process_id, render_frame_host, base::Passed(&detail)));
822 void ResourceDispatcherHostImpl::DidReceiveResponse(ResourceLoader* loader) {
823 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
824 net::URLRequest* request = loader->request();
825 if (request->was_fetched_via_proxy() &&
826 request->was_fetched_via_spdy() &&
827 request->url().SchemeIs(url::kHttpScheme)) {
828 scheduler_->OnReceivedSpdyProxiedHttpResponse(
829 info->GetChildID(), info->GetRouteID());
832 int render_process_id, render_frame_host;
833 if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host))
834 return;
836 // Notify the observers on the UI thread.
837 scoped_ptr<ResourceRequestDetails> detail(new ResourceRequestDetails(
838 request, GetCertID(request, info->GetChildID())));
839 BrowserThread::PostTask(
840 BrowserThread::UI, FROM_HERE,
841 base::Bind(
842 &NotifyResponseOnUI,
843 render_process_id, render_frame_host, base::Passed(&detail)));
846 void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader* loader) {
847 ResourceRequestInfo* info = loader->GetRequestInfo();
849 // Record final result of all resource loads.
850 if (info->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME) {
851 // This enumeration has "3" appended to its name to distinguish it from
852 // older versions.
853 UMA_HISTOGRAM_SPARSE_SLOWLY(
854 "Net.ErrorCodesForMainFrame3",
855 -loader->request()->status().error());
857 // Record time to success and error for the most common errors, and for
858 // the aggregate remainder errors.
859 base::TimeDelta request_loading_time(
860 base::TimeTicks::Now() - loader->request()->creation_time());
861 switch (loader->request()->status().error()) {
862 case net::OK:
863 UMA_HISTOGRAM_LONG_TIMES(
864 "Net.RequestTime2.Success", request_loading_time);
865 break;
866 case net::ERR_ABORTED:
867 UMA_HISTOGRAM_LONG_TIMES(
868 "Net.RequestTime2.ErrAborted", request_loading_time);
869 break;
870 case net::ERR_CONNECTION_RESET:
871 UMA_HISTOGRAM_LONG_TIMES(
872 "Net.RequestTime2.ErrConnectionReset", request_loading_time);
873 break;
874 case net::ERR_CONNECTION_TIMED_OUT:
875 UMA_HISTOGRAM_LONG_TIMES(
876 "Net.RequestTime2.ErrConnectionTimedOut", request_loading_time);
877 break;
878 case net::ERR_INTERNET_DISCONNECTED:
879 UMA_HISTOGRAM_LONG_TIMES(
880 "Net.RequestTime2.ErrInternetDisconnected", request_loading_time);
881 break;
882 case net::ERR_NAME_NOT_RESOLVED:
883 UMA_HISTOGRAM_LONG_TIMES(
884 "Net.RequestTime2.ErrNameNotResolved", request_loading_time);
885 break;
886 case net::ERR_TIMED_OUT:
887 UMA_HISTOGRAM_LONG_TIMES(
888 "Net.RequestTime2.ErrTimedOut", request_loading_time);
889 break;
890 default:
891 UMA_HISTOGRAM_LONG_TIMES(
892 "Net.RequestTime2.MiscError", request_loading_time);
893 break;
896 if (loader->request()->url().SchemeIsCryptographic()) {
897 if (loader->request()->url().host() == "www.google.com") {
898 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2",
899 -loader->request()->status().error());
902 int num_valid_scts = std::count_if(
903 loader->request()->ssl_info().signed_certificate_timestamps.begin(),
904 loader->request()->ssl_info().signed_certificate_timestamps.end(),
905 IsValidatedSCT);
906 UMA_HISTOGRAM_COUNTS_100(
907 "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts);
909 } else {
910 if (info->GetResourceType() == RESOURCE_TYPE_IMAGE) {
911 UMA_HISTOGRAM_SPARSE_SLOWLY(
912 "Net.ErrorCodesForImages",
913 -loader->request()->status().error());
915 // This enumeration has "2" appended to distinguish it from older versions.
916 UMA_HISTOGRAM_SPARSE_SLOWLY(
917 "Net.ErrorCodesForSubresources2",
918 -loader->request()->status().error());
921 if (loader->request()->url().SchemeIsCryptographic()) {
922 RecordCertificateHistograms(loader->request()->ssl_info(),
923 info->GetResourceType());
926 if (delegate_)
927 delegate_->RequestComplete(loader->request());
929 // Destroy the ResourceLoader.
930 RemovePendingRequest(info->GetChildID(), info->GetRequestID());
933 void ResourceDispatcherHostImpl::OnInit() {
934 scheduler_.reset(new ResourceScheduler);
937 void ResourceDispatcherHostImpl::OnShutdown() {
938 DCHECK_CURRENTLY_ON(BrowserThread::IO);
940 is_shutdown_ = true;
941 pending_loaders_.clear();
943 // Make sure we shutdown the timer now, otherwise by the time our destructor
944 // runs if the timer is still running the Task is deleted twice (once by
945 // the MessageLoop and the second time by RepeatingTimer).
946 update_load_states_timer_.reset();
948 // Clear blocked requests if any left.
949 // Note that we have to do this in 2 passes as we cannot call
950 // CancelBlockedRequestsForRoute while iterating over
951 // blocked_loaders_map_, as it modifies it.
952 std::set<GlobalRoutingID> ids;
953 for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
954 iter != blocked_loaders_map_.end(); ++iter) {
955 std::pair<std::set<GlobalRoutingID>::iterator, bool> result =
956 ids.insert(iter->first);
957 // We should not have duplicates.
958 DCHECK(result.second);
960 for (std::set<GlobalRoutingID>::const_iterator iter = ids.begin();
961 iter != ids.end(); ++iter) {
962 CancelBlockedRequestsForRoute(iter->child_id, iter->route_id);
965 scheduler_.reset();
968 bool ResourceDispatcherHostImpl::OnMessageReceived(
969 const IPC::Message& message,
970 ResourceMessageFilter* filter) {
971 filter_ = filter;
972 bool handled = true;
973 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcherHostImpl, message)
974 IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource, OnRequestResource)
975 IPC_MESSAGE_HANDLER_DELAY_REPLY(ResourceHostMsg_SyncLoad, OnSyncLoad)
976 IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile,
977 OnReleaseDownloadedFile)
978 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataDownloaded_ACK, OnDataDownloadedACK)
979 IPC_MESSAGE_HANDLER(ResourceHostMsg_UploadProgress_ACK, OnUploadProgressACK)
980 IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest, OnCancelRequest)
981 IPC_MESSAGE_UNHANDLED(handled = false)
982 IPC_END_MESSAGE_MAP()
984 if (!handled && IPC_MESSAGE_ID_CLASS(message.type()) == ResourceMsgStart) {
985 base::PickleIterator iter(message);
986 int request_id = -1;
987 bool ok = iter.ReadInt(&request_id);
988 DCHECK(ok);
989 GlobalRequestID id(filter_->child_id(), request_id);
990 DelegateMap::iterator it = delegate_map_.find(id);
991 if (it != delegate_map_.end()) {
992 base::ObserverList<ResourceMessageDelegate>::Iterator del_it(it->second);
993 ResourceMessageDelegate* delegate;
994 while (!handled && (delegate = del_it.GetNext()) != NULL) {
995 handled = delegate->OnMessageReceived(message);
999 // As the unhandled resource message effectively has no consumer, mark it as
1000 // handled to prevent needless propagation through the filter pipeline.
1001 handled = true;
1004 filter_ = NULL;
1005 return handled;
1008 void ResourceDispatcherHostImpl::OnRequestResource(
1009 int routing_id,
1010 int request_id,
1011 const ResourceHostMsg_Request& request_data) {
1012 // TODO(pkasting): Remove ScopedTracker below once crbug.com/477117 is fixed.
1013 tracked_objects::ScopedTracker tracking_profile(
1014 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1015 "477117 ResourceDispatcherHostImpl::OnRequestResource"));
1016 // When logging time-to-network only care about main frame and non-transfer
1017 // navigations.
1018 if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME &&
1019 request_data.transferred_request_request_id == -1 &&
1020 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1021 switches::kEnableBrowserSideNavigation)) {
1022 BrowserThread::PostTask(
1023 BrowserThread::UI,
1024 FROM_HERE,
1025 base::Bind(&LogResourceRequestTimeOnUI,
1026 TimeTicks::Now(),
1027 filter_->child_id(),
1028 request_data.render_frame_id,
1029 request_data.url));
1031 BeginRequest(request_id, request_data, NULL, routing_id);
1034 // Begins a resource request with the given params on behalf of the specified
1035 // child process. Responses will be dispatched through the given receiver. The
1036 // process ID is used to lookup WebContentsImpl from routing_id's in the case of
1037 // a request from a renderer. request_context is the cookie/cache context to be
1038 // used for this request.
1040 // If sync_result is non-null, then a SyncLoad reply will be generated, else
1041 // a normal asynchronous set of response messages will be generated.
1042 void ResourceDispatcherHostImpl::OnSyncLoad(
1043 int request_id,
1044 const ResourceHostMsg_Request& request_data,
1045 IPC::Message* sync_result) {
1046 BeginRequest(request_id, request_data, sync_result,
1047 sync_result->routing_id());
1050 void ResourceDispatcherHostImpl::UpdateRequestForTransfer(
1051 int child_id,
1052 int route_id,
1053 int request_id,
1054 const ResourceHostMsg_Request& request_data,
1055 const linked_ptr<ResourceLoader>& loader) {
1056 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
1057 GlobalRoutingID old_routing_id(
1058 request_data.transferred_request_child_id, info->GetRouteID());
1059 GlobalRequestID old_request_id(request_data.transferred_request_child_id,
1060 request_data.transferred_request_request_id);
1061 GlobalRoutingID new_routing_id(child_id, route_id);
1062 GlobalRequestID new_request_id(child_id, request_id);
1064 // Clear out data that depends on |info| before updating it.
1065 // We always need to move the memory stats to the new process. In contrast,
1066 // stats.num_requests is only tracked for some requests (those that require
1067 // file descriptors for their shared memory buffer).
1068 IncrementOutstandingRequestsMemory(-1, *info);
1069 bool should_update_count = info->counted_as_in_flight_request();
1070 if (should_update_count)
1071 IncrementOutstandingRequestsCount(-1, info);
1072 pending_loaders_.erase(old_request_id);
1074 // ResourceHandlers should always get state related to the request from the
1075 // ResourceRequestInfo rather than caching it locally. This lets us update
1076 // the info object when a transfer occurs.
1077 info->UpdateForTransfer(child_id, route_id, request_data.origin_pid,
1078 request_id, request_data.parent_render_frame_id,
1079 filter_->GetWeakPtr());
1081 // Update maps that used the old IDs, if necessary. Some transfers in tests
1082 // do not actually use a different ID, so not all maps need to be updated.
1083 pending_loaders_[new_request_id] = loader;
1084 IncrementOutstandingRequestsMemory(1, *info);
1085 if (should_update_count)
1086 IncrementOutstandingRequestsCount(1, info);
1087 if (old_routing_id != new_routing_id) {
1088 if (blocked_loaders_map_.find(old_routing_id) !=
1089 blocked_loaders_map_.end()) {
1090 blocked_loaders_map_[new_routing_id] =
1091 blocked_loaders_map_[old_routing_id];
1092 blocked_loaders_map_.erase(old_routing_id);
1095 if (old_request_id != new_request_id) {
1096 DelegateMap::iterator it = delegate_map_.find(old_request_id);
1097 if (it != delegate_map_.end()) {
1098 // Tell each delegate that the request ID has changed.
1099 base::ObserverList<ResourceMessageDelegate>::Iterator del_it(it->second);
1100 ResourceMessageDelegate* delegate;
1101 while ((delegate = del_it.GetNext()) != NULL) {
1102 delegate->set_request_id(new_request_id);
1104 // Now store the observer list under the new request ID.
1105 delegate_map_[new_request_id] = delegate_map_[old_request_id];
1106 delegate_map_.erase(old_request_id);
1110 AppCacheInterceptor::CompleteCrossSiteTransfer(
1111 loader->request(),
1112 child_id,
1113 request_data.appcache_host_id);
1115 ServiceWorkerRequestHandler* handler =
1116 ServiceWorkerRequestHandler::GetHandler(loader->request());
1117 if (handler) {
1118 handler->CompleteCrossSiteTransfer(
1119 child_id, request_data.service_worker_provider_id);
1122 // We should have a CrossSiteResourceHandler to finish the transfer.
1123 DCHECK(info->cross_site_handler());
1126 void ResourceDispatcherHostImpl::BeginRequest(
1127 int request_id,
1128 const ResourceHostMsg_Request& request_data,
1129 IPC::Message* sync_result, // only valid for sync
1130 int route_id) {
1131 int process_type = filter_->process_type();
1132 int child_id = filter_->child_id();
1134 // Reject invalid priority.
1135 if (request_data.priority < net::MINIMUM_PRIORITY ||
1136 request_data.priority > net::MAXIMUM_PRIORITY) {
1137 bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_PRIORITY);
1138 return;
1141 // If we crash here, figure out what URL the renderer was requesting.
1142 // http://crbug.com/91398
1143 char url_buf[128];
1144 base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf));
1145 base::debug::Alias(url_buf);
1147 // If the request that's coming in is being transferred from another process,
1148 // we want to reuse and resume the old loader rather than start a new one.
1149 LoaderMap::iterator it = pending_loaders_.find(
1150 GlobalRequestID(request_data.transferred_request_child_id,
1151 request_data.transferred_request_request_id));
1152 if (it != pending_loaders_.end()) {
1153 // If the request is transferring to a new process, we can update our
1154 // state and let it resume with its existing ResourceHandlers.
1155 if (it->second->is_transferring()) {
1156 linked_ptr<ResourceLoader> deferred_loader = it->second;
1157 UpdateRequestForTransfer(child_id, route_id, request_id,
1158 request_data, deferred_loader);
1160 deferred_loader->CompleteTransfer();
1161 } else {
1162 bad_message::ReceivedBadMessage(
1163 filter_, bad_message::RDH_REQUEST_NOT_TRANSFERRING);
1165 return;
1168 ResourceContext* resource_context = NULL;
1169 net::URLRequestContext* request_context = NULL;
1170 filter_->GetContexts(request_data, &resource_context, &request_context);
1171 // http://crbug.com/90971
1172 CHECK(ContainsKey(active_resource_contexts_, resource_context));
1174 if (is_shutdown_ ||
1175 !ShouldServiceRequest(process_type, child_id, request_data,
1176 filter_->file_system_context())) {
1177 AbortRequestBeforeItStarts(filter_, sync_result, request_id);
1178 return;
1181 // Allow the observer to block/handle the request.
1182 if (delegate_ && !delegate_->ShouldBeginRequest(request_data.method,
1183 request_data.url,
1184 request_data.resource_type,
1185 resource_context)) {
1186 AbortRequestBeforeItStarts(filter_, sync_result, request_id);
1187 return;
1190 // Construct the request.
1191 scoped_ptr<net::URLRequest> new_request = request_context->CreateRequest(
1192 request_data.url, request_data.priority, NULL);
1194 new_request->set_method(request_data.method);
1195 new_request->set_first_party_for_cookies(
1196 request_data.first_party_for_cookies);
1198 // If the request is a MAIN_FRAME request, the first-party URL gets updated on
1199 // redirects.
1200 if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
1201 new_request->set_first_party_url_policy(
1202 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
1205 const Referrer referrer(request_data.referrer, request_data.referrer_policy);
1206 SetReferrerForRequest(new_request.get(), referrer);
1208 net::HttpRequestHeaders headers;
1209 headers.AddHeadersFromString(request_data.headers);
1210 new_request->SetExtraRequestHeaders(headers);
1212 storage::BlobStorageContext* blob_context =
1213 GetBlobStorageContext(filter_->blob_storage_context());
1214 // Resolve elements from request_body and prepare upload data.
1215 if (request_data.request_body.get()) {
1216 // |blob_context| could be null when the request is from the plugins because
1217 // ResourceMessageFilters created in PluginProcessHost don't have the blob
1218 // context.
1219 if (blob_context) {
1220 // Attaches the BlobDataHandles to request_body not to free the blobs and
1221 // any attached shareable files until upload completion. These data will
1222 // be used in UploadDataStream and ServiceWorkerURLRequestJob.
1223 AttachRequestBodyBlobDataHandles(
1224 request_data.request_body.get(),
1225 blob_context);
1227 new_request->set_upload(UploadDataStreamBuilder::Build(
1228 request_data.request_body.get(),
1229 blob_context,
1230 filter_->file_system_context(),
1231 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1232 .get()));
1235 bool allow_download = request_data.allow_download &&
1236 IsResourceTypeFrame(request_data.resource_type);
1237 bool do_not_prompt_for_login = request_data.do_not_prompt_for_login;
1238 bool is_sync_load = sync_result != NULL;
1239 int load_flags =
1240 BuildLoadFlagsForRequest(request_data, child_id, is_sync_load);
1241 if (request_data.resource_type == RESOURCE_TYPE_PREFETCH ||
1242 request_data.resource_type == RESOURCE_TYPE_FAVICON) {
1243 do_not_prompt_for_login = true;
1245 if (request_data.resource_type == RESOURCE_TYPE_IMAGE &&
1246 HTTP_AUTH_RELATION_BLOCKED_CROSS ==
1247 HttpAuthRelationTypeOf(request_data.url,
1248 request_data.first_party_for_cookies)) {
1249 // Prevent third-party image content from prompting for login, as this
1250 // is often a scam to extract credentials for another domain from the user.
1251 // Only block image loads, as the attack applies largely to the "src"
1252 // property of the <img> tag. It is common for web properties to allow
1253 // untrusted values for <img src>; this is considered a fair thing for an
1254 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
1255 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
1256 // would be considered vulnerable in and of itself.
1257 do_not_prompt_for_login = true;
1258 load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
1261 // Sync loads should have maximum priority and should be the only
1262 // requets that have the ignore limits flag set.
1263 if (is_sync_load) {
1264 DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY);
1265 DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1266 } else {
1267 DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1269 new_request->SetLoadFlags(load_flags);
1271 // Make extra info and read footer (contains request ID).
1272 ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
1273 process_type, child_id, route_id,
1274 -1, // frame_tree_node_id
1275 request_data.origin_pid,
1276 request_id,
1277 request_data.render_frame_id,
1278 request_data.is_main_frame,
1279 request_data.parent_is_main_frame,
1280 request_data.parent_render_frame_id,
1281 request_data.resource_type,
1282 request_data.transition_type,
1283 request_data.should_replace_current_entry,
1284 false, // is download
1285 false, // is stream
1286 allow_download,
1287 request_data.has_user_gesture,
1288 request_data.enable_load_timing,
1289 request_data.enable_upload_progress,
1290 do_not_prompt_for_login,
1291 request_data.referrer_policy,
1292 request_data.visiblity_state,
1293 resource_context, filter_->GetWeakPtr(),
1294 !is_sync_load);
1295 // Request takes ownership.
1296 extra_info->AssociateWithRequest(new_request.get());
1298 if (new_request->url().SchemeIs(url::kBlobScheme)) {
1299 // Hang on to a reference to ensure the blob is not released prior
1300 // to the job being started.
1301 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1302 new_request.get(),
1303 filter_->blob_storage_context()->context()->GetBlobDataFromPublicURL(
1304 new_request->url()));
1307 // Initialize the service worker handler for the request. We don't use
1308 // ServiceWorker for synchronous loads to avoid renderer deadlocks.
1309 ServiceWorkerRequestHandler::InitializeHandler(
1310 new_request.get(),
1311 filter_->service_worker_context(),
1312 blob_context,
1313 child_id,
1314 request_data.service_worker_provider_id,
1315 request_data.skip_service_worker || is_sync_load,
1316 request_data.fetch_request_mode,
1317 request_data.fetch_credentials_mode,
1318 request_data.resource_type,
1319 request_data.fetch_request_context_type,
1320 request_data.fetch_frame_type,
1321 request_data.request_body);
1323 // Have the appcache associate its extra info with the request.
1324 AppCacheInterceptor::SetExtraRequestInfo(
1325 new_request.get(), filter_->appcache_service(), child_id,
1326 request_data.appcache_host_id, request_data.resource_type,
1327 request_data.should_reset_appcache);
1329 scoped_ptr<ResourceHandler> handler(
1330 CreateResourceHandler(
1331 new_request.get(),
1332 request_data, sync_result, route_id, process_type, child_id,
1333 resource_context));
1335 if (handler)
1336 BeginRequestInternal(new_request.Pass(), handler.Pass());
1339 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::CreateResourceHandler(
1340 net::URLRequest* request,
1341 const ResourceHostMsg_Request& request_data,
1342 IPC::Message* sync_result,
1343 int route_id,
1344 int process_type,
1345 int child_id,
1346 ResourceContext* resource_context) {
1347 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1348 tracked_objects::ScopedTracker tracking_profile(
1349 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1350 "456331 ResourceDispatcherHostImpl::CreateResourceHandler"));
1351 // Construct the IPC resource handler.
1352 scoped_ptr<ResourceHandler> handler;
1353 if (sync_result) {
1354 // download_to_file is not supported for synchronous requests.
1355 if (request_data.download_to_file) {
1356 bad_message::ReceivedBadMessage(filter_, bad_message::RDH_BAD_DOWNLOAD);
1357 return scoped_ptr<ResourceHandler>();
1360 handler.reset(new SyncResourceHandler(request, sync_result, this));
1361 } else {
1362 handler.reset(new AsyncResourceHandler(request, this));
1364 // The RedirectToFileResourceHandler depends on being next in the chain.
1365 if (request_data.download_to_file) {
1366 handler.reset(
1367 new RedirectToFileResourceHandler(handler.Pass(), request));
1371 // Prefetches and <a ping> requests outlive their child process.
1372 if (!sync_result && IsDetachableResourceType(request_data.resource_type)) {
1373 handler.reset(new DetachableResourceHandler(
1374 request,
1375 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs),
1376 handler.Pass()));
1379 // PlzNavigate: If using --enable-browser-side-navigation, the
1380 // CrossSiteResourceHandler is not needed. This codepath is not used for the
1381 // actual navigation request, but only the subsequent blob URL load. This does
1382 // not require request transfers.
1383 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1384 switches::kEnableBrowserSideNavigation)) {
1385 // Install a CrossSiteResourceHandler for all main frame requests. This will
1386 // check whether a transfer is required and, if so, pause for the UI thread
1387 // to drive the transfer.
1388 bool is_swappable_navigation =
1389 request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME;
1390 // If out-of-process iframes are possible, then all subframe requests need
1391 // to go through the CrossSiteResourceHandler to enforce the site isolation
1392 // policy.
1393 if (!is_swappable_navigation &&
1394 SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
1395 is_swappable_navigation =
1396 request_data.resource_type == RESOURCE_TYPE_SUB_FRAME;
1398 if (is_swappable_navigation && process_type == PROCESS_TYPE_RENDERER)
1399 handler.reset(new CrossSiteResourceHandler(handler.Pass(), request));
1402 return AddStandardHandlers(request, request_data.resource_type,
1403 resource_context, filter_->appcache_service(),
1404 child_id, route_id, handler.Pass());
1407 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::AddStandardHandlers(
1408 net::URLRequest* request,
1409 ResourceType resource_type,
1410 ResourceContext* resource_context,
1411 AppCacheService* appcache_service,
1412 int child_id,
1413 int route_id,
1414 scoped_ptr<ResourceHandler> handler) {
1416 PluginService* plugin_service = nullptr;
1417 #if defined(ENABLE_PLUGINS)
1418 plugin_service = PluginService::GetInstance();
1419 #endif
1420 // Insert a buffered event handler before the actual one.
1421 handler.reset(new MimeTypeResourceHandler(handler.Pass(), this,
1422 plugin_service, request));
1424 ScopedVector<ResourceThrottle> throttles;
1425 if (delegate_) {
1426 delegate_->RequestBeginning(request,
1427 resource_context,
1428 appcache_service,
1429 resource_type,
1430 &throttles);
1433 if (request->has_upload()) {
1434 // Block power save while uploading data.
1435 throttles.push_back(new PowerSaveBlockResourceThrottle());
1438 throttles.push_back(
1439 scheduler_->ScheduleRequest(child_id, route_id, request).release());
1441 handler.reset(
1442 new ThrottlingResourceHandler(handler.Pass(), request, throttles.Pass()));
1444 return handler.Pass();
1447 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id) {
1448 UnregisterDownloadedTempFile(filter_->child_id(), request_id);
1451 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id) {
1452 // TODO(michaeln): maybe throttle DataDownloaded messages
1455 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1456 int child_id, int request_id, const base::FilePath& file_path) {
1457 scoped_refptr<ShareableFileReference> reference =
1458 ShareableFileReference::Get(file_path);
1459 DCHECK(reference.get());
1461 registered_temp_files_[child_id][request_id] = reference;
1462 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1463 child_id, reference->path());
1465 // When the temp file is deleted, revoke permissions that the renderer has
1466 // to that file. This covers an edge case where the file is deleted and then
1467 // the same name is re-used for some other purpose, we don't want the old
1468 // renderer to still have access to it.
1470 // We do this when the file is deleted because the renderer can take a blob
1471 // reference to the temp file that outlives the url loaded that it was
1472 // loaded with to keep the file (and permissions) alive.
1473 reference->AddFinalReleaseCallback(
1474 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy,
1475 child_id));
1478 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1479 int child_id, int request_id) {
1480 DeletableFilesMap& map = registered_temp_files_[child_id];
1481 DeletableFilesMap::iterator found = map.find(request_id);
1482 if (found == map.end())
1483 return;
1485 map.erase(found);
1487 // Note that we don't remove the security bits here. This will be done
1488 // when all file refs are deleted (see RegisterDownloadedTempFile).
1491 bool ResourceDispatcherHostImpl::Send(IPC::Message* message) {
1492 delete message;
1493 return false;
1496 void ResourceDispatcherHostImpl::OnUploadProgressACK(int request_id) {
1497 ResourceLoader* loader = GetLoader(filter_->child_id(), request_id);
1498 if (loader)
1499 loader->OnUploadProgressACK();
1502 // Note that this cancel is subtly different from the other
1503 // CancelRequest methods in this file, which also tear down the loader.
1504 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id) {
1505 int child_id = filter_->child_id();
1507 // When the old renderer dies, it sends a message to us to cancel its
1508 // requests.
1509 if (IsTransferredNavigation(GlobalRequestID(child_id, request_id)))
1510 return;
1512 ResourceLoader* loader = GetLoader(child_id, request_id);
1513 if (!loader) {
1514 // We probably want to remove this warning eventually, but I wanted to be
1515 // able to notice when this happens during initial development since it
1516 // should be rare and may indicate a bug.
1517 DVLOG(1) << "Canceling a request that wasn't found";
1518 return;
1521 loader->CancelRequest(true);
1524 ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo(
1525 int child_id,
1526 int route_id,
1527 bool download,
1528 ResourceContext* context) {
1529 return new ResourceRequestInfoImpl(
1530 PROCESS_TYPE_RENDERER,
1531 child_id,
1532 route_id,
1533 -1, // frame_tree_node_id
1535 request_id_,
1536 MSG_ROUTING_NONE, // render_frame_id
1537 false, // is_main_frame
1538 false, // parent_is_main_frame
1539 -1, // parent_render_frame_id
1540 RESOURCE_TYPE_SUB_RESOURCE,
1541 ui::PAGE_TRANSITION_LINK,
1542 false, // should_replace_current_entry
1543 download, // is_download
1544 false, // is_stream
1545 download, // allow_download
1546 false, // has_user_gesture
1547 false, // enable_load_timing
1548 false, // enable_upload_progress
1549 false, // do_not_prompt_for_login
1550 blink::WebReferrerPolicyDefault,
1551 blink::WebPageVisibilityStateVisible,
1552 context,
1553 base::WeakPtr<ResourceMessageFilter>(), // filter
1554 true); // is_async
1557 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(int child_id,
1558 int route_id,
1559 bool is_visible,
1560 bool is_audible) {
1561 scheduler_->OnClientCreated(child_id, route_id, is_visible, is_audible);
1564 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1565 int child_id,
1566 int route_id) {
1567 scheduler_->OnClientDeleted(child_id, route_id);
1568 CancelRequestsForRoute(child_id, route_id);
1571 void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id,
1572 int route_id,
1573 bool is_loading) {
1574 scheduler_->OnLoadingStateChanged(child_id, route_id, !is_loading);
1577 void ResourceDispatcherHostImpl::OnRenderViewHostWasHidden(
1578 int child_id,
1579 int route_id) {
1580 scheduler_->OnVisibilityChanged(child_id, route_id, false);
1583 void ResourceDispatcherHostImpl::OnRenderViewHostWasShown(
1584 int child_id,
1585 int route_id) {
1586 scheduler_->OnVisibilityChanged(child_id, route_id, true);
1589 void ResourceDispatcherHostImpl::OnAudioRenderHostStreamStateChanged(
1590 int child_id,
1591 int route_id,
1592 bool is_playing) {
1593 // The ResourceDispatcherHost may have already been shut down.
1594 // See http://crbug.com/455098
1595 if (!scheduler_)
1596 return;
1597 scheduler_->OnAudibilityChanged(child_id, route_id, is_playing);
1600 // This function is only used for saving feature.
1601 void ResourceDispatcherHostImpl::BeginSaveFile(
1602 const GURL& url,
1603 const Referrer& referrer,
1604 int child_id,
1605 int route_id,
1606 ResourceContext* context) {
1607 if (is_shutdown_)
1608 return;
1610 // http://crbug.com/90971
1611 char url_buf[128];
1612 base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
1613 base::debug::Alias(url_buf);
1614 CHECK(ContainsKey(active_resource_contexts_, context));
1616 request_id_--;
1618 const net::URLRequestContext* request_context = context->GetRequestContext();
1619 bool known_proto =
1620 request_context->job_factory()->IsHandledURL(url);
1621 if (!known_proto) {
1622 // Since any URLs which have non-standard scheme have been filtered
1623 // by save manager(see GURL::SchemeIsStandard). This situation
1624 // should not happen.
1625 NOTREACHED();
1626 return;
1629 scoped_ptr<net::URLRequest> request(
1630 request_context->CreateRequest(url, net::DEFAULT_PRIORITY, NULL));
1631 request->set_method("GET");
1632 SetReferrerForRequest(request.get(), referrer);
1634 // So far, for saving page, we need fetch content from cache, in the
1635 // future, maybe we can use a configuration to configure this behavior.
1636 request->SetLoadFlags(net::LOAD_PREFERRING_CACHE);
1638 // Since we're just saving some resources we need, disallow downloading.
1639 ResourceRequestInfoImpl* extra_info =
1640 CreateRequestInfo(child_id, route_id, false, context);
1641 extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
1643 scoped_ptr<ResourceHandler> handler(
1644 new SaveFileResourceHandler(request.get(),
1645 child_id,
1646 route_id,
1647 url,
1648 save_file_manager_.get()));
1650 BeginRequestInternal(request.Pass(), handler.Pass());
1653 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1654 const GlobalRequestID& id) {
1655 GetLoader(id)->MarkAsTransferring();
1658 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1659 const GlobalRequestID& id) {
1660 // Request should still exist and be in the middle of a transfer.
1661 DCHECK(IsTransferredNavigation(id));
1662 RemovePendingRequest(id.child_id, id.request_id);
1665 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1666 const GlobalRequestID& id) {
1667 ResourceLoader* loader = GetLoader(id);
1668 // The response we were meant to resume could have already been canceled.
1669 if (loader)
1670 loader->CompleteTransfer();
1673 // The object died, so cancel and detach all requests associated with it except
1674 // for downloads and detachable resources, which belong to the browser process
1675 // even if initiated via a renderer.
1676 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id) {
1677 CancelRequestsForRoute(child_id, -1 /* cancel all */);
1678 registered_temp_files_.erase(child_id);
1681 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id,
1682 int route_id) {
1683 // Since pending_requests_ is a map, we first build up a list of all of the
1684 // matching requests to be cancelled, and then we cancel them. Since there
1685 // may be more than one request to cancel, we cannot simply hold onto the map
1686 // iterators found in the first loop.
1688 // Find the global ID of all matching elements.
1689 bool any_requests_transferring = false;
1690 std::vector<GlobalRequestID> matching_requests;
1691 for (LoaderMap::const_iterator i = pending_loaders_.begin();
1692 i != pending_loaders_.end(); ++i) {
1693 if (i->first.child_id != child_id)
1694 continue;
1696 ResourceRequestInfoImpl* info = i->second->GetRequestInfo();
1698 GlobalRequestID id(child_id, i->first.request_id);
1699 DCHECK(id == i->first);
1700 // Don't cancel navigations that are expected to live beyond this process.
1701 if (IsTransferredNavigation(id))
1702 any_requests_transferring = true;
1703 if (info->detachable_handler()) {
1704 info->detachable_handler()->Detach();
1705 } else if (!info->IsDownload() && !info->is_stream() &&
1706 !IsTransferredNavigation(id) &&
1707 (route_id == -1 || route_id == info->GetRouteID())) {
1708 matching_requests.push_back(id);
1712 // Remove matches.
1713 for (size_t i = 0; i < matching_requests.size(); ++i) {
1714 LoaderMap::iterator iter = pending_loaders_.find(matching_requests[i]);
1715 // Although every matching request was in pending_requests_ when we built
1716 // matching_requests, it is normal for a matching request to be not found
1717 // in pending_requests_ after we have removed some matching requests from
1718 // pending_requests_. For example, deleting a net::URLRequest that has
1719 // exclusive (write) access to an HTTP cache entry may unblock another
1720 // net::URLRequest that needs exclusive access to the same cache entry, and
1721 // that net::URLRequest may complete and remove itself from
1722 // pending_requests_. So we need to check that iter is not equal to
1723 // pending_requests_.end().
1724 if (iter != pending_loaders_.end())
1725 RemovePendingLoader(iter);
1728 // Don't clear the blocked loaders or offline policy maps if any of the
1729 // requests in route_id are being transferred to a new process, since those
1730 // maps will be updated with the new route_id after the transfer. Otherwise
1731 // we will lose track of this info when the old route goes away, before the
1732 // new one is created.
1733 if (any_requests_transferring)
1734 return;
1736 // Now deal with blocked requests if any.
1737 if (route_id != -1) {
1738 if (blocked_loaders_map_.find(GlobalRoutingID(child_id, route_id)) !=
1739 blocked_loaders_map_.end()) {
1740 CancelBlockedRequestsForRoute(child_id, route_id);
1742 } else {
1743 // We have to do all render views for the process |child_id|.
1744 // Note that we have to do this in 2 passes as we cannot call
1745 // CancelBlockedRequestsForRoute while iterating over
1746 // blocked_loaders_map_, as it modifies it.
1747 std::set<int> route_ids;
1748 for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
1749 iter != blocked_loaders_map_.end(); ++iter) {
1750 if (iter->first.child_id == child_id)
1751 route_ids.insert(iter->first.route_id);
1753 for (std::set<int>::const_iterator iter = route_ids.begin();
1754 iter != route_ids.end(); ++iter) {
1755 CancelBlockedRequestsForRoute(child_id, *iter);
1760 // Cancels the request and removes it from the list.
1761 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id,
1762 int request_id) {
1763 LoaderMap::iterator i = pending_loaders_.find(
1764 GlobalRequestID(child_id, request_id));
1765 if (i == pending_loaders_.end()) {
1766 NOTREACHED() << "Trying to remove a request that's not here";
1767 return;
1769 RemovePendingLoader(i);
1772 void ResourceDispatcherHostImpl::RemovePendingLoader(
1773 const LoaderMap::iterator& iter) {
1774 ResourceRequestInfoImpl* info = iter->second->GetRequestInfo();
1776 // Remove the memory credit that we added when pushing the request onto
1777 // the pending list.
1778 IncrementOutstandingRequestsMemory(-1, *info);
1780 pending_loaders_.erase(iter);
1783 void ResourceDispatcherHostImpl::CancelRequest(int child_id,
1784 int request_id) {
1785 ResourceLoader* loader = GetLoader(child_id, request_id);
1786 if (!loader) {
1787 // We probably want to remove this warning eventually, but I wanted to be
1788 // able to notice when this happens during initial development since it
1789 // should be rare and may indicate a bug.
1790 DVLOG(1) << "Canceling a request that wasn't found";
1791 return;
1794 RemovePendingRequest(child_id, request_id);
1797 ResourceDispatcherHostImpl::OustandingRequestsStats
1798 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1799 const ResourceRequestInfoImpl& info) {
1800 OutstandingRequestsStatsMap::iterator entry =
1801 outstanding_requests_stats_map_.find(info.GetChildID());
1802 OustandingRequestsStats stats = { 0, 0 };
1803 if (entry != outstanding_requests_stats_map_.end())
1804 stats = entry->second;
1805 return stats;
1808 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1809 const ResourceRequestInfoImpl& info,
1810 const OustandingRequestsStats& stats) {
1811 if (stats.memory_cost == 0 && stats.num_requests == 0)
1812 outstanding_requests_stats_map_.erase(info.GetChildID());
1813 else
1814 outstanding_requests_stats_map_[info.GetChildID()] = stats;
1817 ResourceDispatcherHostImpl::OustandingRequestsStats
1818 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1819 int count,
1820 const ResourceRequestInfoImpl& info) {
1821 DCHECK_EQ(1, abs(count));
1823 // Retrieve the previous value (defaulting to 0 if not found).
1824 OustandingRequestsStats stats = GetOutstandingRequestsStats(info);
1826 // Insert/update the total; delete entries when their count reaches 0.
1827 stats.memory_cost += count * info.memory_cost();
1828 DCHECK_GE(stats.memory_cost, 0);
1829 UpdateOutstandingRequestsStats(info, stats);
1831 return stats;
1834 ResourceDispatcherHostImpl::OustandingRequestsStats
1835 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1836 int count,
1837 ResourceRequestInfoImpl* info) {
1838 DCHECK_EQ(1, abs(count));
1839 num_in_flight_requests_ += count;
1841 // Keep track of whether this request is counting toward the number of
1842 // in-flight requests for this process, in case we need to transfer it to
1843 // another process. This should be a toggle.
1844 DCHECK_NE(info->counted_as_in_flight_request(), count > 0);
1845 info->set_counted_as_in_flight_request(count > 0);
1847 OustandingRequestsStats stats = GetOutstandingRequestsStats(*info);
1848 stats.num_requests += count;
1849 DCHECK_GE(stats.num_requests, 0);
1850 UpdateOutstandingRequestsStats(*info, stats);
1852 return stats;
1855 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1856 net::URLRequest* request) {
1857 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1858 OustandingRequestsStats stats = IncrementOutstandingRequestsCount(1, info);
1860 if (stats.num_requests > max_num_in_flight_requests_per_process_)
1861 return false;
1862 if (num_in_flight_requests_ > max_num_in_flight_requests_)
1863 return false;
1865 return true;
1868 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1869 net::URLRequest* request) {
1870 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1871 IncrementOutstandingRequestsCount(-1, info);
1874 void ResourceDispatcherHostImpl::BeginNavigationRequest(
1875 ResourceContext* resource_context,
1876 int frame_tree_node_id,
1877 const NavigationRequestInfo& info,
1878 NavigationURLLoaderImplCore* loader) {
1879 // PlzNavigate: BeginNavigationRequest currently should only be used for the
1880 // browser-side navigations project.
1881 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1882 switches::kEnableBrowserSideNavigation));
1884 ResourceType resource_type = info.is_main_frame ?
1885 RESOURCE_TYPE_MAIN_FRAME : RESOURCE_TYPE_SUB_FRAME;
1887 if (is_shutdown_ ||
1888 // TODO(davidben): Check ShouldServiceRequest here. This is important; it
1889 // needs to be checked relative to the child that /requested/ the
1890 // navigation. It's where file upload checks, etc., come in.
1891 (delegate_ && !delegate_->ShouldBeginRequest(
1892 info.begin_params.method,
1893 info.common_params.url,
1894 resource_type,
1895 resource_context))) {
1896 loader->NotifyRequestFailed(false, net::ERR_ABORTED);
1897 return;
1900 // Save the URL on the stack to help catch URLRequests which outlive their
1901 // URLRequestContexts. See https://crbug.com/90971
1902 char url_buf[128];
1903 base::strlcpy(
1904 url_buf, info.common_params.url.spec().c_str(), arraysize(url_buf));
1905 base::debug::Alias(url_buf);
1906 CHECK(ContainsKey(active_resource_contexts_, resource_context));
1908 const net::URLRequestContext* request_context =
1909 resource_context->GetRequestContext();
1911 int load_flags = info.begin_params.load_flags;
1912 load_flags |= net::LOAD_VERIFY_EV_CERT;
1913 if (info.is_main_frame)
1914 load_flags |= net::LOAD_MAIN_FRAME;
1916 // TODO(davidben): BuildLoadFlagsForRequest includes logic for
1917 // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here?
1919 // Sync loads should have maximum priority and should be the only
1920 // requests that have the ignore limits flag set.
1921 DCHECK(!(load_flags & net::LOAD_IGNORE_LIMITS));
1923 scoped_ptr<net::URLRequest> new_request;
1924 new_request = request_context->CreateRequest(
1925 info.common_params.url, net::HIGHEST, nullptr);
1927 new_request->set_method(info.begin_params.method);
1928 new_request->set_first_party_for_cookies(
1929 info.first_party_for_cookies);
1930 if (info.is_main_frame) {
1931 new_request->set_first_party_url_policy(
1932 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
1935 SetReferrerForRequest(new_request.get(), info.common_params.referrer);
1937 net::HttpRequestHeaders headers;
1938 headers.AddHeadersFromString(info.begin_params.headers);
1939 new_request->SetExtraRequestHeaders(headers);
1941 new_request->SetLoadFlags(load_flags);
1943 // Resolve elements from request_body and prepare upload data.
1944 if (info.request_body.get()) {
1945 storage::BlobStorageContext* blob_context = GetBlobStorageContext(
1946 GetChromeBlobStorageContextForResourceContext(resource_context));
1947 AttachRequestBodyBlobDataHandles(
1948 info.request_body.get(),
1949 blob_context);
1950 // TODO(davidben): The FileSystemContext is null here. In the case where
1951 // another renderer requested this navigation, this should be the same
1952 // FileSystemContext passed into ShouldServiceRequest.
1953 new_request->set_upload(UploadDataStreamBuilder::Build(
1954 info.request_body.get(),
1955 blob_context,
1956 nullptr, // file_system_context
1957 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1958 .get()));
1961 request_id_--;
1963 // Make extra info and read footer (contains request ID).
1965 // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so
1966 // that IO thread -> UI thread hops will work.
1967 ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
1968 PROCESS_TYPE_BROWSER,
1969 -1, // child_id
1970 -1, // route_id
1971 info.frame_tree_node_id,
1972 -1, // request_data.origin_pid,
1973 request_id_,
1974 -1, // request_data.render_frame_id,
1975 info.is_main_frame,
1976 info.parent_is_main_frame,
1977 -1, // request_data.parent_render_frame_id,
1978 resource_type,
1979 info.common_params.transition,
1980 // should_replace_current_entry. This was only maintained at layer for
1981 // request transfers and isn't needed for browser-side navigations.
1982 false,
1983 false, // is download
1984 false, // is stream
1985 info.common_params.allow_download,
1986 info.begin_params.has_user_gesture,
1987 true, // enable_load_timing
1988 false, // enable_upload_progress
1989 false, // do_not_prompt_for_login
1990 info.common_params.referrer.policy,
1991 // TODO(davidben): This is only used for prerenders. Replace
1992 // is_showing with something for that. Or maybe it just comes from the
1993 // same mechanism as the cookie one.
1994 blink::WebPageVisibilityStateVisible,
1995 resource_context,
1996 base::WeakPtr<ResourceMessageFilter>(), // filter
1997 true);
1998 // Request takes ownership.
1999 extra_info->AssociateWithRequest(new_request.get());
2001 if (new_request->url().SchemeIs(url::kBlobScheme)) {
2002 // Hang on to a reference to ensure the blob is not released prior
2003 // to the job being started.
2004 ChromeBlobStorageContext* blob_context =
2005 GetChromeBlobStorageContextForResourceContext(resource_context);
2006 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
2007 new_request.get(),
2008 blob_context->context()->GetBlobDataFromPublicURL(new_request->url()));
2011 // TODO(davidben): Attach ServiceWorkerRequestHandler.
2012 // TODO(michaeln): Help out with this and that.
2013 // TODO(davidben): Attach AppCacheInterceptor.
2015 scoped_ptr<ResourceHandler> handler(new NavigationResourceHandler(
2016 new_request.get(), loader));
2018 // TODO(davidben): Pass in the appropriate appcache_service. Also fix the
2019 // dependency on child_id/route_id. Those are used by the ResourceScheduler;
2020 // currently it's a no-op.
2021 handler = AddStandardHandlers(new_request.get(), resource_type,
2022 resource_context,
2023 nullptr, // appcache_service
2024 -1, // child_id
2025 -1, // route_id
2026 handler.Pass());
2028 BeginRequestInternal(new_request.Pass(), handler.Pass());
2031 // static
2032 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
2033 net::URLRequest* request) {
2034 // The following fields should be a minor size contribution (experimentally
2035 // on the order of 100). However since they are variable length, it could
2036 // in theory be a sizeable contribution.
2037 int strings_cost = request->extra_request_headers().ToString().size() +
2038 request->original_url().spec().size() +
2039 request->referrer().size() +
2040 request->method().size();
2042 // Note that this expression will typically be dominated by:
2043 // |kAvgBytesPerOutstandingRequest|.
2044 return kAvgBytesPerOutstandingRequest + strings_cost;
2047 void ResourceDispatcherHostImpl::BeginRequestInternal(
2048 scoped_ptr<net::URLRequest> request,
2049 scoped_ptr<ResourceHandler> handler) {
2050 DCHECK(!request->is_pending());
2051 ResourceRequestInfoImpl* info =
2052 ResourceRequestInfoImpl::ForRequest(request.get());
2054 if ((TimeTicks::Now() - last_user_gesture_time_) <
2055 TimeDelta::FromMilliseconds(kUserGestureWindowMs)) {
2056 request->SetLoadFlags(
2057 request->load_flags() | net::LOAD_MAYBE_USER_GESTURE);
2060 // Add the memory estimate that starting this request will consume.
2061 info->set_memory_cost(CalculateApproximateMemoryCost(request.get()));
2063 // If enqueing/starting this request will exceed our per-process memory
2064 // bound, abort it right away.
2065 OustandingRequestsStats stats = IncrementOutstandingRequestsMemory(1, *info);
2066 if (stats.memory_cost > max_outstanding_requests_cost_per_process_) {
2067 // We call "CancelWithError()" as a way of setting the net::URLRequest's
2068 // status -- it has no effect beyond this, since the request hasn't started.
2069 request->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
2071 bool defer = false;
2072 handler->OnResponseCompleted(request->status(), std::string(), &defer);
2073 if (defer) {
2074 // TODO(darin): The handler is not ready for us to kill the request. Oops!
2075 NOTREACHED();
2078 IncrementOutstandingRequestsMemory(-1, *info);
2080 // A ResourceHandler must not outlive its associated URLRequest.
2081 handler.reset();
2082 return;
2085 linked_ptr<ResourceLoader> loader(
2086 new ResourceLoader(request.Pass(), handler.Pass(), this));
2088 GlobalRoutingID id(info->GetGlobalRoutingID());
2089 BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.find(id);
2090 if (iter != blocked_loaders_map_.end()) {
2091 // The request should be blocked.
2092 iter->second->push_back(loader);
2093 return;
2096 StartLoading(info, loader);
2099 void ResourceDispatcherHostImpl::StartLoading(
2100 ResourceRequestInfoImpl* info,
2101 const linked_ptr<ResourceLoader>& loader) {
2102 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
2103 tracked_objects::ScopedTracker tracking_profile(
2104 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2105 "456331 ResourceDispatcherHostImpl::StartLoading"));
2106 pending_loaders_[info->GetGlobalRequestID()] = loader;
2108 loader->StartRequest();
2111 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl* contents) {
2112 last_user_gesture_time_ = TimeTicks::Now();
2115 net::URLRequest* ResourceDispatcherHostImpl::GetURLRequest(
2116 const GlobalRequestID& id) {
2117 ResourceLoader* loader = GetLoader(id);
2118 if (!loader)
2119 return NULL;
2121 return loader->request();
2124 // static
2125 bool ResourceDispatcherHostImpl::LoadInfoIsMoreInteresting(const LoadInfo& a,
2126 const LoadInfo& b) {
2127 // Set |*_uploading_size| to be the size of the corresponding upload body if
2128 // it's currently being uploaded.
2130 uint64 a_uploading_size = 0;
2131 if (a.load_state.state == net::LOAD_STATE_SENDING_REQUEST)
2132 a_uploading_size = a.upload_size;
2134 uint64 b_uploading_size = 0;
2135 if (b.load_state.state == net::LOAD_STATE_SENDING_REQUEST)
2136 b_uploading_size = b.upload_size;
2138 if (a_uploading_size != b_uploading_size)
2139 return a_uploading_size > b_uploading_size;
2141 return a.load_state.state > b.load_state.state;
2144 // static
2145 void ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread(
2146 scoped_ptr<LoadInfoMap> info_map) {
2147 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2148 // is fixed.
2149 tracked_objects::ScopedTracker tracking_profile(
2150 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2151 "466285 ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread"));
2152 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2153 for (const auto& load_info : *info_map) {
2154 RenderViewHostImpl* view = RenderViewHostImpl::FromID(
2155 load_info.first.child_id, load_info.first.route_id);
2156 // The view could be gone at this point.
2157 if (view) {
2158 view->LoadStateChanged(load_info.second.url, load_info.second.load_state,
2159 load_info.second.upload_position,
2160 load_info.second.upload_size);
2165 scoped_ptr<ResourceDispatcherHostImpl::LoadInfoMap>
2166 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes() {
2167 // Populate this map with load state changes, and then send them on to the UI
2168 // thread where they can be passed along to the respective RVHs.
2169 scoped_ptr<LoadInfoMap> info_map(new LoadInfoMap());
2171 for (const auto& loader : pending_loaders_) {
2172 net::URLRequest* request = loader.second->request();
2173 net::UploadProgress upload_progress = request->GetUploadProgress();
2175 LoadInfo load_info;
2176 load_info.url = request->url();
2177 load_info.load_state = request->GetLoadState();
2178 load_info.upload_size = upload_progress.size();
2179 load_info.upload_position = upload_progress.position();
2181 GlobalRoutingID id(loader.second->GetRequestInfo()->GetGlobalRoutingID());
2182 LoadInfoMap::iterator existing = info_map->find(id);
2184 if (existing == info_map->end() ||
2185 LoadInfoIsMoreInteresting(load_info, existing->second)) {
2186 (*info_map)[id] = load_info;
2189 return info_map.Pass();
2192 void ResourceDispatcherHostImpl::UpdateLoadInfo() {
2193 scoped_ptr<LoadInfoMap> info_map(GetLoadInfoForAllRoutes());
2195 // Stop the timer if there are no more pending requests. Future new requests
2196 // will restart it as necessary.
2197 // Also stop the timer if there are no loading clients, to avoid waking up
2198 // unnecessarily when there is a long running (hanging get) request.
2199 if (info_map->empty() || !scheduler_->HasLoadingClients()) {
2200 update_load_states_timer_->Stop();
2201 return;
2204 BrowserThread::PostTask(
2205 BrowserThread::UI, FROM_HERE,
2206 base::Bind(&ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread,
2207 base::Passed(&info_map)));
2210 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id,
2211 int route_id) {
2212 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2213 GlobalRoutingID key(child_id, route_id);
2214 DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) <<
2215 "BlockRequestsForRoute called multiple time for the same RVH";
2216 blocked_loaders_map_[key] = new BlockedLoadersList();
2219 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id,
2220 int route_id) {
2221 ProcessBlockedRequestsForRoute(child_id, route_id, false);
2224 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id,
2225 int route_id) {
2226 ProcessBlockedRequestsForRoute(child_id, route_id, true);
2229 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
2230 int child_id,
2231 int route_id,
2232 bool cancel_requests) {
2233 BlockedLoadersMap::iterator iter = blocked_loaders_map_.find(
2234 GlobalRoutingID(child_id, route_id));
2235 if (iter == blocked_loaders_map_.end()) {
2236 // It's possible to reach here if the renderer crashed while an interstitial
2237 // page was showing.
2238 return;
2241 BlockedLoadersList* loaders = iter->second;
2243 // Removing the vector from the map unblocks any subsequent requests.
2244 blocked_loaders_map_.erase(iter);
2246 for (BlockedLoadersList::iterator loaders_iter = loaders->begin();
2247 loaders_iter != loaders->end(); ++loaders_iter) {
2248 linked_ptr<ResourceLoader> loader = *loaders_iter;
2249 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
2250 if (cancel_requests) {
2251 IncrementOutstandingRequestsMemory(-1, *info);
2252 } else {
2253 StartLoading(info, loader);
2257 delete loaders;
2260 ResourceDispatcherHostImpl::HttpAuthRelationType
2261 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
2262 const GURL& request_url,
2263 const GURL& first_party) {
2264 if (!first_party.is_valid())
2265 return HTTP_AUTH_RELATION_TOP;
2267 if (net::registry_controlled_domains::SameDomainOrHost(
2268 first_party, request_url,
2269 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES))
2270 return HTTP_AUTH_RELATION_SAME_DOMAIN;
2272 if (allow_cross_origin_auth_prompt())
2273 return HTTP_AUTH_RELATION_ALLOWED_CROSS;
2275 return HTTP_AUTH_RELATION_BLOCKED_CROSS;
2278 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
2279 return allow_cross_origin_auth_prompt_;
2282 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
2283 const GlobalRequestID& id) const {
2284 ResourceLoader* loader = GetLoader(id);
2285 return loader ? loader->is_transferring() : false;
2288 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(
2289 const GlobalRequestID& id) const {
2290 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2292 LoaderMap::const_iterator i = pending_loaders_.find(id);
2293 if (i == pending_loaders_.end())
2294 return NULL;
2296 return i->second.get();
2299 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(int child_id,
2300 int request_id) const {
2301 return GetLoader(GlobalRequestID(child_id, request_id));
2304 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
2305 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
2306 DelegateMap::iterator it = delegate_map_.find(id);
2307 if (it == delegate_map_.end()) {
2308 it = delegate_map_.insert(
2309 std::make_pair(
2311 new base::ObserverList<ResourceMessageDelegate>))
2312 .first;
2314 it->second->AddObserver(delegate);
2317 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
2318 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
2319 DCHECK(ContainsKey(delegate_map_, id));
2320 DelegateMap::iterator it = delegate_map_.find(id);
2321 DCHECK(it->second->HasObserver(delegate));
2322 it->second->RemoveObserver(delegate);
2323 if (!it->second->might_have_observers()) {
2324 delete it->second;
2325 delegate_map_.erase(it);
2329 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
2330 const ResourceHostMsg_Request& request_data,
2331 int child_id,
2332 bool is_sync_load) {
2333 int load_flags = request_data.load_flags;
2335 // Although EV status is irrelevant to sub-frames and sub-resources, we have
2336 // to perform EV certificate verification on all resources because an HTTP
2337 // keep-alive connection created to load a sub-frame or a sub-resource could
2338 // be reused to load a main frame.
2339 load_flags |= net::LOAD_VERIFY_EV_CERT;
2340 if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
2341 load_flags |= net::LOAD_MAIN_FRAME;
2342 } else if (request_data.resource_type == RESOURCE_TYPE_PREFETCH) {
2343 load_flags |= net::LOAD_PREFETCH;
2346 if (is_sync_load)
2347 load_flags |= net::LOAD_IGNORE_LIMITS;
2349 ChildProcessSecurityPolicyImpl* policy =
2350 ChildProcessSecurityPolicyImpl::GetInstance();
2352 // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only
2353 // allow requesting them if requester has ReadRawCookies permission.
2354 if ((load_flags & net::LOAD_REPORT_RAW_HEADERS)
2355 && !policy->CanReadRawCookies(child_id)) {
2356 VLOG(1) << "Denied unauthorized request for raw headers";
2357 load_flags &= ~net::LOAD_REPORT_RAW_HEADERS;
2360 return load_flags;
2363 } // namespace content