[refactor] More post-NSS WebCrypto cleanups (utility functions).
[chromium-blink-merge.git] / content / browser / loader / resource_dispatcher_host_impl.cc
bloba5d74a92cd6954b74f778985fefad2b86e18017d
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 // TODO: crbug.com/523063 can we call bad_message::ReceivedBadMessage here?
1281 VLOG(1) << "Denied unauthorized request for raw headers";
1282 report_raw_headers = false;
1284 int load_flags =
1285 BuildLoadFlagsForRequest(request_data, child_id, is_sync_load);
1286 if (request_data.resource_type == RESOURCE_TYPE_PREFETCH ||
1287 request_data.resource_type == RESOURCE_TYPE_FAVICON) {
1288 do_not_prompt_for_login = true;
1290 if (request_data.resource_type == RESOURCE_TYPE_IMAGE &&
1291 HTTP_AUTH_RELATION_BLOCKED_CROSS ==
1292 HttpAuthRelationTypeOf(request_data.url,
1293 request_data.first_party_for_cookies)) {
1294 // Prevent third-party image content from prompting for login, as this
1295 // is often a scam to extract credentials for another domain from the user.
1296 // Only block image loads, as the attack applies largely to the "src"
1297 // property of the <img> tag. It is common for web properties to allow
1298 // untrusted values for <img src>; this is considered a fair thing for an
1299 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
1300 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
1301 // would be considered vulnerable in and of itself.
1302 do_not_prompt_for_login = true;
1303 load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
1306 // Sync loads should have maximum priority and should be the only
1307 // requets that have the ignore limits flag set.
1308 if (is_sync_load) {
1309 DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY);
1310 DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1311 } else {
1312 DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1314 new_request->SetLoadFlags(load_flags);
1316 // Make extra info and read footer (contains request ID).
1317 ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
1318 process_type, child_id, route_id,
1319 -1, // frame_tree_node_id
1320 request_data.origin_pid,
1321 request_id,
1322 request_data.render_frame_id,
1323 request_data.is_main_frame,
1324 request_data.parent_is_main_frame,
1325 request_data.parent_render_frame_id,
1326 request_data.resource_type,
1327 request_data.transition_type,
1328 request_data.should_replace_current_entry,
1329 false, // is download
1330 false, // is stream
1331 allow_download,
1332 request_data.has_user_gesture,
1333 request_data.enable_load_timing,
1334 request_data.enable_upload_progress,
1335 do_not_prompt_for_login,
1336 request_data.referrer_policy,
1337 request_data.visiblity_state,
1338 resource_context, filter_->GetWeakPtr(),
1339 report_raw_headers,
1340 !is_sync_load);
1341 // Request takes ownership.
1342 extra_info->AssociateWithRequest(new_request.get());
1344 if (new_request->url().SchemeIs(url::kBlobScheme)) {
1345 // Hang on to a reference to ensure the blob is not released prior
1346 // to the job being started.
1347 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1348 new_request.get(),
1349 filter_->blob_storage_context()->context()->GetBlobDataFromPublicURL(
1350 new_request->url()));
1353 // Initialize the service worker handler for the request. We don't use
1354 // ServiceWorker for synchronous loads to avoid renderer deadlocks.
1355 ServiceWorkerRequestHandler::InitializeHandler(
1356 new_request.get(), filter_->service_worker_context(), blob_context,
1357 child_id, request_data.service_worker_provider_id,
1358 request_data.skip_service_worker || is_sync_load,
1359 request_data.fetch_request_mode, request_data.fetch_credentials_mode,
1360 request_data.fetch_redirect_mode, request_data.resource_type,
1361 request_data.fetch_request_context_type, request_data.fetch_frame_type,
1362 request_data.request_body);
1364 // Have the appcache associate its extra info with the request.
1365 AppCacheInterceptor::SetExtraRequestInfo(
1366 new_request.get(), filter_->appcache_service(), child_id,
1367 request_data.appcache_host_id, request_data.resource_type,
1368 request_data.should_reset_appcache);
1370 scoped_ptr<ResourceHandler> handler(
1371 CreateResourceHandler(
1372 new_request.get(),
1373 request_data, sync_result, route_id, process_type, child_id,
1374 resource_context));
1376 if (handler)
1377 BeginRequestInternal(new_request.Pass(), handler.Pass());
1380 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::CreateResourceHandler(
1381 net::URLRequest* request,
1382 const ResourceHostMsg_Request& request_data,
1383 IPC::Message* sync_result,
1384 int route_id,
1385 int process_type,
1386 int child_id,
1387 ResourceContext* resource_context) {
1388 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1389 tracked_objects::ScopedTracker tracking_profile(
1390 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1391 "456331 ResourceDispatcherHostImpl::CreateResourceHandler"));
1392 // Construct the IPC resource handler.
1393 scoped_ptr<ResourceHandler> handler;
1394 if (sync_result) {
1395 // download_to_file is not supported for synchronous requests.
1396 if (request_data.download_to_file) {
1397 bad_message::ReceivedBadMessage(filter_, bad_message::RDH_BAD_DOWNLOAD);
1398 return scoped_ptr<ResourceHandler>();
1401 handler.reset(new SyncResourceHandler(request, sync_result, this));
1402 } else {
1403 handler.reset(new AsyncResourceHandler(request, this));
1405 // The RedirectToFileResourceHandler depends on being next in the chain.
1406 if (request_data.download_to_file) {
1407 handler.reset(
1408 new RedirectToFileResourceHandler(handler.Pass(), request));
1412 // Prefetches and <a ping> requests outlive their child process.
1413 if (!sync_result && IsDetachableResourceType(request_data.resource_type)) {
1414 handler.reset(new DetachableResourceHandler(
1415 request,
1416 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs),
1417 handler.Pass()));
1420 // PlzNavigate: If using --enable-browser-side-navigation, the
1421 // CrossSiteResourceHandler is not needed. This codepath is not used for the
1422 // actual navigation request, but only the subsequent blob URL load. This does
1423 // not require request transfers.
1424 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1425 switches::kEnableBrowserSideNavigation)) {
1426 // Install a CrossSiteResourceHandler for all main frame requests. This will
1427 // check whether a transfer is required and, if so, pause for the UI thread
1428 // to drive the transfer.
1429 bool is_swappable_navigation =
1430 request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME;
1431 // If out-of-process iframes are possible, then all subframe requests need
1432 // to go through the CrossSiteResourceHandler to enforce the site isolation
1433 // policy.
1434 if (!is_swappable_navigation &&
1435 SiteIsolationPolicy::AreCrossProcessFramesPossible()) {
1436 is_swappable_navigation =
1437 request_data.resource_type == RESOURCE_TYPE_SUB_FRAME;
1439 if (is_swappable_navigation && process_type == PROCESS_TYPE_RENDERER)
1440 handler.reset(new CrossSiteResourceHandler(handler.Pass(), request));
1443 return AddStandardHandlers(request, request_data.resource_type,
1444 resource_context, filter_->appcache_service(),
1445 child_id, route_id, handler.Pass());
1448 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::AddStandardHandlers(
1449 net::URLRequest* request,
1450 ResourceType resource_type,
1451 ResourceContext* resource_context,
1452 AppCacheService* appcache_service,
1453 int child_id,
1454 int route_id,
1455 scoped_ptr<ResourceHandler> handler) {
1457 PluginService* plugin_service = nullptr;
1458 #if defined(ENABLE_PLUGINS)
1459 plugin_service = PluginService::GetInstance();
1460 #endif
1461 // Insert a buffered event handler before the actual one.
1462 handler.reset(new MimeTypeResourceHandler(handler.Pass(), this,
1463 plugin_service, request));
1465 ScopedVector<ResourceThrottle> throttles;
1466 if (delegate_) {
1467 delegate_->RequestBeginning(request,
1468 resource_context,
1469 appcache_service,
1470 resource_type,
1471 &throttles);
1474 if (request->has_upload()) {
1475 // Block power save while uploading data.
1476 throttles.push_back(new PowerSaveBlockResourceThrottle());
1479 // TODO(ricea): Stop looking this up so much.
1480 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1481 throttles.push_back(scheduler_->ScheduleRequest(child_id, route_id,
1482 info->IsAsync(), request));
1484 handler.reset(
1485 new ThrottlingResourceHandler(handler.Pass(), request, throttles.Pass()));
1487 return handler.Pass();
1490 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id) {
1491 UnregisterDownloadedTempFile(filter_->child_id(), request_id);
1494 void ResourceDispatcherHostImpl::OnDidChangePriority(
1495 int request_id,
1496 net::RequestPriority new_priority,
1497 int intra_priority_value) {
1498 ResourceLoader* loader = GetLoader(filter_->child_id(), request_id);
1499 // The request may go away before processing this message, so |loader| can
1500 // legitimately be null.
1501 if (!loader)
1502 return;
1504 scheduler_->ReprioritizeRequest(loader->request(), new_priority,
1505 intra_priority_value);
1508 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id) {
1509 // TODO(michaeln): maybe throttle DataDownloaded messages
1512 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1513 int child_id, int request_id, const base::FilePath& file_path) {
1514 scoped_refptr<ShareableFileReference> reference =
1515 ShareableFileReference::Get(file_path);
1516 DCHECK(reference.get());
1518 registered_temp_files_[child_id][request_id] = reference;
1519 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1520 child_id, reference->path());
1522 // When the temp file is deleted, revoke permissions that the renderer has
1523 // to that file. This covers an edge case where the file is deleted and then
1524 // the same name is re-used for some other purpose, we don't want the old
1525 // renderer to still have access to it.
1527 // We do this when the file is deleted because the renderer can take a blob
1528 // reference to the temp file that outlives the url loaded that it was
1529 // loaded with to keep the file (and permissions) alive.
1530 reference->AddFinalReleaseCallback(
1531 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy,
1532 child_id));
1535 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1536 int child_id, int request_id) {
1537 DeletableFilesMap& map = registered_temp_files_[child_id];
1538 DeletableFilesMap::iterator found = map.find(request_id);
1539 if (found == map.end())
1540 return;
1542 map.erase(found);
1544 // Note that we don't remove the security bits here. This will be done
1545 // when all file refs are deleted (see RegisterDownloadedTempFile).
1548 bool ResourceDispatcherHostImpl::Send(IPC::Message* message) {
1549 delete message;
1550 return false;
1553 // Note that this cancel is subtly different from the other
1554 // CancelRequest methods in this file, which also tear down the loader.
1555 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id) {
1556 int child_id = filter_->child_id();
1558 // When the old renderer dies, it sends a message to us to cancel its
1559 // requests.
1560 if (IsTransferredNavigation(GlobalRequestID(child_id, request_id)))
1561 return;
1563 ResourceLoader* loader = GetLoader(child_id, request_id);
1564 if (!loader) {
1565 // We probably want to remove this warning eventually, but I wanted to be
1566 // able to notice when this happens during initial development since it
1567 // should be rare and may indicate a bug.
1568 DVLOG(1) << "Canceling a request that wasn't found";
1569 return;
1572 loader->CancelRequest(true);
1575 ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo(
1576 int child_id,
1577 int render_view_route_id,
1578 int render_frame_route_id,
1579 bool download,
1580 ResourceContext* context) {
1581 return new ResourceRequestInfoImpl(
1582 PROCESS_TYPE_RENDERER,
1583 child_id,
1584 render_view_route_id,
1585 -1, // frame_tree_node_id
1587 request_id_,
1588 render_frame_route_id,
1589 false, // is_main_frame
1590 false, // parent_is_main_frame
1591 -1, // parent_render_frame_id
1592 RESOURCE_TYPE_SUB_RESOURCE,
1593 ui::PAGE_TRANSITION_LINK,
1594 false, // should_replace_current_entry
1595 download, // is_download
1596 false, // is_stream
1597 download, // allow_download
1598 false, // has_user_gesture
1599 false, // enable_load_timing
1600 false, // enable_upload_progress
1601 false, // do_not_prompt_for_login
1602 blink::WebReferrerPolicyDefault,
1603 blink::WebPageVisibilityStateVisible,
1604 context,
1605 base::WeakPtr<ResourceMessageFilter>(), // filter
1606 false, // report_raw_headers
1607 true); // is_async
1610 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(int child_id,
1611 int route_id,
1612 bool is_visible,
1613 bool is_audible) {
1614 scheduler_->OnClientCreated(child_id, route_id, is_visible, is_audible);
1617 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1618 int child_id,
1619 int route_id) {
1620 scheduler_->OnClientDeleted(child_id, route_id);
1621 CancelRequestsForRoute(child_id, route_id);
1624 void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id,
1625 int route_id,
1626 bool is_loading) {
1627 scheduler_->OnLoadingStateChanged(child_id, route_id, !is_loading);
1630 void ResourceDispatcherHostImpl::OnRenderViewHostWasHidden(
1631 int child_id,
1632 int route_id) {
1633 scheduler_->OnVisibilityChanged(child_id, route_id, false);
1636 void ResourceDispatcherHostImpl::OnRenderViewHostWasShown(
1637 int child_id,
1638 int route_id) {
1639 scheduler_->OnVisibilityChanged(child_id, route_id, true);
1642 void ResourceDispatcherHostImpl::OnAudioRenderHostStreamStateChanged(
1643 int child_id,
1644 int route_id,
1645 bool is_playing) {
1646 // The ResourceDispatcherHost may have already been shut down.
1647 // See http://crbug.com/455098
1648 if (!scheduler_)
1649 return;
1650 scheduler_->OnAudibilityChanged(child_id, route_id, is_playing);
1653 // This function is only used for saving feature.
1654 void ResourceDispatcherHostImpl::BeginSaveFile(
1655 const GURL& url,
1656 const Referrer& referrer,
1657 int child_id,
1658 int render_view_route_id,
1659 int render_frame_route_id,
1660 ResourceContext* context) {
1661 if (is_shutdown_)
1662 return;
1664 // http://crbug.com/90971
1665 char url_buf[128];
1666 base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
1667 base::debug::Alias(url_buf);
1668 CHECK(ContainsKey(active_resource_contexts_, context));
1670 request_id_--;
1672 const net::URLRequestContext* request_context = context->GetRequestContext();
1673 bool known_proto =
1674 request_context->job_factory()->IsHandledURL(url);
1675 if (!known_proto) {
1676 // Since any URLs which have non-standard scheme have been filtered
1677 // by save manager(see GURL::SchemeIsStandard). This situation
1678 // should not happen.
1679 NOTREACHED();
1680 return;
1683 scoped_ptr<net::URLRequest> request(
1684 request_context->CreateRequest(url, net::DEFAULT_PRIORITY, NULL));
1685 request->set_method("GET");
1686 SetReferrerForRequest(request.get(), referrer);
1688 // So far, for saving page, we need fetch content from cache, in the
1689 // future, maybe we can use a configuration to configure this behavior.
1690 request->SetLoadFlags(net::LOAD_PREFERRING_CACHE);
1692 // Since we're just saving some resources we need, disallow downloading.
1693 ResourceRequestInfoImpl* extra_info =
1694 CreateRequestInfo(child_id, render_view_route_id,
1695 render_frame_route_id, false, context);
1696 extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
1698 scoped_ptr<ResourceHandler> handler(
1699 new SaveFileResourceHandler(request.get(),
1700 child_id,
1701 render_frame_route_id,
1702 url,
1703 save_file_manager_.get()));
1705 BeginRequestInternal(request.Pass(), handler.Pass());
1708 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1709 const GlobalRequestID& id) {
1710 GetLoader(id)->MarkAsTransferring();
1713 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1714 const GlobalRequestID& id) {
1715 // Request should still exist and be in the middle of a transfer.
1716 DCHECK(IsTransferredNavigation(id));
1717 RemovePendingRequest(id.child_id, id.request_id);
1720 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1721 const GlobalRequestID& id) {
1722 ResourceLoader* loader = GetLoader(id);
1723 // The response we were meant to resume could have already been canceled.
1724 if (loader)
1725 loader->CompleteTransfer();
1728 // The object died, so cancel and detach all requests associated with it except
1729 // for downloads and detachable resources, which belong to the browser process
1730 // even if initiated via a renderer.
1731 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id) {
1732 CancelRequestsForRoute(child_id, -1 /* cancel all */);
1733 registered_temp_files_.erase(child_id);
1736 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id,
1737 int route_id) {
1738 // Since pending_requests_ is a map, we first build up a list of all of the
1739 // matching requests to be cancelled, and then we cancel them. Since there
1740 // may be more than one request to cancel, we cannot simply hold onto the map
1741 // iterators found in the first loop.
1743 // Find the global ID of all matching elements.
1744 bool any_requests_transferring = false;
1745 std::vector<GlobalRequestID> matching_requests;
1746 for (LoaderMap::const_iterator i = pending_loaders_.begin();
1747 i != pending_loaders_.end(); ++i) {
1748 if (i->first.child_id != child_id)
1749 continue;
1751 ResourceRequestInfoImpl* info = i->second->GetRequestInfo();
1753 GlobalRequestID id(child_id, i->first.request_id);
1754 DCHECK(id == i->first);
1755 // Don't cancel navigations that are expected to live beyond this process.
1756 if (IsTransferredNavigation(id))
1757 any_requests_transferring = true;
1758 if (info->detachable_handler()) {
1759 info->detachable_handler()->Detach();
1760 } else if (!info->IsDownload() && !info->is_stream() &&
1761 !IsTransferredNavigation(id) &&
1762 (route_id == -1 || route_id == info->GetRouteID())) {
1763 matching_requests.push_back(id);
1767 // Remove matches.
1768 for (size_t i = 0; i < matching_requests.size(); ++i) {
1769 LoaderMap::iterator iter = pending_loaders_.find(matching_requests[i]);
1770 // Although every matching request was in pending_requests_ when we built
1771 // matching_requests, it is normal for a matching request to be not found
1772 // in pending_requests_ after we have removed some matching requests from
1773 // pending_requests_. For example, deleting a net::URLRequest that has
1774 // exclusive (write) access to an HTTP cache entry may unblock another
1775 // net::URLRequest that needs exclusive access to the same cache entry, and
1776 // that net::URLRequest may complete and remove itself from
1777 // pending_requests_. So we need to check that iter is not equal to
1778 // pending_requests_.end().
1779 if (iter != pending_loaders_.end())
1780 RemovePendingLoader(iter);
1783 // Don't clear the blocked loaders or offline policy maps if any of the
1784 // requests in route_id are being transferred to a new process, since those
1785 // maps will be updated with the new route_id after the transfer. Otherwise
1786 // we will lose track of this info when the old route goes away, before the
1787 // new one is created.
1788 if (any_requests_transferring)
1789 return;
1791 // Now deal with blocked requests if any.
1792 if (route_id != -1) {
1793 if (blocked_loaders_map_.find(GlobalRoutingID(child_id, route_id)) !=
1794 blocked_loaders_map_.end()) {
1795 CancelBlockedRequestsForRoute(child_id, route_id);
1797 } else {
1798 // We have to do all render views for the process |child_id|.
1799 // Note that we have to do this in 2 passes as we cannot call
1800 // CancelBlockedRequestsForRoute while iterating over
1801 // blocked_loaders_map_, as it modifies it.
1802 std::set<int> route_ids;
1803 for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
1804 iter != blocked_loaders_map_.end(); ++iter) {
1805 if (iter->first.child_id == child_id)
1806 route_ids.insert(iter->first.route_id);
1808 for (std::set<int>::const_iterator iter = route_ids.begin();
1809 iter != route_ids.end(); ++iter) {
1810 CancelBlockedRequestsForRoute(child_id, *iter);
1815 // Cancels the request and removes it from the list.
1816 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id,
1817 int request_id) {
1818 LoaderMap::iterator i = pending_loaders_.find(
1819 GlobalRequestID(child_id, request_id));
1820 if (i == pending_loaders_.end()) {
1821 NOTREACHED() << "Trying to remove a request that's not here";
1822 return;
1824 RemovePendingLoader(i);
1827 void ResourceDispatcherHostImpl::RemovePendingLoader(
1828 const LoaderMap::iterator& iter) {
1829 ResourceRequestInfoImpl* info = iter->second->GetRequestInfo();
1831 // Remove the memory credit that we added when pushing the request onto
1832 // the pending list.
1833 IncrementOutstandingRequestsMemory(-1, *info);
1835 pending_loaders_.erase(iter);
1838 void ResourceDispatcherHostImpl::CancelRequest(int child_id,
1839 int request_id) {
1840 ResourceLoader* loader = GetLoader(child_id, request_id);
1841 if (!loader) {
1842 // We probably want to remove this warning eventually, but I wanted to be
1843 // able to notice when this happens during initial development since it
1844 // should be rare and may indicate a bug.
1845 DVLOG(1) << "Canceling a request that wasn't found";
1846 return;
1849 RemovePendingRequest(child_id, request_id);
1852 ResourceDispatcherHostImpl::OustandingRequestsStats
1853 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1854 const ResourceRequestInfoImpl& info) {
1855 OutstandingRequestsStatsMap::iterator entry =
1856 outstanding_requests_stats_map_.find(info.GetChildID());
1857 OustandingRequestsStats stats = { 0, 0 };
1858 if (entry != outstanding_requests_stats_map_.end())
1859 stats = entry->second;
1860 return stats;
1863 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1864 const ResourceRequestInfoImpl& info,
1865 const OustandingRequestsStats& stats) {
1866 if (stats.memory_cost == 0 && stats.num_requests == 0)
1867 outstanding_requests_stats_map_.erase(info.GetChildID());
1868 else
1869 outstanding_requests_stats_map_[info.GetChildID()] = stats;
1872 ResourceDispatcherHostImpl::OustandingRequestsStats
1873 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1874 int count,
1875 const ResourceRequestInfoImpl& info) {
1876 DCHECK_EQ(1, abs(count));
1878 // Retrieve the previous value (defaulting to 0 if not found).
1879 OustandingRequestsStats stats = GetOutstandingRequestsStats(info);
1881 // Insert/update the total; delete entries when their count reaches 0.
1882 stats.memory_cost += count * info.memory_cost();
1883 DCHECK_GE(stats.memory_cost, 0);
1884 UpdateOutstandingRequestsStats(info, stats);
1886 return stats;
1889 ResourceDispatcherHostImpl::OustandingRequestsStats
1890 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1891 int count,
1892 ResourceRequestInfoImpl* info) {
1893 DCHECK_EQ(1, abs(count));
1894 num_in_flight_requests_ += count;
1896 // Keep track of whether this request is counting toward the number of
1897 // in-flight requests for this process, in case we need to transfer it to
1898 // another process. This should be a toggle.
1899 DCHECK_NE(info->counted_as_in_flight_request(), count > 0);
1900 info->set_counted_as_in_flight_request(count > 0);
1902 OustandingRequestsStats stats = GetOutstandingRequestsStats(*info);
1903 stats.num_requests += count;
1904 DCHECK_GE(stats.num_requests, 0);
1905 UpdateOutstandingRequestsStats(*info, stats);
1907 return stats;
1910 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1911 net::URLRequest* request) {
1912 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1913 OustandingRequestsStats stats = IncrementOutstandingRequestsCount(1, info);
1915 if (stats.num_requests > max_num_in_flight_requests_per_process_)
1916 return false;
1917 if (num_in_flight_requests_ > max_num_in_flight_requests_)
1918 return false;
1920 return true;
1923 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1924 net::URLRequest* request) {
1925 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
1926 IncrementOutstandingRequestsCount(-1, info);
1929 void ResourceDispatcherHostImpl::BeginNavigationRequest(
1930 ResourceContext* resource_context,
1931 int frame_tree_node_id,
1932 const NavigationRequestInfo& info,
1933 NavigationURLLoaderImplCore* loader) {
1934 // PlzNavigate: BeginNavigationRequest currently should only be used for the
1935 // browser-side navigations project.
1936 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1937 switches::kEnableBrowserSideNavigation));
1939 ResourceType resource_type = info.is_main_frame ?
1940 RESOURCE_TYPE_MAIN_FRAME : RESOURCE_TYPE_SUB_FRAME;
1942 if (is_shutdown_ ||
1943 // TODO(davidben): Check ShouldServiceRequest here. This is important; it
1944 // needs to be checked relative to the child that /requested/ the
1945 // navigation. It's where file upload checks, etc., come in.
1946 (delegate_ && !delegate_->ShouldBeginRequest(
1947 info.begin_params.method,
1948 info.common_params.url,
1949 resource_type,
1950 resource_context))) {
1951 loader->NotifyRequestFailed(false, net::ERR_ABORTED);
1952 return;
1955 // Save the URL on the stack to help catch URLRequests which outlive their
1956 // URLRequestContexts. See https://crbug.com/90971
1957 char url_buf[128];
1958 base::strlcpy(
1959 url_buf, info.common_params.url.spec().c_str(), arraysize(url_buf));
1960 base::debug::Alias(url_buf);
1961 CHECK(ContainsKey(active_resource_contexts_, resource_context));
1963 const net::URLRequestContext* request_context =
1964 resource_context->GetRequestContext();
1966 int load_flags = info.begin_params.load_flags;
1967 load_flags |= net::LOAD_VERIFY_EV_CERT;
1968 if (info.is_main_frame)
1969 load_flags |= net::LOAD_MAIN_FRAME;
1971 // TODO(davidben): BuildLoadFlagsForRequest includes logic for
1972 // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here?
1974 // Sync loads should have maximum priority and should be the only
1975 // requests that have the ignore limits flag set.
1976 DCHECK(!(load_flags & net::LOAD_IGNORE_LIMITS));
1978 scoped_ptr<net::URLRequest> new_request;
1979 new_request = request_context->CreateRequest(
1980 info.common_params.url, net::HIGHEST, nullptr);
1982 new_request->set_method(info.begin_params.method);
1983 new_request->set_first_party_for_cookies(
1984 info.first_party_for_cookies);
1985 if (info.is_main_frame) {
1986 new_request->set_first_party_url_policy(
1987 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
1990 SetReferrerForRequest(new_request.get(), info.common_params.referrer);
1992 net::HttpRequestHeaders headers;
1993 headers.AddHeadersFromString(info.begin_params.headers);
1994 new_request->SetExtraRequestHeaders(headers);
1996 new_request->SetLoadFlags(load_flags);
1998 // Resolve elements from request_body and prepare upload data.
1999 if (info.request_body.get()) {
2000 storage::BlobStorageContext* blob_context = GetBlobStorageContext(
2001 GetChromeBlobStorageContextForResourceContext(resource_context));
2002 AttachRequestBodyBlobDataHandles(
2003 info.request_body.get(),
2004 blob_context);
2005 // TODO(davidben): The FileSystemContext is null here. In the case where
2006 // another renderer requested this navigation, this should be the same
2007 // FileSystemContext passed into ShouldServiceRequest.
2008 new_request->set_upload(UploadDataStreamBuilder::Build(
2009 info.request_body.get(),
2010 blob_context,
2011 nullptr, // file_system_context
2012 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
2013 .get()));
2016 request_id_--;
2018 // Make extra info and read footer (contains request ID).
2020 // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so
2021 // that IO thread -> UI thread hops will work.
2022 ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
2023 PROCESS_TYPE_BROWSER,
2024 -1, // child_id
2025 -1, // route_id
2026 info.frame_tree_node_id,
2027 -1, // request_data.origin_pid,
2028 request_id_,
2029 -1, // request_data.render_frame_id,
2030 info.is_main_frame,
2031 info.parent_is_main_frame,
2032 -1, // request_data.parent_render_frame_id,
2033 resource_type,
2034 info.common_params.transition,
2035 // should_replace_current_entry. This was only maintained at layer for
2036 // request transfers and isn't needed for browser-side navigations.
2037 false,
2038 false, // is download
2039 false, // is stream
2040 info.common_params.allow_download,
2041 info.begin_params.has_user_gesture,
2042 true, // enable_load_timing
2043 false, // enable_upload_progress
2044 false, // do_not_prompt_for_login
2045 info.common_params.referrer.policy,
2046 // TODO(davidben): This is only used for prerenders. Replace
2047 // is_showing with something for that. Or maybe it just comes from the
2048 // same mechanism as the cookie one.
2049 blink::WebPageVisibilityStateVisible,
2050 resource_context,
2051 base::WeakPtr<ResourceMessageFilter>(), // filter
2052 false, // request_data.report_raw_headers
2053 true);
2054 // Request takes ownership.
2055 extra_info->AssociateWithRequest(new_request.get());
2057 if (new_request->url().SchemeIs(url::kBlobScheme)) {
2058 // Hang on to a reference to ensure the blob is not released prior
2059 // to the job being started.
2060 ChromeBlobStorageContext* blob_context =
2061 GetChromeBlobStorageContextForResourceContext(resource_context);
2062 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
2063 new_request.get(),
2064 blob_context->context()->GetBlobDataFromPublicURL(new_request->url()));
2067 // TODO(davidben): Attach ServiceWorkerRequestHandler.
2068 // TODO(michaeln): Help out with this and that.
2069 // TODO(davidben): Attach AppCacheInterceptor.
2071 scoped_ptr<ResourceHandler> handler(new NavigationResourceHandler(
2072 new_request.get(), loader));
2074 // TODO(davidben): Pass in the appropriate appcache_service. Also fix the
2075 // dependency on child_id/route_id. Those are used by the ResourceScheduler;
2076 // currently it's a no-op.
2077 handler = AddStandardHandlers(new_request.get(), resource_type,
2078 resource_context,
2079 nullptr, // appcache_service
2080 -1, // child_id
2081 -1, // route_id
2082 handler.Pass());
2084 BeginRequestInternal(new_request.Pass(), handler.Pass());
2087 // static
2088 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
2089 net::URLRequest* request) {
2090 // The following fields should be a minor size contribution (experimentally
2091 // on the order of 100). However since they are variable length, it could
2092 // in theory be a sizeable contribution.
2093 int strings_cost = request->extra_request_headers().ToString().size() +
2094 request->original_url().spec().size() +
2095 request->referrer().size() +
2096 request->method().size();
2098 // Note that this expression will typically be dominated by:
2099 // |kAvgBytesPerOutstandingRequest|.
2100 return kAvgBytesPerOutstandingRequest + strings_cost;
2103 void ResourceDispatcherHostImpl::BeginRequestInternal(
2104 scoped_ptr<net::URLRequest> request,
2105 scoped_ptr<ResourceHandler> handler) {
2106 DCHECK(!request->is_pending());
2107 ResourceRequestInfoImpl* info =
2108 ResourceRequestInfoImpl::ForRequest(request.get());
2110 if ((TimeTicks::Now() - last_user_gesture_time_) <
2111 TimeDelta::FromMilliseconds(kUserGestureWindowMs)) {
2112 request->SetLoadFlags(
2113 request->load_flags() | net::LOAD_MAYBE_USER_GESTURE);
2116 // Add the memory estimate that starting this request will consume.
2117 info->set_memory_cost(CalculateApproximateMemoryCost(request.get()));
2119 // If enqueing/starting this request will exceed our per-process memory
2120 // bound, abort it right away.
2121 OustandingRequestsStats stats = IncrementOutstandingRequestsMemory(1, *info);
2122 if (stats.memory_cost > max_outstanding_requests_cost_per_process_) {
2123 // We call "CancelWithError()" as a way of setting the net::URLRequest's
2124 // status -- it has no effect beyond this, since the request hasn't started.
2125 request->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
2127 bool defer = false;
2128 handler->OnResponseCompleted(request->status(), std::string(), &defer);
2129 if (defer) {
2130 // TODO(darin): The handler is not ready for us to kill the request. Oops!
2131 NOTREACHED();
2134 IncrementOutstandingRequestsMemory(-1, *info);
2136 // A ResourceHandler must not outlive its associated URLRequest.
2137 handler.reset();
2138 return;
2141 linked_ptr<ResourceLoader> loader(
2142 new ResourceLoader(request.Pass(), handler.Pass(), this));
2144 GlobalRoutingID id(info->GetGlobalRoutingID());
2145 BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.find(id);
2146 if (iter != blocked_loaders_map_.end()) {
2147 // The request should be blocked.
2148 iter->second->push_back(loader);
2149 return;
2152 StartLoading(info, loader);
2155 void ResourceDispatcherHostImpl::StartLoading(
2156 ResourceRequestInfoImpl* info,
2157 const linked_ptr<ResourceLoader>& loader) {
2158 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
2159 tracked_objects::ScopedTracker tracking_profile(
2160 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2161 "456331 ResourceDispatcherHostImpl::StartLoading"));
2162 pending_loaders_[info->GetGlobalRequestID()] = loader;
2164 loader->StartRequest();
2167 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl* contents) {
2168 last_user_gesture_time_ = TimeTicks::Now();
2171 net::URLRequest* ResourceDispatcherHostImpl::GetURLRequest(
2172 const GlobalRequestID& id) {
2173 ResourceLoader* loader = GetLoader(id);
2174 if (!loader)
2175 return NULL;
2177 return loader->request();
2180 // static
2181 bool ResourceDispatcherHostImpl::LoadInfoIsMoreInteresting(const LoadInfo& a,
2182 const LoadInfo& b) {
2183 // Set |*_uploading_size| to be the size of the corresponding upload body if
2184 // it's currently being uploaded.
2186 uint64 a_uploading_size = 0;
2187 if (a.load_state.state == net::LOAD_STATE_SENDING_REQUEST)
2188 a_uploading_size = a.upload_size;
2190 uint64 b_uploading_size = 0;
2191 if (b.load_state.state == net::LOAD_STATE_SENDING_REQUEST)
2192 b_uploading_size = b.upload_size;
2194 if (a_uploading_size != b_uploading_size)
2195 return a_uploading_size > b_uploading_size;
2197 return a.load_state.state > b.load_state.state;
2200 // static
2201 void ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread(
2202 scoped_ptr<LoadInfoMap> info_map) {
2203 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2204 // is fixed.
2205 tracked_objects::ScopedTracker tracking_profile(
2206 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2207 "466285 ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread"));
2208 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2209 for (const auto& load_info : *info_map) {
2210 RenderViewHostImpl* view = RenderViewHostImpl::FromID(
2211 load_info.first.child_id, load_info.first.route_id);
2212 // The view could be gone at this point.
2213 if (view) {
2214 view->LoadStateChanged(load_info.second.url, load_info.second.load_state,
2215 load_info.second.upload_position,
2216 load_info.second.upload_size);
2221 scoped_ptr<ResourceDispatcherHostImpl::LoadInfoMap>
2222 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes() {
2223 // Populate this map with load state changes, and then send them on to the UI
2224 // thread where they can be passed along to the respective RVHs.
2225 scoped_ptr<LoadInfoMap> info_map(new LoadInfoMap());
2227 for (const auto& loader : pending_loaders_) {
2228 net::URLRequest* request = loader.second->request();
2229 net::UploadProgress upload_progress = request->GetUploadProgress();
2231 LoadInfo load_info;
2232 load_info.url = request->url();
2233 load_info.load_state = request->GetLoadState();
2234 load_info.upload_size = upload_progress.size();
2235 load_info.upload_position = upload_progress.position();
2237 GlobalRoutingID id(loader.second->GetRequestInfo()->GetGlobalRoutingID());
2238 LoadInfoMap::iterator existing = info_map->find(id);
2240 if (existing == info_map->end() ||
2241 LoadInfoIsMoreInteresting(load_info, existing->second)) {
2242 (*info_map)[id] = load_info;
2245 return info_map.Pass();
2248 void ResourceDispatcherHostImpl::UpdateLoadInfo() {
2249 scoped_ptr<LoadInfoMap> info_map(GetLoadInfoForAllRoutes());
2251 // Stop the timer if there are no more pending requests. Future new requests
2252 // will restart it as necessary.
2253 // Also stop the timer if there are no loading clients, to avoid waking up
2254 // unnecessarily when there is a long running (hanging get) request.
2255 if (info_map->empty() || !scheduler_->HasLoadingClients()) {
2256 update_load_states_timer_->Stop();
2257 return;
2260 BrowserThread::PostTask(
2261 BrowserThread::UI, FROM_HERE,
2262 base::Bind(&ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread,
2263 base::Passed(&info_map)));
2266 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id,
2267 int route_id) {
2268 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2269 GlobalRoutingID key(child_id, route_id);
2270 DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) <<
2271 "BlockRequestsForRoute called multiple time for the same RVH";
2272 blocked_loaders_map_[key] = new BlockedLoadersList();
2275 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id,
2276 int route_id) {
2277 ProcessBlockedRequestsForRoute(child_id, route_id, false);
2280 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id,
2281 int route_id) {
2282 ProcessBlockedRequestsForRoute(child_id, route_id, true);
2285 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
2286 int child_id,
2287 int route_id,
2288 bool cancel_requests) {
2289 BlockedLoadersMap::iterator iter = blocked_loaders_map_.find(
2290 GlobalRoutingID(child_id, route_id));
2291 if (iter == blocked_loaders_map_.end()) {
2292 // It's possible to reach here if the renderer crashed while an interstitial
2293 // page was showing.
2294 return;
2297 BlockedLoadersList* loaders = iter->second;
2299 // Removing the vector from the map unblocks any subsequent requests.
2300 blocked_loaders_map_.erase(iter);
2302 for (BlockedLoadersList::iterator loaders_iter = loaders->begin();
2303 loaders_iter != loaders->end(); ++loaders_iter) {
2304 linked_ptr<ResourceLoader> loader = *loaders_iter;
2305 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
2306 if (cancel_requests) {
2307 IncrementOutstandingRequestsMemory(-1, *info);
2308 } else {
2309 StartLoading(info, loader);
2313 delete loaders;
2316 ResourceDispatcherHostImpl::HttpAuthRelationType
2317 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
2318 const GURL& request_url,
2319 const GURL& first_party) {
2320 if (!first_party.is_valid())
2321 return HTTP_AUTH_RELATION_TOP;
2323 if (net::registry_controlled_domains::SameDomainOrHost(
2324 first_party, request_url,
2325 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES))
2326 return HTTP_AUTH_RELATION_SAME_DOMAIN;
2328 if (allow_cross_origin_auth_prompt())
2329 return HTTP_AUTH_RELATION_ALLOWED_CROSS;
2331 return HTTP_AUTH_RELATION_BLOCKED_CROSS;
2334 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
2335 return allow_cross_origin_auth_prompt_;
2338 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
2339 const GlobalRequestID& id) const {
2340 ResourceLoader* loader = GetLoader(id);
2341 return loader ? loader->is_transferring() : false;
2344 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(
2345 const GlobalRequestID& id) const {
2346 DCHECK_CURRENTLY_ON(BrowserThread::IO);
2348 LoaderMap::const_iterator i = pending_loaders_.find(id);
2349 if (i == pending_loaders_.end())
2350 return NULL;
2352 return i->second.get();
2355 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(int child_id,
2356 int request_id) const {
2357 return GetLoader(GlobalRequestID(child_id, request_id));
2360 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
2361 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
2362 DelegateMap::iterator it = delegate_map_.find(id);
2363 if (it == delegate_map_.end()) {
2364 it = delegate_map_.insert(
2365 std::make_pair(
2367 new base::ObserverList<ResourceMessageDelegate>))
2368 .first;
2370 it->second->AddObserver(delegate);
2373 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
2374 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
2375 DCHECK(ContainsKey(delegate_map_, id));
2376 DelegateMap::iterator it = delegate_map_.find(id);
2377 DCHECK(it->second->HasObserver(delegate));
2378 it->second->RemoveObserver(delegate);
2379 if (!it->second->might_have_observers()) {
2380 delete it->second;
2381 delegate_map_.erase(it);
2385 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
2386 const ResourceHostMsg_Request& request_data,
2387 int child_id,
2388 bool is_sync_load) {
2389 int load_flags = request_data.load_flags;
2391 // Although EV status is irrelevant to sub-frames and sub-resources, we have
2392 // to perform EV certificate verification on all resources because an HTTP
2393 // keep-alive connection created to load a sub-frame or a sub-resource could
2394 // be reused to load a main frame.
2395 load_flags |= net::LOAD_VERIFY_EV_CERT;
2396 if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
2397 load_flags |= net::LOAD_MAIN_FRAME;
2398 } else if (request_data.resource_type == RESOURCE_TYPE_PREFETCH) {
2399 load_flags |= net::LOAD_PREFETCH;
2402 if (is_sync_load)
2403 load_flags |= net::LOAD_IGNORE_LIMITS;
2405 return load_flags;
2408 } // namespace content