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