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