Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / browser / loader / resource_dispatcher_host_impl.cc
blob81cbf8a31769c2ad1331d20fc09a3f9be1cbb9e4
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_resource_throttle.h"
45 #include "content/browser/loader/navigation_url_loader_impl_core.h"
46 #include "content/browser/loader/power_save_block_resource_throttle.h"
47 #include "content/browser/loader/redirect_to_file_resource_handler.h"
48 #include "content/browser/loader/resource_message_filter.h"
49 #include "content/browser/loader/resource_request_info_impl.h"
50 #include "content/browser/loader/stream_resource_handler.h"
51 #include "content/browser/loader/sync_resource_handler.h"
52 #include "content/browser/loader/throttling_resource_handler.h"
53 #include "content/browser/loader/upload_data_stream_builder.h"
54 #include "content/browser/renderer_host/render_view_host_delegate.h"
55 #include "content/browser/renderer_host/render_view_host_impl.h"
56 #include "content/browser/resource_context_impl.h"
57 #include "content/browser/service_worker/service_worker_request_handler.h"
58 #include "content/browser/streams/stream.h"
59 #include "content/browser/streams/stream_context.h"
60 #include "content/browser/streams/stream_registry.h"
61 #include "content/browser/web_contents/web_contents_impl.h"
62 #include "content/common/appcache_interfaces.h"
63 #include "content/common/navigation_params.h"
64 #include "content/common/resource_messages.h"
65 #include "content/common/site_isolation_policy.h"
66 #include "content/common/ssl_status_serialization.h"
67 #include "content/common/view_messages.h"
68 #include "content/public/browser/browser_thread.h"
69 #include "content/public/browser/content_browser_client.h"
70 #include "content/public/browser/download_manager.h"
71 #include "content/public/browser/download_url_parameters.h"
72 #include "content/public/browser/global_request_id.h"
73 #include "content/public/browser/plugin_service.h"
74 #include "content/public/browser/resource_dispatcher_host_delegate.h"
75 #include "content/public/browser/resource_request_details.h"
76 #include "content/public/browser/resource_throttle.h"
77 #include "content/public/browser/stream_handle.h"
78 #include "content/public/browser/stream_info.h"
79 #include "content/public/browser/user_metrics.h"
80 #include "content/public/common/content_switches.h"
81 #include "content/public/common/process_type.h"
82 #include "ipc/ipc_message_macros.h"
83 #include "ipc/ipc_message_start.h"
84 #include "net/base/auth.h"
85 #include "net/base/load_flags.h"
86 #include "net/base/mime_util.h"
87 #include "net/base/net_errors.h"
88 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
89 #include "net/base/request_priority.h"
90 #include "net/base/upload_data_stream.h"
91 #include "net/cert/cert_status_flags.h"
92 #include "net/cookies/cookie_monster.h"
93 #include "net/http/http_response_headers.h"
94 #include "net/http/http_response_info.h"
95 #include "net/ssl/ssl_cert_request_info.h"
96 #include "net/url_request/url_request.h"
97 #include "net/url_request/url_request_context.h"
98 #include "net/url_request/url_request_job_factory.h"
99 #include "storage/browser/blob/blob_data_handle.h"
100 #include "storage/browser/blob/blob_storage_context.h"
101 #include "storage/browser/blob/blob_url_request_job_factory.h"
102 #include "storage/browser/blob/shareable_file_reference.h"
103 #include "storage/browser/fileapi/file_permission_policy.h"
104 #include "storage/browser/fileapi/file_system_context.h"
105 #include "url/url_constants.h"
107 using base::Time;
108 using base::TimeDelta;
109 using base::TimeTicks;
110 using storage::ShareableFileReference;
112 // ----------------------------------------------------------------------------
114 namespace content {
116 namespace {
118 static ResourceDispatcherHostImpl* g_resource_dispatcher_host;
120 // The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates
121 const int kUpdateLoadStatesIntervalMsec = 250;
123 // Maximum byte "cost" of all the outstanding requests for a renderer.
124 // See delcaration of |max_outstanding_requests_cost_per_process_| for details.
125 // This bound is 25MB, which allows for around 6000 outstanding requests.
126 const int kMaxOutstandingRequestsCostPerProcess = 26214400;
128 // The number of milliseconds after noting a user gesture that we will
129 // tag newly-created URLRequest objects with the
130 // net::LOAD_MAYBE_USER_GESTURE load flag. This is a fairly arbitrary
131 // guess at how long to expect direct impact from a user gesture, but
132 // this should be OK as the load flag is a best-effort thing only,
133 // rather than being intended as fully accurate.
134 const int kUserGestureWindowMs = 3500;
136 // Ratio of |max_num_in_flight_requests_| that any one renderer is allowed to
137 // use. Arbitrarily chosen.
138 const double kMaxRequestsPerProcessRatio = 0.45;
140 // TODO(jkarlin): The value is high to reduce the chance of the detachable
141 // request timing out, forcing a blocked second request to open a new connection
142 // and start over. Reduce this value once we have a better idea of what it
143 // should be and once we stop blocking multiple simultaneous requests for the
144 // same resource (see bugs 46104 and 31014).
145 const int kDefaultDetachableCancelDelayMs = 30000;
147 enum SHA1HistogramTypes {
148 // SHA-1 is not present in the certificate chain.
149 SHA1_NOT_PRESENT = 0,
150 // SHA-1 is present in the certificate chain, and the leaf expires on or
151 // after January 1, 2017.
152 SHA1_EXPIRES_AFTER_JANUARY_2017 = 1,
153 // SHA-1 is present in the certificate chain, and the leaf expires on or
154 // after June 1, 2016.
155 SHA1_EXPIRES_AFTER_JUNE_2016 = 2,
156 // SHA-1 is present in the certificate chain, and the leaf expires on or
157 // after January 1, 2016.
158 SHA1_EXPIRES_AFTER_JANUARY_2016 = 3,
159 // SHA-1 is present in the certificate chain, but the leaf expires before
160 // January 1, 2016
161 SHA1_PRESENT = 4,
162 // Always keep this at the end.
163 SHA1_HISTOGRAM_TYPES_MAX,
166 void RecordCertificateHistograms(const net::SSLInfo& ssl_info,
167 ResourceType resource_type) {
168 // The internal representation of the dates for UI treatment of SHA-1.
169 // See http://crbug.com/401365 for details
170 static const int64_t kJanuary2017 = INT64_C(13127702400000000);
171 static const int64_t kJune2016 = INT64_C(13109213000000000);
172 static const int64_t kJanuary2016 = INT64_C(13096080000000000);
174 SHA1HistogramTypes sha1_histogram = SHA1_NOT_PRESENT;
175 if (ssl_info.cert_status & net::CERT_STATUS_SHA1_SIGNATURE_PRESENT) {
176 DCHECK(ssl_info.cert.get());
177 if (ssl_info.cert->valid_expiry() >=
178 base::Time::FromInternalValue(kJanuary2017)) {
179 sha1_histogram = SHA1_EXPIRES_AFTER_JANUARY_2017;
180 } else if (ssl_info.cert->valid_expiry() >=
181 base::Time::FromInternalValue(kJune2016)) {
182 sha1_histogram = SHA1_EXPIRES_AFTER_JUNE_2016;
183 } else if (ssl_info.cert->valid_expiry() >=
184 base::Time::FromInternalValue(kJanuary2016)) {
185 sha1_histogram = SHA1_EXPIRES_AFTER_JANUARY_2016;
186 } else {
187 sha1_histogram = SHA1_PRESENT;
190 if (resource_type == RESOURCE_TYPE_MAIN_FRAME) {
191 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.MainFrame",
192 sha1_histogram,
193 SHA1_HISTOGRAM_TYPES_MAX);
194 } else {
195 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.Subresource",
196 sha1_histogram,
197 SHA1_HISTOGRAM_TYPES_MAX);
201 bool IsDetachableResourceType(ResourceType type) {
202 switch (type) {
203 case RESOURCE_TYPE_PREFETCH:
204 case RESOURCE_TYPE_PING:
205 return true;
206 default:
207 return false;
211 // Aborts a request before an URLRequest has actually been created.
212 void AbortRequestBeforeItStarts(ResourceMessageFilter* filter,
213 IPC::Message* sync_result,
214 int request_id) {
215 if (sync_result) {
216 SyncLoadResult result;
217 result.error_code = net::ERR_ABORTED;
218 ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result, result);
219 filter->Send(sync_result);
220 } else {
221 // Tell the renderer that this request was disallowed.
222 ResourceMsg_RequestCompleteData request_complete_data;
223 request_complete_data.error_code = net::ERR_ABORTED;
224 request_complete_data.was_ignored_by_handler = false;
225 request_complete_data.exists_in_cache = false;
226 // No security info needed, connection not established.
227 request_complete_data.completion_time = base::TimeTicks();
228 request_complete_data.encoded_data_length = 0;
229 filter->Send(new ResourceMsg_RequestComplete(
230 request_id, request_complete_data));
234 void SetReferrerForRequest(net::URLRequest* request, const Referrer& referrer) {
235 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
236 if (!referrer.url.is_valid() ||
237 command_line->HasSwitch(switches::kNoReferrers)) {
238 request->SetReferrer(std::string());
239 } else {
240 request->SetReferrer(referrer.url.spec());
243 net::URLRequest::ReferrerPolicy net_referrer_policy =
244 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
245 switch (referrer.policy) {
246 case blink::WebReferrerPolicyAlways:
247 case blink::WebReferrerPolicyNever:
248 case blink::WebReferrerPolicyOrigin:
249 net_referrer_policy = net::URLRequest::NEVER_CLEAR_REFERRER;
250 break;
251 case blink::WebReferrerPolicyNoReferrerWhenDowngrade:
252 net_referrer_policy =
253 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
254 break;
255 case blink::WebReferrerPolicyOriginWhenCrossOrigin:
256 net_referrer_policy =
257 net::URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN;
258 break;
259 case blink::WebReferrerPolicyDefault:
260 default:
261 net_referrer_policy =
262 command_line->HasSwitch(switches::kReducedReferrerGranularity)
263 ? net::URLRequest::
264 REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
265 : net::URLRequest::
266 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
267 break;
269 request->set_referrer_policy(net_referrer_policy);
272 // Consults the RendererSecurity policy to determine whether the
273 // ResourceDispatcherHostImpl should service this request. A request might be
274 // disallowed if the renderer is not authorized to retrieve the request URL or
275 // if the renderer is attempting to upload an unauthorized file.
276 bool ShouldServiceRequest(int process_type,
277 int child_id,
278 const ResourceHostMsg_Request& request_data,
279 const net::HttpRequestHeaders& headers,
280 ResourceMessageFilter* filter,
281 ResourceContext* resource_context) {
282 if (process_type == PROCESS_TYPE_PLUGIN)
283 return true;
285 ChildProcessSecurityPolicyImpl* policy =
286 ChildProcessSecurityPolicyImpl::GetInstance();
288 // Check if the renderer is permitted to request the requested URL.
289 if (!policy->CanRequestURL(child_id, request_data.url)) {
290 VLOG(1) << "Denied unauthorized request for "
291 << request_data.url.possibly_invalid_spec();
292 return false;
295 // Check if the renderer is using an illegal Origin header. If so, kill it.
296 std::string origin_string;
297 bool has_origin = headers.GetHeader("Origin", &origin_string) &&
298 origin_string != "null";
299 if (has_origin) {
300 GURL origin(origin_string);
301 if (!policy->CanCommitURL(child_id, origin) ||
302 GetContentClient()->browser()->IsIllegalOrigin(resource_context,
303 child_id, origin)) {
304 VLOG(1) << "Killed renderer for illegal origin: " << origin_string;
305 bad_message::ReceivedBadMessage(filter, bad_message::RDH_ILLEGAL_ORIGIN);
306 return false;
310 // Check if the renderer is permitted to upload the requested files.
311 if (request_data.request_body.get()) {
312 const std::vector<ResourceRequestBody::Element>* uploads =
313 request_data.request_body->elements();
314 std::vector<ResourceRequestBody::Element>::const_iterator iter;
315 for (iter = uploads->begin(); iter != uploads->end(); ++iter) {
316 if (iter->type() == ResourceRequestBody::Element::TYPE_FILE &&
317 !policy->CanReadFile(child_id, iter->path())) {
318 NOTREACHED() << "Denied unauthorized upload of "
319 << iter->path().value();
320 return false;
322 if (iter->type() == ResourceRequestBody::Element::TYPE_FILE_FILESYSTEM) {
323 storage::FileSystemURL url =
324 filter->file_system_context()->CrackURL(iter->filesystem_url());
325 if (!policy->CanReadFileSystemFile(child_id, url)) {
326 NOTREACHED() << "Denied unauthorized upload of "
327 << iter->filesystem_url().spec();
328 return false;
334 return true;
337 void RemoveDownloadFileFromChildSecurityPolicy(int child_id,
338 const base::FilePath& path) {
339 ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile(
340 child_id, path);
343 DownloadInterruptReason CallbackAndReturn(
344 const DownloadUrlParameters::OnStartedCallback& started_cb,
345 DownloadInterruptReason interrupt_reason) {
346 if (started_cb.is_null())
347 return interrupt_reason;
348 BrowserThread::PostTask(
349 BrowserThread::UI,
350 FROM_HERE,
351 base::Bind(
352 started_cb, static_cast<DownloadItem*>(NULL), interrupt_reason));
354 return interrupt_reason;
357 int GetCertID(net::URLRequest* request, int child_id) {
358 if (request->ssl_info().cert.get()) {
359 return CertStore::GetInstance()->StoreCert(request->ssl_info().cert.get(),
360 child_id);
362 return 0;
365 void NotifyRedirectOnUI(int render_process_id,
366 int render_frame_host,
367 scoped_ptr<ResourceRedirectDetails> details) {
368 RenderFrameHostImpl* host =
369 RenderFrameHostImpl::FromID(render_process_id, render_frame_host);
370 WebContentsImpl* web_contents =
371 static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(host));
372 if (!web_contents)
373 return;
374 web_contents->DidGetRedirectForResourceRequest(host, *details.get());
377 void NotifyResponseOnUI(int render_process_id,
378 int render_frame_host,
379 scoped_ptr<ResourceRequestDetails> details) {
380 RenderFrameHostImpl* host =
381 RenderFrameHostImpl::FromID(render_process_id, render_frame_host);
382 WebContentsImpl* web_contents =
383 static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(host));
384 if (!web_contents)
385 return;
386 web_contents->DidGetResourceResponseStart(*details.get());
389 bool IsValidatedSCT(
390 const net::SignedCertificateTimestampAndStatus& sct_status) {
391 return sct_status.status == net::ct::SCT_STATUS_OK;
394 storage::BlobStorageContext* GetBlobStorageContext(
395 ChromeBlobStorageContext* blob_storage_context) {
396 if (!blob_storage_context)
397 return NULL;
398 return blob_storage_context->context();
401 void AttachRequestBodyBlobDataHandles(
402 ResourceRequestBody* body,
403 storage::BlobStorageContext* blob_context) {
404 DCHECK(blob_context);
405 for (size_t i = 0; i < body->elements()->size(); ++i) {
406 const ResourceRequestBody::Element& element = (*body->elements())[i];
407 if (element.type() != ResourceRequestBody::Element::TYPE_BLOB)
408 continue;
409 scoped_ptr<storage::BlobDataHandle> handle =
410 blob_context->GetBlobDataFromUUID(element.blob_uuid());
411 DCHECK(handle);
412 if (!handle)
413 continue;
414 // Ensure the blob and any attached shareable files survive until
415 // upload completion. The |body| takes ownership of |handle|.
416 const void* key = handle.get();
417 body->SetUserData(key, handle.release());
421 // PlzNavigate
422 // This method is called in the UI thread to send the timestamp of a resource
423 // request to the respective Navigator (for an UMA histogram).
424 void LogResourceRequestTimeOnUI(
425 base::TimeTicks timestamp,
426 int render_process_id,
427 int render_frame_id,
428 const GURL& url) {
429 DCHECK_CURRENTLY_ON(BrowserThread::UI);
430 RenderFrameHostImpl* host =
431 RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
432 if (host != NULL) {
433 DCHECK(host->frame_tree_node()->IsMainFrame());
434 host->frame_tree_node()->navigator()->LogResourceRequestTime(
435 timestamp, url);
439 } // namespace
441 // static
442 ResourceDispatcherHost* ResourceDispatcherHost::Get() {
443 return g_resource_dispatcher_host;
446 ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
447 : save_file_manager_(new SaveFileManager()),
448 request_id_(-1),
449 is_shutdown_(false),
450 num_in_flight_requests_(0),
451 max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()),
452 max_num_in_flight_requests_per_process_(
453 static_cast<int>(
454 max_num_in_flight_requests_ * kMaxRequestsPerProcessRatio)),
455 max_outstanding_requests_cost_per_process_(
456 kMaxOutstandingRequestsCostPerProcess),
457 filter_(NULL),
458 delegate_(NULL),
459 allow_cross_origin_auth_prompt_(false) {
460 DCHECK_CURRENTLY_ON(BrowserThread::UI);
461 DCHECK(!g_resource_dispatcher_host);
462 g_resource_dispatcher_host = this;
464 GetContentClient()->browser()->ResourceDispatcherHostCreated();
466 ANNOTATE_BENIGN_RACE(
467 &last_user_gesture_time_,
468 "We don't care about the precise value, see http://crbug.com/92889");
470 BrowserThread::PostTask(BrowserThread::IO,
471 FROM_HERE,
472 base::Bind(&ResourceDispatcherHostImpl::OnInit,
473 base::Unretained(this)));
475 update_load_states_timer_.reset(
476 new base::RepeatingTimer<ResourceDispatcherHostImpl>());
479 ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() {
480 DCHECK(outstanding_requests_stats_map_.empty());
481 DCHECK(g_resource_dispatcher_host);
482 g_resource_dispatcher_host = NULL;
485 // static
486 ResourceDispatcherHostImpl* ResourceDispatcherHostImpl::Get() {
487 return g_resource_dispatcher_host;
490 void ResourceDispatcherHostImpl::SetDelegate(
491 ResourceDispatcherHostDelegate* delegate) {
492 delegate_ = delegate;
495 void ResourceDispatcherHostImpl::SetAllowCrossOriginAuthPrompt(bool value) {
496 allow_cross_origin_auth_prompt_ = value;
499 void ResourceDispatcherHostImpl::AddResourceContext(ResourceContext* context) {
500 active_resource_contexts_.insert(context);
503 void ResourceDispatcherHostImpl::RemoveResourceContext(
504 ResourceContext* context) {
505 CHECK(ContainsKey(active_resource_contexts_, context));
506 active_resource_contexts_.erase(context);
509 void ResourceDispatcherHostImpl::CancelRequestsForContext(
510 ResourceContext* context) {
511 DCHECK_CURRENTLY_ON(BrowserThread::IO);
512 DCHECK(context);
514 CHECK(ContainsKey(active_resource_contexts_, context));
516 // Note that request cancellation has side effects. Therefore, we gather all
517 // the requests to cancel first, and then we start cancelling. We assert at
518 // the end that there are no more to cancel since the context is about to go
519 // away.
520 typedef std::vector<linked_ptr<ResourceLoader>> LoaderList;
521 LoaderList loaders_to_cancel;
523 for (LoaderMap::iterator i = pending_loaders_.begin();
524 i != pending_loaders_.end();) {
525 if (i->second->GetRequestInfo()->GetContext() == context) {
526 loaders_to_cancel.push_back(i->second);
527 IncrementOutstandingRequestsMemory(-1, *i->second->GetRequestInfo());
528 pending_loaders_.erase(i++);
529 } else {
530 ++i;
534 for (BlockedLoadersMap::iterator i = blocked_loaders_map_.begin();
535 i != blocked_loaders_map_.end();) {
536 BlockedLoadersList* loaders = i->second;
537 if (loaders->empty()) {
538 // This can happen if BlockRequestsForRoute() has been called for a route,
539 // but we haven't blocked any matching requests yet.
540 ++i;
541 continue;
543 ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo();
544 if (info->GetContext() == context) {
545 blocked_loaders_map_.erase(i++);
546 for (BlockedLoadersList::const_iterator it = loaders->begin();
547 it != loaders->end(); ++it) {
548 linked_ptr<ResourceLoader> loader = *it;
549 info = loader->GetRequestInfo();
550 // We make the assumption that all requests on the list have the same
551 // ResourceContext.
552 DCHECK_EQ(context, info->GetContext());
553 IncrementOutstandingRequestsMemory(-1, *info);
554 loaders_to_cancel.push_back(loader);
556 delete loaders;
557 } else {
558 ++i;
562 #ifndef NDEBUG
563 for (LoaderList::iterator i = loaders_to_cancel.begin();
564 i != loaders_to_cancel.end(); ++i) {
565 // There is no strict requirement that this be the case, but currently
566 // downloads, streams, detachable requests, transferred requests, and
567 // browser-owned requests are the only requests that aren't cancelled when
568 // the associated processes go away. It may be OK for this invariant to
569 // change in the future, but if this assertion fires without the invariant
570 // changing, then it's indicative of a leak.
571 DCHECK((*i)->GetRequestInfo()->IsDownload() ||
572 (*i)->GetRequestInfo()->is_stream() ||
573 ((*i)->GetRequestInfo()->detachable_handler() &&
574 (*i)->GetRequestInfo()->detachable_handler()->is_detached()) ||
575 (*i)->GetRequestInfo()->GetProcessType() == PROCESS_TYPE_BROWSER ||
576 (*i)->is_transferring());
578 #endif
580 loaders_to_cancel.clear();
582 // Validate that no more requests for this context were added.
583 for (LoaderMap::const_iterator i = pending_loaders_.begin();
584 i != pending_loaders_.end(); ++i) {
585 // http://crbug.com/90971
586 CHECK_NE(i->second->GetRequestInfo()->GetContext(), context);
589 for (BlockedLoadersMap::const_iterator i = blocked_loaders_map_.begin();
590 i != blocked_loaders_map_.end(); ++i) {
591 BlockedLoadersList* loaders = i->second;
592 if (!loaders->empty()) {
593 ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo();
594 // http://crbug.com/90971
595 CHECK_NE(info->GetContext(), context);
600 DownloadInterruptReason ResourceDispatcherHostImpl::BeginDownload(
601 scoped_ptr<net::URLRequest> request,
602 const Referrer& referrer,
603 bool is_content_initiated,
604 ResourceContext* context,
605 int child_id,
606 int render_view_route_id,
607 int render_frame_route_id,
608 bool prefer_cache,
609 bool do_not_prompt_for_login,
610 scoped_ptr<DownloadSaveInfo> save_info,
611 uint32 download_id,
612 const DownloadStartedCallback& started_callback) {
613 if (is_shutdown_)
614 return CallbackAndReturn(started_callback,
615 DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN);
617 const GURL& url = request->original_url();
619 // http://crbug.com/90971
620 char url_buf[128];
621 base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
622 base::debug::Alias(url_buf);
623 CHECK(ContainsKey(active_resource_contexts_, context));
625 SetReferrerForRequest(request.get(), referrer);
627 int extra_load_flags = net::LOAD_NORMAL;
628 if (prefer_cache) {
629 // If there is upload data attached, only retrieve from cache because there
630 // is no current mechanism to prompt the user for their consent for a
631 // re-post. For GETs, try to retrieve data from the cache and skip
632 // validating the entry if present.
633 if (request->get_upload() != NULL)
634 extra_load_flags |= net::LOAD_ONLY_FROM_CACHE;
635 else
636 extra_load_flags |= net::LOAD_PREFERRING_CACHE;
637 } else {
638 extra_load_flags |= net::LOAD_DISABLE_CACHE;
640 request->SetLoadFlags(request->load_flags() | extra_load_flags);
642 // We treat a download as a main frame load, and thus update the policy URL on
643 // redirects.
645 // TODO(davidben): Is this correct? If this came from a
646 // ViewHostMsg_DownloadUrl in a frame, should it have first-party URL set
647 // appropriately?
648 request->set_first_party_url_policy(
649 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
651 // Check if the renderer is permitted to request the requested URL.
652 if (!ChildProcessSecurityPolicyImpl::GetInstance()->
653 CanRequestURL(child_id, url)) {
654 VLOG(1) << "Denied unauthorized download request for "
655 << url.possibly_invalid_spec();
656 return CallbackAndReturn(started_callback,
657 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST);
660 request_id_--;
662 const net::URLRequestContext* request_context = context->GetRequestContext();
663 if (!request_context->job_factory()->IsHandledURL(url)) {
664 VLOG(1) << "Download request for unsupported protocol: "
665 << url.possibly_invalid_spec();
666 return CallbackAndReturn(started_callback,
667 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST);
670 ResourceRequestInfoImpl* extra_info =
671 CreateRequestInfo(child_id, render_view_route_id,
672 render_frame_route_id, true, context);
673 extra_info->set_do_not_prompt_for_login(do_not_prompt_for_login);
674 extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
676 if (request->url().SchemeIs(url::kBlobScheme)) {
677 ChromeBlobStorageContext* blob_context =
678 GetChromeBlobStorageContextForResourceContext(context);
679 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
680 request.get(),
681 blob_context->context()->GetBlobDataFromPublicURL(request->url()));
684 // From this point forward, the |DownloadResourceHandler| is responsible for
685 // |started_callback|.
686 scoped_ptr<ResourceHandler> handler(
687 CreateResourceHandlerForDownload(request.get(), is_content_initiated,
688 true, download_id, save_info.Pass(),
689 started_callback));
691 BeginRequestInternal(request.Pass(), handler.Pass());
693 return DOWNLOAD_INTERRUPT_REASON_NONE;
696 void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest(
697 net::URLRequest* request) {
698 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
699 if (info) {
700 ResourceLoader* loader = GetLoader(info->GetGlobalRequestID());
701 if (loader)
702 loader->ClearLoginDelegate();
706 void ResourceDispatcherHostImpl::Shutdown() {
707 DCHECK_CURRENTLY_ON(BrowserThread::UI);
708 BrowserThread::PostTask(BrowserThread::IO,
709 FROM_HERE,
710 base::Bind(&ResourceDispatcherHostImpl::OnShutdown,
711 base::Unretained(this)));
714 scoped_ptr<ResourceHandler>
715 ResourceDispatcherHostImpl::CreateResourceHandlerForDownload(
716 net::URLRequest* request,
717 bool is_content_initiated,
718 bool must_download,
719 uint32 id,
720 scoped_ptr<DownloadSaveInfo> save_info,
721 const DownloadUrlParameters::OnStartedCallback& started_cb) {
722 scoped_ptr<ResourceHandler> handler(
723 new DownloadResourceHandler(id, request, started_cb, save_info.Pass()));
724 if (delegate_) {
725 const ResourceRequestInfo* request_info(
726 ResourceRequestInfo::ForRequest(request));
728 ScopedVector<ResourceThrottle> throttles;
729 delegate_->DownloadStarting(
730 request, request_info->GetContext(), request_info->GetChildID(),
731 request_info->GetRouteID(), request_info->GetRequestID(),
732 is_content_initiated, must_download, &throttles);
733 if (!throttles.empty()) {
734 handler.reset(
735 new ThrottlingResourceHandler(
736 handler.Pass(), request, throttles.Pass()));
739 return handler.Pass();
742 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::MaybeInterceptAsStream(
743 const base::FilePath& plugin_path,
744 net::URLRequest* request,
745 ResourceResponse* response,
746 std::string* payload) {
747 payload->clear();
748 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
749 const std::string& mime_type = response->head.mime_type;
751 GURL origin;
752 if (!delegate_ ||
753 !delegate_->ShouldInterceptResourceAsStream(
754 request, plugin_path, mime_type, &origin, payload)) {
755 return scoped_ptr<ResourceHandler>();
758 StreamContext* stream_context =
759 GetStreamContextForResourceContext(info->GetContext());
761 scoped_ptr<StreamResourceHandler> handler(
762 new StreamResourceHandler(request,
763 stream_context->registry(),
764 origin));
766 info->set_is_stream(true);
767 scoped_ptr<StreamInfo> stream_info(new StreamInfo);
768 stream_info->handle = handler->stream()->CreateHandle();
769 stream_info->original_url = request->url();
770 stream_info->mime_type = mime_type;
771 // Make a copy of the response headers so it is safe to pass across threads;
772 // the old handler (AsyncResourceHandler) may modify it in parallel via the
773 // ResourceDispatcherHostDelegate.
774 if (response->head.headers.get()) {
775 stream_info->response_headers =
776 new net::HttpResponseHeaders(response->head.headers->raw_headers());
778 delegate_->OnStreamCreated(request, stream_info.Pass());
779 return handler.Pass();
782 ResourceDispatcherHostLoginDelegate*
783 ResourceDispatcherHostImpl::CreateLoginDelegate(
784 ResourceLoader* loader,
785 net::AuthChallengeInfo* auth_info) {
786 if (!delegate_)
787 return NULL;
789 return delegate_->CreateLoginDelegate(auth_info, loader->request());
792 bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader* loader,
793 const GURL& url) {
794 if (!delegate_)
795 return false;
797 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
799 if (!IsResourceTypeFrame(info->GetResourceType()))
800 return false;
802 const net::URLRequestJobFactory* job_factory =
803 info->GetContext()->GetRequestContext()->job_factory();
804 if (job_factory->IsHandledURL(url))
805 return false;
807 return delegate_->HandleExternalProtocol(
808 url, info->GetChildID(), info->GetRouteID(), info->IsMainFrame(),
809 info->GetPageTransition(), info->HasUserGesture());
812 void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader* loader) {
813 // Make sure we have the load state monitor running.
814 if (!update_load_states_timer_->IsRunning() &&
815 scheduler_->HasLoadingClients()) {
816 update_load_states_timer_->Start(
817 FROM_HERE, TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec),
818 this, &ResourceDispatcherHostImpl::UpdateLoadInfo);
822 void ResourceDispatcherHostImpl::DidReceiveRedirect(ResourceLoader* loader,
823 const GURL& new_url) {
824 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
826 int render_process_id, render_frame_host;
827 if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host))
828 return;
830 // Don't notify WebContents observers for requests known to be
831 // downloads; they aren't really associated with the Webcontents.
832 // Note that not all downloads are known before content sniffing.
833 if (info->IsDownload())
834 return;
836 // Notify the observers on the UI thread.
837 scoped_ptr<ResourceRedirectDetails> detail(new ResourceRedirectDetails(
838 loader->request(),
839 GetCertID(loader->request(), info->GetChildID()),
840 new_url));
841 BrowserThread::PostTask(
842 BrowserThread::UI, FROM_HERE,
843 base::Bind(
844 &NotifyRedirectOnUI,
845 render_process_id, render_frame_host, base::Passed(&detail)));
848 void ResourceDispatcherHostImpl::DidReceiveResponse(ResourceLoader* loader) {
849 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
850 net::URLRequest* request = loader->request();
851 if (request->was_fetched_via_proxy() &&
852 request->was_fetched_via_spdy() &&
853 request->url().SchemeIs(url::kHttpScheme)) {
854 scheduler_->OnReceivedSpdyProxiedHttpResponse(
855 info->GetChildID(), info->GetRouteID());
858 int render_process_id, render_frame_host;
859 if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host))
860 return;
862 // Don't notify WebContents observers for requests known to be
863 // downloads; they aren't really associated with the Webcontents.
864 // Note that not all downloads are known before content sniffing.
865 if (info->IsDownload())
866 return;
868 // Notify the observers on the UI thread.
869 scoped_ptr<ResourceRequestDetails> detail(new ResourceRequestDetails(
870 request, GetCertID(request, info->GetChildID())));
871 BrowserThread::PostTask(
872 BrowserThread::UI, FROM_HERE,
873 base::Bind(
874 &NotifyResponseOnUI,
875 render_process_id, render_frame_host, base::Passed(&detail)));
878 void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader* loader) {
879 ResourceRequestInfo* info = loader->GetRequestInfo();
881 // Record final result of all resource loads.
882 if (info->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME) {
883 // This enumeration has "3" appended to its name to distinguish it from
884 // older versions.
885 UMA_HISTOGRAM_SPARSE_SLOWLY(
886 "Net.ErrorCodesForMainFrame3",
887 -loader->request()->status().error());
889 // Record time to success and error for the most common errors, and for
890 // the aggregate remainder errors.
891 base::TimeDelta request_loading_time(
892 base::TimeTicks::Now() - loader->request()->creation_time());
893 switch (loader->request()->status().error()) {
894 case net::OK:
895 UMA_HISTOGRAM_LONG_TIMES(
896 "Net.RequestTime2.Success", request_loading_time);
897 break;
898 case net::ERR_ABORTED:
899 UMA_HISTOGRAM_LONG_TIMES(
900 "Net.RequestTime2.ErrAborted", request_loading_time);
901 break;
902 case net::ERR_CONNECTION_RESET:
903 UMA_HISTOGRAM_LONG_TIMES(
904 "Net.RequestTime2.ErrConnectionReset", request_loading_time);
905 break;
906 case net::ERR_CONNECTION_TIMED_OUT:
907 UMA_HISTOGRAM_LONG_TIMES(
908 "Net.RequestTime2.ErrConnectionTimedOut", request_loading_time);
909 break;
910 case net::ERR_INTERNET_DISCONNECTED:
911 UMA_HISTOGRAM_LONG_TIMES(
912 "Net.RequestTime2.ErrInternetDisconnected", request_loading_time);
913 break;
914 case net::ERR_NAME_NOT_RESOLVED:
915 UMA_HISTOGRAM_LONG_TIMES(
916 "Net.RequestTime2.ErrNameNotResolved", request_loading_time);
917 break;
918 case net::ERR_TIMED_OUT:
919 UMA_HISTOGRAM_LONG_TIMES(
920 "Net.RequestTime2.ErrTimedOut", request_loading_time);
921 break;
922 default:
923 UMA_HISTOGRAM_LONG_TIMES(
924 "Net.RequestTime2.MiscError", request_loading_time);
925 break;
928 if (loader->request()->url().SchemeIsCryptographic()) {
929 if (loader->request()->url().host() == "www.google.com") {
930 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2",
931 -loader->request()->status().error());
934 int num_valid_scts = std::count_if(
935 loader->request()->ssl_info().signed_certificate_timestamps.begin(),
936 loader->request()->ssl_info().signed_certificate_timestamps.end(),
937 IsValidatedSCT);
938 UMA_HISTOGRAM_COUNTS_100(
939 "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts);
941 } else {
942 if (info->GetResourceType() == RESOURCE_TYPE_IMAGE) {
943 UMA_HISTOGRAM_SPARSE_SLOWLY(
944 "Net.ErrorCodesForImages",
945 -loader->request()->status().error());
947 // This enumeration has "2" appended to distinguish it from older versions.
948 UMA_HISTOGRAM_SPARSE_SLOWLY(
949 "Net.ErrorCodesForSubresources2",
950 -loader->request()->status().error());
953 if (loader->request()->url().SchemeIsCryptographic()) {
954 RecordCertificateHistograms(loader->request()->ssl_info(),
955 info->GetResourceType());
958 if (delegate_)
959 delegate_->RequestComplete(loader->request());
961 // Destroy the ResourceLoader.
962 RemovePendingRequest(info->GetChildID(), info->GetRequestID());
965 void ResourceDispatcherHostImpl::OnInit() {
966 scheduler_.reset(new ResourceScheduler);
969 void ResourceDispatcherHostImpl::OnShutdown() {
970 DCHECK_CURRENTLY_ON(BrowserThread::IO);
972 is_shutdown_ = true;
973 pending_loaders_.clear();
975 // Make sure we shutdown the timer now, otherwise by the time our destructor
976 // runs if the timer is still running the Task is deleted twice (once by
977 // the MessageLoop and the second time by RepeatingTimer).
978 update_load_states_timer_.reset();
980 // Clear blocked requests if any left.
981 // Note that we have to do this in 2 passes as we cannot call
982 // CancelBlockedRequestsForRoute while iterating over
983 // blocked_loaders_map_, as it modifies it.
984 std::set<GlobalRoutingID> ids;
985 for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
986 iter != blocked_loaders_map_.end(); ++iter) {
987 std::pair<std::set<GlobalRoutingID>::iterator, bool> result =
988 ids.insert(iter->first);
989 // We should not have duplicates.
990 DCHECK(result.second);
992 for (std::set<GlobalRoutingID>::const_iterator iter = ids.begin();
993 iter != ids.end(); ++iter) {
994 CancelBlockedRequestsForRoute(iter->child_id, iter->route_id);
997 scheduler_.reset();
1000 bool ResourceDispatcherHostImpl::OnMessageReceived(
1001 const IPC::Message& message,
1002 ResourceMessageFilter* filter) {
1003 filter_ = filter;
1004 bool handled = true;
1005 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcherHostImpl, message)
1006 IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource, OnRequestResource)
1007 IPC_MESSAGE_HANDLER_DELAY_REPLY(ResourceHostMsg_SyncLoad, OnSyncLoad)
1008 IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile,
1009 OnReleaseDownloadedFile)
1010 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataDownloaded_ACK, OnDataDownloadedACK)
1011 IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest, OnCancelRequest)
1012 IPC_MESSAGE_HANDLER(ResourceHostMsg_DidChangePriority, OnDidChangePriority)
1013 IPC_MESSAGE_UNHANDLED(handled = false)
1014 IPC_END_MESSAGE_MAP()
1016 if (!handled && IPC_MESSAGE_ID_CLASS(message.type()) == ResourceMsgStart) {
1017 base::PickleIterator iter(message);
1018 int request_id = -1;
1019 bool ok = iter.ReadInt(&request_id);
1020 DCHECK(ok);
1021 GlobalRequestID id(filter_->child_id(), request_id);
1022 DelegateMap::iterator it = delegate_map_.find(id);
1023 if (it != delegate_map_.end()) {
1024 base::ObserverList<ResourceMessageDelegate>::Iterator del_it(it->second);
1025 ResourceMessageDelegate* delegate;
1026 while (!handled && (delegate = del_it.GetNext()) != NULL) {
1027 handled = delegate->OnMessageReceived(message);
1031 // As the unhandled resource message effectively has no consumer, mark it as
1032 // handled to prevent needless propagation through the filter pipeline.
1033 handled = true;
1036 filter_ = NULL;
1037 return handled;
1040 void ResourceDispatcherHostImpl::OnRequestResource(
1041 int routing_id,
1042 int request_id,
1043 const ResourceHostMsg_Request& request_data) {
1044 // TODO(pkasting): Remove ScopedTracker below once crbug.com/477117 is fixed.
1045 tracked_objects::ScopedTracker tracking_profile(
1046 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1047 "477117 ResourceDispatcherHostImpl::OnRequestResource"));
1048 // When logging time-to-network only care about main frame and non-transfer
1049 // navigations.
1050 if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME &&
1051 request_data.transferred_request_request_id == -1 &&
1052 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1053 switches::kEnableBrowserSideNavigation)) {
1054 BrowserThread::PostTask(
1055 BrowserThread::UI,
1056 FROM_HERE,
1057 base::Bind(&LogResourceRequestTimeOnUI,
1058 TimeTicks::Now(),
1059 filter_->child_id(),
1060 request_data.render_frame_id,
1061 request_data.url));
1063 BeginRequest(request_id, request_data, NULL, routing_id);
1066 // Begins a resource request with the given params on behalf of the specified
1067 // child process. Responses will be dispatched through the given receiver. The
1068 // process ID is used to lookup WebContentsImpl from routing_id's in the case of
1069 // a request from a renderer. request_context is the cookie/cache context to be
1070 // used for this request.
1072 // If sync_result is non-null, then a SyncLoad reply will be generated, else
1073 // a normal asynchronous set of response messages will be generated.
1074 void ResourceDispatcherHostImpl::OnSyncLoad(
1075 int request_id,
1076 const ResourceHostMsg_Request& request_data,
1077 IPC::Message* sync_result) {
1078 BeginRequest(request_id, request_data, sync_result,
1079 sync_result->routing_id());
1082 void ResourceDispatcherHostImpl::UpdateRequestForTransfer(
1083 int child_id,
1084 int route_id,
1085 int request_id,
1086 const ResourceHostMsg_Request& request_data,
1087 const linked_ptr<ResourceLoader>& loader) {
1088 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
1089 GlobalRoutingID old_routing_id(
1090 request_data.transferred_request_child_id, info->GetRouteID());
1091 GlobalRequestID old_request_id(request_data.transferred_request_child_id,
1092 request_data.transferred_request_request_id);
1093 GlobalRoutingID new_routing_id(child_id, route_id);
1094 GlobalRequestID new_request_id(child_id, request_id);
1096 // Clear out data that depends on |info| before updating it.
1097 // We always need to move the memory stats to the new process. In contrast,
1098 // stats.num_requests is only tracked for some requests (those that require
1099 // file descriptors for their shared memory buffer).
1100 IncrementOutstandingRequestsMemory(-1, *info);
1101 bool should_update_count = info->counted_as_in_flight_request();
1102 if (should_update_count)
1103 IncrementOutstandingRequestsCount(-1, info);
1104 pending_loaders_.erase(old_request_id);
1106 // ResourceHandlers should always get state related to the request from the
1107 // ResourceRequestInfo rather than caching it locally. This lets us update
1108 // the info object when a transfer occurs.
1109 info->UpdateForTransfer(child_id, route_id, request_data.origin_pid,
1110 request_id, request_data.parent_render_frame_id,
1111 filter_->GetWeakPtr());
1113 // Update maps that used the old IDs, if necessary. Some transfers in tests
1114 // do not actually use a different ID, so not all maps need to be updated.
1115 pending_loaders_[new_request_id] = loader;
1116 IncrementOutstandingRequestsMemory(1, *info);
1117 if (should_update_count)
1118 IncrementOutstandingRequestsCount(1, info);
1119 if (old_routing_id != new_routing_id) {
1120 if (blocked_loaders_map_.find(old_routing_id) !=
1121 blocked_loaders_map_.end()) {
1122 blocked_loaders_map_[new_routing_id] =
1123 blocked_loaders_map_[old_routing_id];
1124 blocked_loaders_map_.erase(old_routing_id);
1127 if (old_request_id != new_request_id) {
1128 DelegateMap::iterator it = delegate_map_.find(old_request_id);
1129 if (it != delegate_map_.end()) {
1130 // Tell each delegate that the request ID has changed.
1131 base::ObserverList<ResourceMessageDelegate>::Iterator del_it(it->second);
1132 ResourceMessageDelegate* delegate;
1133 while ((delegate = del_it.GetNext()) != NULL) {
1134 delegate->set_request_id(new_request_id);
1136 // Now store the observer list under the new request ID.
1137 delegate_map_[new_request_id] = delegate_map_[old_request_id];
1138 delegate_map_.erase(old_request_id);
1142 AppCacheInterceptor::CompleteCrossSiteTransfer(
1143 loader->request(),
1144 child_id,
1145 request_data.appcache_host_id);
1147 ServiceWorkerRequestHandler* handler =
1148 ServiceWorkerRequestHandler::GetHandler(loader->request());
1149 if (handler) {
1150 handler->CompleteCrossSiteTransfer(
1151 child_id, request_data.service_worker_provider_id);
1154 // We should have a CrossSiteResourceHandler to finish the transfer.
1155 DCHECK(info->cross_site_handler());
1158 void ResourceDispatcherHostImpl::BeginRequest(
1159 int request_id,
1160 const ResourceHostMsg_Request& request_data,
1161 IPC::Message* sync_result, // only valid for sync
1162 int route_id) {
1163 int process_type = filter_->process_type();
1164 int child_id = filter_->child_id();
1166 // PlzNavigate: reject invalid renderer main resource request.
1167 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1168 switches::kEnableBrowserSideNavigation) &&
1169 IsResourceTypeFrame(request_data.resource_type) &&
1170 !request_data.url.SchemeIs(url::kBlobScheme)) {
1171 bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_URL);
1172 return;
1175 // Reject invalid priority.
1176 if (request_data.priority < net::MINIMUM_PRIORITY ||
1177 request_data.priority > net::MAXIMUM_PRIORITY) {
1178 bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_PRIORITY);
1179 return;
1182 // If we crash here, figure out what URL the renderer was requesting.
1183 // http://crbug.com/91398
1184 char url_buf[128];
1185 base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf));
1186 base::debug::Alias(url_buf);
1188 // If the request that's coming in is being transferred from another process,
1189 // we want to reuse and resume the old loader rather than start a new one.
1190 LoaderMap::iterator it = pending_loaders_.find(
1191 GlobalRequestID(request_data.transferred_request_child_id,
1192 request_data.transferred_request_request_id));
1193 if (it != pending_loaders_.end()) {
1194 // If the request is transferring to a new process, we can update our
1195 // state and let it resume with its existing ResourceHandlers.
1196 if (it->second->is_transferring()) {
1197 linked_ptr<ResourceLoader> deferred_loader = it->second;
1198 UpdateRequestForTransfer(child_id, route_id, request_id,
1199 request_data, deferred_loader);
1201 deferred_loader->CompleteTransfer();
1202 } else {
1203 bad_message::ReceivedBadMessage(
1204 filter_, bad_message::RDH_REQUEST_NOT_TRANSFERRING);
1206 return;
1209 ResourceContext* resource_context = NULL;
1210 net::URLRequestContext* request_context = NULL;
1211 filter_->GetContexts(request_data, &resource_context, &request_context);
1212 // http://crbug.com/90971
1213 CHECK(ContainsKey(active_resource_contexts_, resource_context));
1215 // Parse the headers before calling ShouldServiceRequest, so that they are
1216 // available to be validated.
1217 net::HttpRequestHeaders headers;
1218 headers.AddHeadersFromString(request_data.headers);
1220 if (is_shutdown_ ||
1221 !ShouldServiceRequest(process_type, child_id, request_data, headers,
1222 filter_, resource_context)) {
1223 AbortRequestBeforeItStarts(filter_, sync_result, request_id);
1224 return;
1227 // Allow the observer to block/handle the request.
1228 if (delegate_ && !delegate_->ShouldBeginRequest(request_data.method,
1229 request_data.url,
1230 request_data.resource_type,
1231 resource_context)) {
1232 AbortRequestBeforeItStarts(filter_, sync_result, request_id);
1233 return;
1236 // Construct the request.
1237 scoped_ptr<net::URLRequest> new_request = request_context->CreateRequest(
1238 request_data.url, request_data.priority, NULL);
1240 new_request->set_method(request_data.method);
1241 new_request->set_first_party_for_cookies(
1242 request_data.first_party_for_cookies);
1244 // If the request is a MAIN_FRAME request, the first-party URL gets updated on
1245 // redirects.
1246 if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
1247 new_request->set_first_party_url_policy(
1248 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
1251 const Referrer referrer(request_data.referrer, request_data.referrer_policy);
1252 SetReferrerForRequest(new_request.get(), referrer);
1254 new_request->SetExtraRequestHeaders(headers);
1256 storage::BlobStorageContext* blob_context =
1257 GetBlobStorageContext(filter_->blob_storage_context());
1258 // Resolve elements from request_body and prepare upload data.
1259 if (request_data.request_body.get()) {
1260 // |blob_context| could be null when the request is from the plugins because
1261 // ResourceMessageFilters created in PluginProcessHost don't have the blob
1262 // context.
1263 if (blob_context) {
1264 // Attaches the BlobDataHandles to request_body not to free the blobs and
1265 // any attached shareable files until upload completion. These data will
1266 // be used in UploadDataStream and ServiceWorkerURLRequestJob.
1267 AttachRequestBodyBlobDataHandles(
1268 request_data.request_body.get(),
1269 blob_context);
1271 new_request->set_upload(UploadDataStreamBuilder::Build(
1272 request_data.request_body.get(),
1273 blob_context,
1274 filter_->file_system_context(),
1275 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1276 .get()));
1279 bool allow_download = request_data.allow_download &&
1280 IsResourceTypeFrame(request_data.resource_type);
1281 bool do_not_prompt_for_login = request_data.do_not_prompt_for_login;
1282 bool is_sync_load = sync_result != NULL;
1284 // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only
1285 // allow requesting them if requester has ReadRawCookies permission.
1286 ChildProcessSecurityPolicyImpl* policy =
1287 ChildProcessSecurityPolicyImpl::GetInstance();
1288 bool report_raw_headers = request_data.report_raw_headers;
1289 if (report_raw_headers && !policy->CanReadRawCookies(child_id)) {
1290 // TODO: crbug.com/523063 can we call bad_message::ReceivedBadMessage here?
1291 VLOG(1) << "Denied unauthorized request for raw headers";
1292 report_raw_headers = false;
1294 int load_flags =
1295 BuildLoadFlagsForRequest(request_data, child_id, is_sync_load);
1296 if (request_data.resource_type == RESOURCE_TYPE_PREFETCH ||
1297 request_data.resource_type == RESOURCE_TYPE_FAVICON) {
1298 do_not_prompt_for_login = true;
1300 if (request_data.resource_type == RESOURCE_TYPE_IMAGE &&
1301 HTTP_AUTH_RELATION_BLOCKED_CROSS ==
1302 HttpAuthRelationTypeOf(request_data.url,
1303 request_data.first_party_for_cookies)) {
1304 // Prevent third-party image content from prompting for login, as this
1305 // is often a scam to extract credentials for another domain from the user.
1306 // Only block image loads, as the attack applies largely to the "src"
1307 // property of the <img> tag. It is common for web properties to allow
1308 // untrusted values for <img src>; this is considered a fair thing for an
1309 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
1310 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
1311 // would be considered vulnerable in and of itself.
1312 do_not_prompt_for_login = true;
1313 load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
1316 // Sync loads should have maximum priority and should be the only
1317 // requets that have the ignore limits flag set.
1318 if (is_sync_load) {
1319 DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY);
1320 DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1321 } else {
1322 DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1324 new_request->SetLoadFlags(load_flags);
1326 // Make extra info and read footer (contains request ID).
1327 ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
1328 process_type, child_id, route_id,
1329 -1, // frame_tree_node_id
1330 request_data.origin_pid,
1331 request_id,
1332 request_data.render_frame_id,
1333 request_data.is_main_frame,
1334 request_data.parent_is_main_frame,
1335 request_data.parent_render_frame_id,
1336 request_data.resource_type,
1337 request_data.transition_type,
1338 request_data.should_replace_current_entry,
1339 false, // is download
1340 false, // is stream
1341 allow_download,
1342 request_data.has_user_gesture,
1343 request_data.enable_load_timing,
1344 request_data.enable_upload_progress,
1345 do_not_prompt_for_login,
1346 request_data.referrer_policy,
1347 request_data.visiblity_state,
1348 resource_context, filter_->GetWeakPtr(),
1349 report_raw_headers,
1350 !is_sync_load);
1351 // Request takes ownership.
1352 extra_info->AssociateWithRequest(new_request.get());
1354 if (new_request->url().SchemeIs(url::kBlobScheme)) {
1355 // Hang on to a reference to ensure the blob is not released prior
1356 // to the job being started.
1357 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1358 new_request.get(),
1359 filter_->blob_storage_context()->context()->GetBlobDataFromPublicURL(
1360 new_request->url()));
1363 // Initialize the service worker handler for the request. We don't use
1364 // ServiceWorker for synchronous loads to avoid renderer deadlocks.
1365 ServiceWorkerRequestHandler::InitializeHandler(
1366 new_request.get(), filter_->service_worker_context(), blob_context,
1367 child_id, request_data.service_worker_provider_id,
1368 request_data.skip_service_worker || is_sync_load,
1369 request_data.fetch_request_mode, request_data.fetch_credentials_mode,
1370 request_data.fetch_redirect_mode, request_data.resource_type,
1371 request_data.fetch_request_context_type, request_data.fetch_frame_type,
1372 request_data.request_body);
1374 // Have the appcache associate its extra info with the request.
1375 AppCacheInterceptor::SetExtraRequestInfo(
1376 new_request.get(), filter_->appcache_service(), child_id,
1377 request_data.appcache_host_id, request_data.resource_type,
1378 request_data.should_reset_appcache);
1380 scoped_ptr<ResourceHandler> handler(
1381 CreateResourceHandler(
1382 new_request.get(),
1383 request_data, sync_result, route_id, process_type, child_id,
1384 resource_context));
1386 if (handler)
1387 BeginRequestInternal(new_request.Pass(), handler.Pass());
1390 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::CreateResourceHandler(
1391 net::URLRequest* request,
1392 const ResourceHostMsg_Request& request_data,
1393 IPC::Message* sync_result,
1394 int route_id,
1395 int process_type,
1396 int child_id,
1397 ResourceContext* resource_context) {
1398 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1399 tracked_objects::ScopedTracker tracking_profile(
1400 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1401 "456331 ResourceDispatcherHostImpl::CreateResourceHandler"));
1402 // Construct the IPC resource handler.
1403 scoped_ptr<ResourceHandler> handler;
1404 if (sync_result) {
1405 // download_to_file is not supported for synchronous requests.
1406 if (request_data.download_to_file) {
1407 bad_message::ReceivedBadMessage(filter_, bad_message::RDH_BAD_DOWNLOAD);
1408 return scoped_ptr<ResourceHandler>();
1411 handler.reset(new SyncResourceHandler(request, sync_result, this));
1412 } else {
1413 handler.reset(new AsyncResourceHandler(request, this));
1415 // The RedirectToFileResourceHandler depends on being next in the chain.
1416 if (request_data.download_to_file) {
1417 handler.reset(
1418 new RedirectToFileResourceHandler(handler.Pass(), request));
1422 // Prefetches and <a ping> requests outlive their child process.
1423 if (!sync_result && IsDetachableResourceType(request_data.resource_type)) {
1424 handler.reset(new DetachableResourceHandler(
1425 request,
1426 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs),
1427 handler.Pass()));
1430 // PlzNavigate: If using --enable-browser-side-navigation, the
1431 // CrossSiteResourceHandler is not needed. This codepath is not used for the
1432 // actual navigation request, but only the subsequent blob URL load. This does
1433 // not require request transfers.
1434 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1435 switches::kEnableBrowserSideNavigation)) {
1436 // Install a CrossSiteResourceHandler for all main frame requests. This will
1437 // check whether a transfer is required and, if so, pause for the UI thread
1438 // to drive the transfer.
1439 bool is_swappable_navigation =
1440 request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME;
1441 // If out-of-process iframes are possible, then all subframe requests need
1442 // to go through the CrossSiteResourceHandler to enforce the site isolation
1443 // policy.
1444 if (!is_swappable_navigation &&
1445 SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
1446 is_swappable_navigation =
1447 request_data.resource_type == RESOURCE_TYPE_SUB_FRAME;
1449 if (is_swappable_navigation && process_type == PROCESS_TYPE_RENDERER)
1450 handler.reset(new CrossSiteResourceHandler(handler.Pass(), request));
1453 return AddStandardHandlers(request, request_data.resource_type,
1454 resource_context, filter_->appcache_service(),
1455 child_id, route_id, handler.Pass());
1458 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::AddStandardHandlers(
1459 net::URLRequest* request,
1460 ResourceType resource_type,
1461 ResourceContext* resource_context,
1462 AppCacheService* appcache_service,
1463 int child_id,
1464 int route_id,
1465 scoped_ptr<ResourceHandler> handler) {
1466 // PlzNavigate: do not add ResourceThrottles for main resource requests from
1467 // the renderer. Decisions about the navigation should have been done in the
1468 // initial request.
1469 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1470 switches::kEnableBrowserSideNavigation) &&
1471 IsResourceTypeFrame(resource_type) && child_id != -1) {
1472 DCHECK(request->url().SchemeIs(url::kBlobScheme));
1473 return handler.Pass();
1476 PluginService* plugin_service = nullptr;
1477 #if defined(ENABLE_PLUGINS)
1478 plugin_service = PluginService::GetInstance();
1479 #endif
1480 // Insert a buffered event handler before the actual one.
1481 handler.reset(new MimeTypeResourceHandler(handler.Pass(), this,
1482 plugin_service, request));
1484 ScopedVector<ResourceThrottle> throttles;
1486 // Add a NavigationResourceThrottle for navigations.
1487 // PlzNavigate: the throttle is unnecessary as communication with the UI
1488 // thread is handled by the NavigationURLloader.
1489 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1490 switches::kEnableBrowserSideNavigation) &&
1491 IsResourceTypeFrame(resource_type)) {
1492 throttles.push_back(new NavigationResourceThrottle(request));
1495 if (delegate_) {
1496 delegate_->RequestBeginning(request,
1497 resource_context,
1498 appcache_service,
1499 resource_type,
1500 &throttles);
1503 if (request->has_upload()) {
1504 // Block power save while uploading data.
1505 throttles.push_back(new PowerSaveBlockResourceThrottle());
1508 // TODO(ricea): Stop looking this up so much.
1509 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1510 throttles.push_back(scheduler_->ScheduleRequest(child_id, route_id,
1511 info->IsAsync(), request));
1513 handler.reset(
1514 new ThrottlingResourceHandler(handler.Pass(), request, throttles.Pass()));
1516 return handler.Pass();
1519 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id) {
1520 UnregisterDownloadedTempFile(filter_->child_id(), request_id);
1523 void ResourceDispatcherHostImpl::OnDidChangePriority(
1524 int request_id,
1525 net::RequestPriority new_priority,
1526 int intra_priority_value) {
1527 ResourceLoader* loader = GetLoader(filter_->child_id(), request_id);
1528 // The request may go away before processing this message, so |loader| can
1529 // legitimately be null.
1530 if (!loader)
1531 return;
1533 scheduler_->ReprioritizeRequest(loader->request(), new_priority,
1534 intra_priority_value);
1537 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id) {
1538 // TODO(michaeln): maybe throttle DataDownloaded messages
1541 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1542 int child_id, int request_id, const base::FilePath& file_path) {
1543 scoped_refptr<ShareableFileReference> reference =
1544 ShareableFileReference::Get(file_path);
1545 DCHECK(reference.get());
1547 registered_temp_files_[child_id][request_id] = reference;
1548 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1549 child_id, reference->path());
1551 // When the temp file is deleted, revoke permissions that the renderer has
1552 // to that file. This covers an edge case where the file is deleted and then
1553 // the same name is re-used for some other purpose, we don't want the old
1554 // renderer to still have access to it.
1556 // We do this when the file is deleted because the renderer can take a blob
1557 // reference to the temp file that outlives the url loaded that it was
1558 // loaded with to keep the file (and permissions) alive.
1559 reference->AddFinalReleaseCallback(
1560 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy,
1561 child_id));
1564 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1565 int child_id, int request_id) {
1566 DeletableFilesMap& map = registered_temp_files_[child_id];
1567 DeletableFilesMap::iterator found = map.find(request_id);
1568 if (found == map.end())
1569 return;
1571 map.erase(found);
1573 // Note that we don't remove the security bits here. This will be done
1574 // when all file refs are deleted (see RegisterDownloadedTempFile).
1577 bool ResourceDispatcherHostImpl::Send(IPC::Message* message) {
1578 delete message;
1579 return false;
1582 // Note that this cancel is subtly different from the other
1583 // CancelRequest methods in this file, which also tear down the loader.
1584 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id) {
1585 int child_id = filter_->child_id();
1587 // When the old renderer dies, it sends a message to us to cancel its
1588 // requests.
1589 if (IsTransferredNavigation(GlobalRequestID(child_id, request_id)))
1590 return;
1592 ResourceLoader* loader = GetLoader(child_id, request_id);
1593 if (!loader) {
1594 // We probably want to remove this warning eventually, but I wanted to be
1595 // able to notice when this happens during initial development since it
1596 // should be rare and may indicate a bug.
1597 DVLOG(1) << "Canceling a request that wasn't found";
1598 return;
1601 loader->CancelRequest(true);
1604 ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo(
1605 int child_id,
1606 int render_view_route_id,
1607 int render_frame_route_id,
1608 bool download,
1609 ResourceContext* context) {
1610 return new ResourceRequestInfoImpl(
1611 PROCESS_TYPE_RENDERER,
1612 child_id,
1613 render_view_route_id,
1614 -1, // frame_tree_node_id
1616 request_id_,
1617 render_frame_route_id,
1618 false, // is_main_frame
1619 false, // parent_is_main_frame
1620 -1, // parent_render_frame_id
1621 RESOURCE_TYPE_SUB_RESOURCE,
1622 ui::PAGE_TRANSITION_LINK,
1623 false, // should_replace_current_entry
1624 download, // is_download
1625 false, // is_stream
1626 download, // allow_download
1627 false, // has_user_gesture
1628 false, // enable_load_timing
1629 false, // enable_upload_progress
1630 false, // do_not_prompt_for_login
1631 blink::WebReferrerPolicyDefault,
1632 blink::WebPageVisibilityStateVisible,
1633 context,
1634 base::WeakPtr<ResourceMessageFilter>(), // filter
1635 false, // report_raw_headers
1636 true); // is_async
1639 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(int child_id,
1640 int route_id,
1641 bool is_visible,
1642 bool is_audible) {
1643 scheduler_->OnClientCreated(child_id, route_id, is_visible, is_audible);
1646 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1647 int child_id,
1648 int route_id) {
1649 scheduler_->OnClientDeleted(child_id, route_id);
1650 CancelRequestsForRoute(child_id, route_id);
1653 void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id,
1654 int route_id,
1655 bool is_loading) {
1656 scheduler_->OnLoadingStateChanged(child_id, route_id, !is_loading);
1659 void ResourceDispatcherHostImpl::OnRenderViewHostWasHidden(
1660 int child_id,
1661 int route_id) {
1662 scheduler_->OnVisibilityChanged(child_id, route_id, false);
1665 void ResourceDispatcherHostImpl::OnRenderViewHostWasShown(
1666 int child_id,
1667 int route_id) {
1668 scheduler_->OnVisibilityChanged(child_id, route_id, true);
1671 void ResourceDispatcherHostImpl::OnAudioRenderHostStreamStateChanged(
1672 int child_id,
1673 int route_id,
1674 bool is_playing) {
1675 // The ResourceDispatcherHost may have already been shut down.
1676 // See http://crbug.com/455098
1677 if (!scheduler_)
1678 return;
1679 scheduler_->OnAudibilityChanged(child_id, route_id, is_playing);
1682 // This function is only used for saving feature.
1683 void ResourceDispatcherHostImpl::BeginSaveFile(
1684 const GURL& url,
1685 const Referrer& referrer,
1686 int child_id,
1687 int render_view_route_id,
1688 int render_frame_route_id,
1689 ResourceContext* context) {
1690 if (is_shutdown_)
1691 return;
1693 // http://crbug.com/90971
1694 char url_buf[128];
1695 base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
1696 base::debug::Alias(url_buf);
1697 CHECK(ContainsKey(active_resource_contexts_, context));
1699 request_id_--;
1701 const net::URLRequestContext* request_context = context->GetRequestContext();
1702 bool known_proto =
1703 request_context->job_factory()->IsHandledURL(url);
1704 if (!known_proto) {
1705 // Since any URLs which have non-standard scheme have been filtered
1706 // by save manager(see GURL::SchemeIsStandard). This situation
1707 // should not happen.
1708 NOTREACHED();
1709 return;
1712 scoped_ptr<net::URLRequest> request(
1713 request_context->CreateRequest(url, net::DEFAULT_PRIORITY, NULL));
1714 request->set_method("GET");
1715 SetReferrerForRequest(request.get(), referrer);
1717 // So far, for saving page, we need fetch content from cache, in the
1718 // future, maybe we can use a configuration to configure this behavior.
1719 request->SetLoadFlags(net::LOAD_PREFERRING_CACHE);
1721 // Since we're just saving some resources we need, disallow downloading.
1722 ResourceRequestInfoImpl* extra_info =
1723 CreateRequestInfo(child_id, render_view_route_id,
1724 render_frame_route_id, false, context);
1725 extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
1727 scoped_ptr<ResourceHandler> handler(
1728 new SaveFileResourceHandler(request.get(),
1729 child_id,
1730 render_frame_route_id,
1731 url,
1732 save_file_manager_.get()));
1734 BeginRequestInternal(request.Pass(), handler.Pass());
1737 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1738 const GlobalRequestID& id) {
1739 GetLoader(id)->MarkAsTransferring();
1742 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1743 const GlobalRequestID& id) {
1744 // Request should still exist and be in the middle of a transfer.
1745 DCHECK(IsTransferredNavigation(id));
1746 RemovePendingRequest(id.child_id, id.request_id);
1749 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1750 const GlobalRequestID& id) {
1751 ResourceLoader* loader = GetLoader(id);
1752 // The response we were meant to resume could have already been canceled.
1753 if (loader)
1754 loader->CompleteTransfer();
1757 // The object died, so cancel and detach all requests associated with it except
1758 // for downloads and detachable resources, which belong to the browser process
1759 // even if initiated via a renderer.
1760 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id) {
1761 CancelRequestsForRoute(child_id, -1 /* cancel all */);
1762 registered_temp_files_.erase(child_id);
1765 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id,
1766 int route_id) {
1767 // Since pending_requests_ is a map, we first build up a list of all of the
1768 // matching requests to be cancelled, and then we cancel them. Since there
1769 // may be more than one request to cancel, we cannot simply hold onto the map
1770 // iterators found in the first loop.
1772 // Find the global ID of all matching elements.
1773 bool any_requests_transferring = false;
1774 std::vector<GlobalRequestID> matching_requests;
1775 for (LoaderMap::const_iterator i = pending_loaders_.begin();
1776 i != pending_loaders_.end(); ++i) {
1777 if (i->first.child_id != child_id)
1778 continue;
1780 ResourceRequestInfoImpl* info = i->second->GetRequestInfo();
1782 GlobalRequestID id(child_id, i->first.request_id);
1783 DCHECK(id == i->first);
1784 // Don't cancel navigations that are expected to live beyond this process.
1785 if (IsTransferredNavigation(id))
1786 any_requests_transferring = true;
1787 if (info->detachable_handler()) {
1788 info->detachable_handler()->Detach();
1789 } else if (!info->IsDownload() && !info->is_stream() &&
1790 !IsTransferredNavigation(id) &&
1791 (route_id == -1 || route_id == info->GetRouteID())) {
1792 matching_requests.push_back(id);
1796 // Remove matches.
1797 for (size_t i = 0; i < matching_requests.size(); ++i) {
1798 LoaderMap::iterator iter = pending_loaders_.find(matching_requests[i]);
1799 // Although every matching request was in pending_requests_ when we built
1800 // matching_requests, it is normal for a matching request to be not found
1801 // in pending_requests_ after we have removed some matching requests from
1802 // pending_requests_. For example, deleting a net::URLRequest that has
1803 // exclusive (write) access to an HTTP cache entry may unblock another
1804 // net::URLRequest that needs exclusive access to the same cache entry, and
1805 // that net::URLRequest may complete and remove itself from
1806 // pending_requests_. So we need to check that iter is not equal to
1807 // pending_requests_.end().
1808 if (iter != pending_loaders_.end())
1809 RemovePendingLoader(iter);
1812 // Don't clear the blocked loaders or offline policy maps if any of the
1813 // requests in route_id are being transferred to a new process, since those
1814 // maps will be updated with the new route_id after the transfer. Otherwise
1815 // we will lose track of this info when the old route goes away, before the
1816 // new one is created.
1817 if (any_requests_transferring)
1818 return;
1820 // Now deal with blocked requests if any.
1821 if (route_id != -1) {
1822 if (blocked_loaders_map_.find(GlobalRoutingID(child_id, route_id)) !=
1823 blocked_loaders_map_.end()) {
1824 CancelBlockedRequestsForRoute(child_id, route_id);
1826 } else {
1827 // We have to do all render views for the process |child_id|.
1828 // Note that we have to do this in 2 passes as we cannot call
1829 // CancelBlockedRequestsForRoute while iterating over
1830 // blocked_loaders_map_, as it modifies it.
1831 std::set<int> route_ids;
1832 for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
1833 iter != blocked_loaders_map_.end(); ++iter) {
1834 if (iter->first.child_id == child_id)
1835 route_ids.insert(iter->first.route_id);
1837 for (std::set<int>::const_iterator iter = route_ids.begin();
1838 iter != route_ids.end(); ++iter) {
1839 CancelBlockedRequestsForRoute(child_id, *iter);
1844 // Cancels the request and removes it from the list.
1845 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id,
1846 int request_id) {
1847 LoaderMap::iterator i = pending_loaders_.find(
1848 GlobalRequestID(child_id, request_id));
1849 if (i == pending_loaders_.end()) {
1850 NOTREACHED() << "Trying to remove a request that's not here";
1851 return;
1853 RemovePendingLoader(i);
1856 void ResourceDispatcherHostImpl::RemovePendingLoader(
1857 const LoaderMap::iterator& iter) {
1858 ResourceRequestInfoImpl* info = iter->second->GetRequestInfo();
1860 // Remove the memory credit that we added when pushing the request onto
1861 // the pending list.
1862 IncrementOutstandingRequestsMemory(-1, *info);
1864 pending_loaders_.erase(iter);
1867 void ResourceDispatcherHostImpl::CancelRequest(int child_id,
1868 int request_id) {
1869 ResourceLoader* loader = GetLoader(child_id, request_id);
1870 if (!loader) {
1871 // We probably want to remove this warning eventually, but I wanted to be
1872 // able to notice when this happens during initial development since it
1873 // should be rare and may indicate a bug.
1874 DVLOG(1) << "Canceling a request that wasn't found";
1875 return;
1878 RemovePendingRequest(child_id, request_id);
1881 ResourceDispatcherHostImpl::OustandingRequestsStats
1882 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1883 const ResourceRequestInfoImpl& info) {
1884 OutstandingRequestsStatsMap::iterator entry =
1885 outstanding_requests_stats_map_.find(info.GetChildID());
1886 OustandingRequestsStats stats = { 0, 0 };
1887 if (entry != outstanding_requests_stats_map_.end())
1888 stats = entry->second;
1889 return stats;
1892 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1893 const ResourceRequestInfoImpl& info,
1894 const OustandingRequestsStats& stats) {
1895 if (stats.memory_cost == 0 && stats.num_requests == 0)
1896 outstanding_requests_stats_map_.erase(info.GetChildID());
1897 else
1898 outstanding_requests_stats_map_[info.GetChildID()] = stats;
1901 ResourceDispatcherHostImpl::OustandingRequestsStats
1902 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1903 int count,
1904 const ResourceRequestInfoImpl& info) {
1905 DCHECK_EQ(1, abs(count));
1907 // Retrieve the previous value (defaulting to 0 if not found).
1908 OustandingRequestsStats stats = GetOutstandingRequestsStats(info);
1910 // Insert/update the total; delete entries when their count reaches 0.
1911 stats.memory_cost += count * info.memory_cost();
1912 DCHECK_GE(stats.memory_cost, 0);
1913 UpdateOutstandingRequestsStats(info, stats);
1915 return stats;
1918 ResourceDispatcherHostImpl::OustandingRequestsStats
1919 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1920 int count,
1921 ResourceRequestInfoImpl* info) {
1922 DCHECK_EQ(1, abs(count));
1923 num_in_flight_requests_ += count;
1925 // Keep track of whether this request is counting toward the number of
1926 // in-flight requests for this process, in case we need to transfer it to
1927 // another process. This should be a toggle.
1928 DCHECK_NE(info->counted_as_in_flight_request(), count > 0);
1929 info->set_counted_as_in_flight_request(count > 0);
1931 OustandingRequestsStats stats = GetOutstandingRequestsStats(*info);
1932 stats.num_requests += count;
1933 DCHECK_GE(stats.num_requests, 0);
1934 UpdateOutstandingRequestsStats(*info, stats);
1936 return stats;
1939 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1940 net::URLRequest* request) {
1941 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1942 OustandingRequestsStats stats = IncrementOutstandingRequestsCount(1, info);
1944 if (stats.num_requests > max_num_in_flight_requests_per_process_)
1945 return false;
1946 if (num_in_flight_requests_ > max_num_in_flight_requests_)
1947 return false;
1949 return true;
1952 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1953 net::URLRequest* request) {
1954 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1955 IncrementOutstandingRequestsCount(-1, info);
1958 void ResourceDispatcherHostImpl::BeginNavigationRequest(
1959 ResourceContext* resource_context,
1960 int frame_tree_node_id,
1961 const NavigationRequestInfo& info,
1962 NavigationURLLoaderImplCore* loader) {
1963 // PlzNavigate: BeginNavigationRequest currently should only be used for the
1964 // browser-side navigations project.
1965 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1966 switches::kEnableBrowserSideNavigation));
1968 ResourceType resource_type = info.is_main_frame ?
1969 RESOURCE_TYPE_MAIN_FRAME : RESOURCE_TYPE_SUB_FRAME;
1971 if (is_shutdown_ ||
1972 // TODO(davidben): Check ShouldServiceRequest here. This is important; it
1973 // needs to be checked relative to the child that /requested/ the
1974 // navigation. It's where file upload checks, etc., come in.
1975 (delegate_ && !delegate_->ShouldBeginRequest(
1976 info.begin_params.method,
1977 info.common_params.url,
1978 resource_type,
1979 resource_context))) {
1980 loader->NotifyRequestFailed(false, net::ERR_ABORTED);
1981 return;
1984 // Save the URL on the stack to help catch URLRequests which outlive their
1985 // URLRequestContexts. See https://crbug.com/90971
1986 char url_buf[128];
1987 base::strlcpy(
1988 url_buf, info.common_params.url.spec().c_str(), arraysize(url_buf));
1989 base::debug::Alias(url_buf);
1990 CHECK(ContainsKey(active_resource_contexts_, resource_context));
1992 const net::URLRequestContext* request_context =
1993 resource_context->GetRequestContext();
1995 int load_flags = info.begin_params.load_flags;
1996 load_flags |= net::LOAD_VERIFY_EV_CERT;
1997 if (info.is_main_frame)
1998 load_flags |= net::LOAD_MAIN_FRAME;
2000 // TODO(davidben): BuildLoadFlagsForRequest includes logic for
2001 // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here?
2003 // Sync loads should have maximum priority and should be the only
2004 // requests that have the ignore limits flag set.
2005 DCHECK(!(load_flags & net::LOAD_IGNORE_LIMITS));
2007 scoped_ptr<net::URLRequest> new_request;
2008 new_request = request_context->CreateRequest(
2009 info.common_params.url, net::HIGHEST, nullptr);
2011 new_request->set_method(info.begin_params.method);
2012 new_request->set_first_party_for_cookies(
2013 info.first_party_for_cookies);
2014 if (info.is_main_frame) {
2015 new_request->set_first_party_url_policy(
2016 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
2019 SetReferrerForRequest(new_request.get(), info.common_params.referrer);
2021 net::HttpRequestHeaders headers;
2022 headers.AddHeadersFromString(info.begin_params.headers);
2023 new_request->SetExtraRequestHeaders(headers);
2025 new_request->SetLoadFlags(load_flags);
2027 // Resolve elements from request_body and prepare upload data.
2028 if (info.request_body.get()) {
2029 storage::BlobStorageContext* blob_context = GetBlobStorageContext(
2030 GetChromeBlobStorageContextForResourceContext(resource_context));
2031 AttachRequestBodyBlobDataHandles(
2032 info.request_body.get(),
2033 blob_context);
2034 // TODO(davidben): The FileSystemContext is null here. In the case where
2035 // another renderer requested this navigation, this should be the same
2036 // FileSystemContext passed into ShouldServiceRequest.
2037 new_request->set_upload(UploadDataStreamBuilder::Build(
2038 info.request_body.get(),
2039 blob_context,
2040 nullptr, // file_system_context
2041 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
2042 .get()));
2045 request_id_--;
2047 // Make extra info and read footer (contains request ID).
2049 // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so
2050 // that IO thread -> UI thread hops will work.
2051 ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
2052 PROCESS_TYPE_BROWSER,
2053 -1, // child_id
2054 -1, // route_id
2055 info.frame_tree_node_id,
2056 -1, // request_data.origin_pid,
2057 request_id_,
2058 -1, // request_data.render_frame_id,
2059 info.is_main_frame,
2060 info.parent_is_main_frame,
2061 -1, // request_data.parent_render_frame_id,
2062 resource_type,
2063 info.common_params.transition,
2064 // should_replace_current_entry. This was only maintained at layer for
2065 // request transfers and isn't needed for browser-side navigations.
2066 false,
2067 false, // is download
2068 false, // is stream
2069 info.common_params.allow_download,
2070 info.begin_params.has_user_gesture,
2071 true, // enable_load_timing
2072 false, // enable_upload_progress
2073 false, // do_not_prompt_for_login
2074 info.common_params.referrer.policy,
2075 // TODO(davidben): This is only used for prerenders. Replace
2076 // is_showing with something for that. Or maybe it just comes from the
2077 // same mechanism as the cookie one.
2078 blink::WebPageVisibilityStateVisible,
2079 resource_context,
2080 base::WeakPtr<ResourceMessageFilter>(), // filter
2081 false, // request_data.report_raw_headers
2082 true);
2083 // Request takes ownership.
2084 extra_info->AssociateWithRequest(new_request.get());
2086 if (new_request->url().SchemeIs(url::kBlobScheme)) {
2087 // Hang on to a reference to ensure the blob is not released prior
2088 // to the job being started.
2089 ChromeBlobStorageContext* blob_context =
2090 GetChromeBlobStorageContextForResourceContext(resource_context);
2091 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
2092 new_request.get(),
2093 blob_context->context()->GetBlobDataFromPublicURL(new_request->url()));
2096 // TODO(davidben): Attach ServiceWorkerRequestHandler.
2097 // TODO(michaeln): Help out with this and that.
2098 // TODO(davidben): Attach AppCacheInterceptor.
2100 scoped_ptr<ResourceHandler> handler(new NavigationResourceHandler(
2101 new_request.get(), loader));
2103 // TODO(davidben): Pass in the appropriate appcache_service. Also fix the
2104 // dependency on child_id/route_id. Those are used by the ResourceScheduler;
2105 // currently it's a no-op.
2106 handler = AddStandardHandlers(new_request.get(), resource_type,
2107 resource_context,
2108 nullptr, // appcache_service
2109 -1, // child_id
2110 -1, // route_id
2111 handler.Pass());
2113 BeginRequestInternal(new_request.Pass(), handler.Pass());
2116 // static
2117 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
2118 net::URLRequest* request) {
2119 // The following fields should be a minor size contribution (experimentally
2120 // on the order of 100). However since they are variable length, it could
2121 // in theory be a sizeable contribution.
2122 int strings_cost = request->extra_request_headers().ToString().size() +
2123 request->original_url().spec().size() +
2124 request->referrer().size() +
2125 request->method().size();
2127 // Note that this expression will typically be dominated by:
2128 // |kAvgBytesPerOutstandingRequest|.
2129 return kAvgBytesPerOutstandingRequest + strings_cost;
2132 void ResourceDispatcherHostImpl::BeginRequestInternal(
2133 scoped_ptr<net::URLRequest> request,
2134 scoped_ptr<ResourceHandler> handler) {
2135 DCHECK(!request->is_pending());
2136 ResourceRequestInfoImpl* info =
2137 ResourceRequestInfoImpl::ForRequest(request.get());
2139 if ((TimeTicks::Now() - last_user_gesture_time_) <
2140 TimeDelta::FromMilliseconds(kUserGestureWindowMs)) {
2141 request->SetLoadFlags(
2142 request->load_flags() | net::LOAD_MAYBE_USER_GESTURE);
2145 // Add the memory estimate that starting this request will consume.
2146 info->set_memory_cost(CalculateApproximateMemoryCost(request.get()));
2148 // If enqueing/starting this request will exceed our per-process memory
2149 // bound, abort it right away.
2150 OustandingRequestsStats stats = IncrementOutstandingRequestsMemory(1, *info);
2151 if (stats.memory_cost > max_outstanding_requests_cost_per_process_) {
2152 // We call "CancelWithError()" as a way of setting the net::URLRequest's
2153 // status -- it has no effect beyond this, since the request hasn't started.
2154 request->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
2156 bool defer = false;
2157 handler->OnResponseCompleted(request->status(), std::string(), &defer);
2158 if (defer) {
2159 // TODO(darin): The handler is not ready for us to kill the request. Oops!
2160 NOTREACHED();
2163 IncrementOutstandingRequestsMemory(-1, *info);
2165 // A ResourceHandler must not outlive its associated URLRequest.
2166 handler.reset();
2167 return;
2170 linked_ptr<ResourceLoader> loader(
2171 new ResourceLoader(request.Pass(), handler.Pass(), this));
2173 GlobalRoutingID id(info->GetGlobalRoutingID());
2174 BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.find(id);
2175 if (iter != blocked_loaders_map_.end()) {
2176 // The request should be blocked.
2177 iter->second->push_back(loader);
2178 return;
2181 StartLoading(info, loader);
2184 void ResourceDispatcherHostImpl::StartLoading(
2185 ResourceRequestInfoImpl* info,
2186 const linked_ptr<ResourceLoader>& loader) {
2187 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
2188 tracked_objects::ScopedTracker tracking_profile(
2189 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2190 "456331 ResourceDispatcherHostImpl::StartLoading"));
2191 pending_loaders_[info->GetGlobalRequestID()] = loader;
2193 loader->StartRequest();
2196 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl* contents) {
2197 last_user_gesture_time_ = TimeTicks::Now();
2200 net::URLRequest* ResourceDispatcherHostImpl::GetURLRequest(
2201 const GlobalRequestID& id) {
2202 ResourceLoader* loader = GetLoader(id);
2203 if (!loader)
2204 return NULL;
2206 return loader->request();
2209 // static
2210 bool ResourceDispatcherHostImpl::LoadInfoIsMoreInteresting(const LoadInfo& a,
2211 const LoadInfo& b) {
2212 // Set |*_uploading_size| to be the size of the corresponding upload body if
2213 // it's currently being uploaded.
2215 uint64 a_uploading_size = 0;
2216 if (a.load_state.state == net::LOAD_STATE_SENDING_REQUEST)
2217 a_uploading_size = a.upload_size;
2219 uint64 b_uploading_size = 0;
2220 if (b.load_state.state == net::LOAD_STATE_SENDING_REQUEST)
2221 b_uploading_size = b.upload_size;
2223 if (a_uploading_size != b_uploading_size)
2224 return a_uploading_size > b_uploading_size;
2226 return a.load_state.state > b.load_state.state;
2229 // static
2230 void ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread(
2231 scoped_ptr<LoadInfoMap> info_map) {
2232 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2233 // is fixed.
2234 tracked_objects::ScopedTracker tracking_profile(
2235 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2236 "466285 ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread"));
2237 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2238 for (const auto& load_info : *info_map) {
2239 RenderViewHostImpl* view = RenderViewHostImpl::FromID(
2240 load_info.first.child_id, load_info.first.route_id);
2241 // The view could be gone at this point.
2242 if (view) {
2243 view->LoadStateChanged(load_info.second.url, load_info.second.load_state,
2244 load_info.second.upload_position,
2245 load_info.second.upload_size);
2250 scoped_ptr<ResourceDispatcherHostImpl::LoadInfoMap>
2251 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes() {
2252 // Populate this map with load state changes, and then send them on to the UI
2253 // thread where they can be passed along to the respective RVHs.
2254 scoped_ptr<LoadInfoMap> info_map(new LoadInfoMap());
2256 for (const auto& loader : pending_loaders_) {
2257 net::URLRequest* request = loader.second->request();
2258 net::UploadProgress upload_progress = request->GetUploadProgress();
2260 LoadInfo load_info;
2261 load_info.url = request->url();
2262 load_info.load_state = request->GetLoadState();
2263 load_info.upload_size = upload_progress.size();
2264 load_info.upload_position = upload_progress.position();
2266 GlobalRoutingID id(loader.second->GetRequestInfo()->GetGlobalRoutingID());
2267 LoadInfoMap::iterator existing = info_map->find(id);
2269 if (existing == info_map->end() ||
2270 LoadInfoIsMoreInteresting(load_info, existing->second)) {
2271 (*info_map)[id] = load_info;
2274 return info_map.Pass();
2277 void ResourceDispatcherHostImpl::UpdateLoadInfo() {
2278 scoped_ptr<LoadInfoMap> info_map(GetLoadInfoForAllRoutes());
2280 // Stop the timer if there are no more pending requests. Future new requests
2281 // will restart it as necessary.
2282 // Also stop the timer if there are no loading clients, to avoid waking up
2283 // unnecessarily when there is a long running (hanging get) request.
2284 if (info_map->empty() || !scheduler_->HasLoadingClients()) {
2285 update_load_states_timer_->Stop();
2286 return;
2289 BrowserThread::PostTask(
2290 BrowserThread::UI, FROM_HERE,
2291 base::Bind(&ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread,
2292 base::Passed(&info_map)));
2295 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id,
2296 int route_id) {
2297 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2298 GlobalRoutingID key(child_id, route_id);
2299 DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) <<
2300 "BlockRequestsForRoute called multiple time for the same RVH";
2301 blocked_loaders_map_[key] = new BlockedLoadersList();
2304 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id,
2305 int route_id) {
2306 ProcessBlockedRequestsForRoute(child_id, route_id, false);
2309 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id,
2310 int route_id) {
2311 ProcessBlockedRequestsForRoute(child_id, route_id, true);
2314 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
2315 int child_id,
2316 int route_id,
2317 bool cancel_requests) {
2318 BlockedLoadersMap::iterator iter = blocked_loaders_map_.find(
2319 GlobalRoutingID(child_id, route_id));
2320 if (iter == blocked_loaders_map_.end()) {
2321 // It's possible to reach here if the renderer crashed while an interstitial
2322 // page was showing.
2323 return;
2326 BlockedLoadersList* loaders = iter->second;
2328 // Removing the vector from the map unblocks any subsequent requests.
2329 blocked_loaders_map_.erase(iter);
2331 for (BlockedLoadersList::iterator loaders_iter = loaders->begin();
2332 loaders_iter != loaders->end(); ++loaders_iter) {
2333 linked_ptr<ResourceLoader> loader = *loaders_iter;
2334 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
2335 if (cancel_requests) {
2336 IncrementOutstandingRequestsMemory(-1, *info);
2337 } else {
2338 StartLoading(info, loader);
2342 delete loaders;
2345 ResourceDispatcherHostImpl::HttpAuthRelationType
2346 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
2347 const GURL& request_url,
2348 const GURL& first_party) {
2349 if (!first_party.is_valid())
2350 return HTTP_AUTH_RELATION_TOP;
2352 if (net::registry_controlled_domains::SameDomainOrHost(
2353 first_party, request_url,
2354 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES))
2355 return HTTP_AUTH_RELATION_SAME_DOMAIN;
2357 if (allow_cross_origin_auth_prompt())
2358 return HTTP_AUTH_RELATION_ALLOWED_CROSS;
2360 return HTTP_AUTH_RELATION_BLOCKED_CROSS;
2363 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
2364 return allow_cross_origin_auth_prompt_;
2367 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
2368 const GlobalRequestID& id) const {
2369 ResourceLoader* loader = GetLoader(id);
2370 return loader ? loader->is_transferring() : false;
2373 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(
2374 const GlobalRequestID& id) const {
2375 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2377 LoaderMap::const_iterator i = pending_loaders_.find(id);
2378 if (i == pending_loaders_.end())
2379 return NULL;
2381 return i->second.get();
2384 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(int child_id,
2385 int request_id) const {
2386 return GetLoader(GlobalRequestID(child_id, request_id));
2389 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
2390 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
2391 DelegateMap::iterator it = delegate_map_.find(id);
2392 if (it == delegate_map_.end()) {
2393 it = delegate_map_.insert(
2394 std::make_pair(
2396 new base::ObserverList<ResourceMessageDelegate>))
2397 .first;
2399 it->second->AddObserver(delegate);
2402 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
2403 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
2404 DCHECK(ContainsKey(delegate_map_, id));
2405 DelegateMap::iterator it = delegate_map_.find(id);
2406 DCHECK(it->second->HasObserver(delegate));
2407 it->second->RemoveObserver(delegate);
2408 if (!it->second->might_have_observers()) {
2409 delete it->second;
2410 delegate_map_.erase(it);
2414 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
2415 const ResourceHostMsg_Request& request_data,
2416 int child_id,
2417 bool is_sync_load) {
2418 int load_flags = request_data.load_flags;
2420 // Although EV status is irrelevant to sub-frames and sub-resources, we have
2421 // to perform EV certificate verification on all resources because an HTTP
2422 // keep-alive connection created to load a sub-frame or a sub-resource could
2423 // be reused to load a main frame.
2424 load_flags |= net::LOAD_VERIFY_EV_CERT;
2425 if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
2426 load_flags |= net::LOAD_MAIN_FRAME;
2427 } else if (request_data.resource_type == RESOURCE_TYPE_PREFETCH) {
2428 load_flags |= net::LOAD_PREFETCH;
2431 if (is_sync_load)
2432 load_flags |= net::LOAD_IGNORE_LIMITS;
2434 return load_flags;
2437 } // namespace content