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"
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/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"
106 using base::TimeDelta
;
107 using base::TimeTicks
;
108 using storage::ShareableFileReference
;
110 // ----------------------------------------------------------------------------
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
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
;
185 sha1_histogram
= SHA1_PRESENT
;
188 if (resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
189 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.MainFrame",
191 SHA1_HISTOGRAM_TYPES_MAX
);
193 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.Subresource",
195 SHA1_HISTOGRAM_TYPES_MAX
);
199 bool IsDetachableResourceType(ResourceType type
) {
201 case RESOURCE_TYPE_PREFETCH
:
202 case RESOURCE_TYPE_PING
:
209 // Aborts a request before an URLRequest has actually been created.
210 void AbortRequestBeforeItStarts(ResourceMessageFilter
* filter
,
211 IPC::Message
* sync_result
,
214 SyncLoadResult result
;
215 result
.error_code
= net::ERR_ABORTED
;
216 ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result
, result
);
217 filter
->Send(sync_result
);
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());
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
;
249 case blink::WebReferrerPolicyNoReferrerWhenDowngrade
:
250 net_referrer_policy
=
251 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
253 case blink::WebReferrerPolicyOriginWhenCrossOrigin
:
254 net_referrer_policy
=
255 net::URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
;
257 case blink::WebReferrerPolicyDefault
:
259 net_referrer_policy
=
260 command_line
->HasSwitch(switches::kReducedReferrerGranularity
)
262 REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
264 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
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
,
276 const ResourceHostMsg_Request
& request_data
,
277 storage::FileSystemContext
* file_system_context
) {
278 if (process_type
== PROCESS_TYPE_PLUGIN
)
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();
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();
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();
318 void RemoveDownloadFileFromChildSecurityPolicy(int child_id
,
319 const base::FilePath
& path
) {
320 ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile(
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(
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(),
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
));
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
));
367 web_contents
->DidGetResourceResponseStart(*details
.get());
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
)
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
)
390 scoped_ptr
<storage::BlobDataHandle
> handle
=
391 blob_context
->GetBlobDataFromUUID(element
.blob_uuid());
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());
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
,
410 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
411 RenderFrameHostImpl
* host
=
412 RenderFrameHostImpl::FromID(render_process_id
, render_frame_id
);
414 DCHECK(host
->frame_tree_node()->IsMainFrame());
415 host
->frame_tree_node()->navigator()->LogResourceRequestTime(
423 ResourceDispatcherHost
* ResourceDispatcherHost::Get() {
424 return g_resource_dispatcher_host
;
427 ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
428 : save_file_manager_(new SaveFileManager()),
431 num_in_flight_requests_(0),
432 max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()),
433 max_num_in_flight_requests_per_process_(
435 max_num_in_flight_requests_
* kMaxRequestsPerProcessRatio
)),
436 max_outstanding_requests_cost_per_process_(
437 kMaxOutstandingRequestsCostPerProcess
),
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
,
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
;
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
);
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
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
++);
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.
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
533 DCHECK_EQ(context
, info
->GetContext());
534 IncrementOutstandingRequestsMemory(-1, *info
);
535 loaders_to_cancel
.push_back(loader
);
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());
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
,
589 bool do_not_prompt_for_login
,
590 scoped_ptr
<DownloadSaveInfo
> save_info
,
592 const DownloadStartedCallback
& started_callback
) {
594 return CallbackAndReturn(started_callback
,
595 DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN
);
597 const GURL
& url
= request
->original_url();
599 // http://crbug.com/90971
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
;
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
;
616 extra_load_flags
|= net::LOAD_PREFERRING_CACHE
;
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
625 // TODO(davidben): Is this correct? If this came from a
626 // ViewHostMsg_DownloadUrl in a frame, should it have first-party URL set
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
);
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(
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(),
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
);
679 ResourceLoader
* loader
= GetLoader(info
->GetGlobalRequestID());
681 loader
->ClearLoginDelegate();
685 void ResourceDispatcherHostImpl::Shutdown() {
686 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
687 BrowserThread::PostTask(BrowserThread::IO
,
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
,
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()));
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()) {
714 new ThrottlingResourceHandler(
715 handler
.Pass(), request
, throttles
.Pass()));
718 return handler
.Pass();
721 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::MaybeInterceptAsStream(
722 const base::FilePath
& plugin_path
,
723 net::URLRequest
* request
,
724 ResourceResponse
* response
,
725 std::string
* payload
) {
727 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
728 const std::string
& mime_type
= response
->head
.mime_type
;
732 !delegate_
->ShouldInterceptResourceAsStream(
733 request
, plugin_path
, mime_type
, &origin
, 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(),
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
) {
768 return delegate_
->CreateLoginDelegate(auth_info
, loader
->request());
771 bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader
* loader
,
776 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
778 if (!IsResourceTypeFrame(info
->GetResourceType()))
781 const net::URLRequestJobFactory
* job_factory
=
782 info
->GetContext()->GetRequestContext()->job_factory();
783 if (job_factory
->IsHandledURL(url
))
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
))
809 // Notify the observers on the UI thread.
810 scoped_ptr
<ResourceRedirectDetails
> detail(new ResourceRedirectDetails(
812 GetCertID(loader
->request(), info
->GetChildID()),
814 BrowserThread::PostTask(
815 BrowserThread::UI
, FROM_HERE
,
818 render_process_id
, render_frame_host
, base::Passed(&detail
)));
821 void ResourceDispatcherHostImpl::DidReceiveResponse(ResourceLoader
* loader
) {
822 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
823 net::URLRequest
* request
= loader
->request();
824 if (request
->was_fetched_via_proxy() &&
825 request
->was_fetched_via_spdy() &&
826 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
))
835 // Notify the observers on the UI thread.
836 scoped_ptr
<ResourceRequestDetails
> detail(new ResourceRequestDetails(
837 request
, GetCertID(request
, info
->GetChildID())));
838 BrowserThread::PostTask(
839 BrowserThread::UI
, FROM_HERE
,
842 render_process_id
, render_frame_host
, base::Passed(&detail
)));
845 void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader
* loader
) {
846 ResourceRequestInfo
* info
= loader
->GetRequestInfo();
848 // Record final result of all resource loads.
849 if (info
->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME
) {
850 // This enumeration has "3" appended to its name to distinguish it from
852 UMA_HISTOGRAM_SPARSE_SLOWLY(
853 "Net.ErrorCodesForMainFrame3",
854 -loader
->request()->status().error());
856 // Record time to success and error for the most common errors, and for
857 // the aggregate remainder errors.
858 base::TimeDelta
request_loading_time(
859 base::TimeTicks::Now() - loader
->request()->creation_time());
860 switch (loader
->request()->status().error()) {
862 UMA_HISTOGRAM_LONG_TIMES(
863 "Net.RequestTime2.Success", request_loading_time
);
865 case net::ERR_ABORTED
:
866 UMA_HISTOGRAM_LONG_TIMES(
867 "Net.RequestTime2.ErrAborted", request_loading_time
);
869 case net::ERR_CONNECTION_RESET
:
870 UMA_HISTOGRAM_LONG_TIMES(
871 "Net.RequestTime2.ErrConnectionReset", request_loading_time
);
873 case net::ERR_CONNECTION_TIMED_OUT
:
874 UMA_HISTOGRAM_LONG_TIMES(
875 "Net.RequestTime2.ErrConnectionTimedOut", request_loading_time
);
877 case net::ERR_INTERNET_DISCONNECTED
:
878 UMA_HISTOGRAM_LONG_TIMES(
879 "Net.RequestTime2.ErrInternetDisconnected", request_loading_time
);
881 case net::ERR_NAME_NOT_RESOLVED
:
882 UMA_HISTOGRAM_LONG_TIMES(
883 "Net.RequestTime2.ErrNameNotResolved", request_loading_time
);
885 case net::ERR_TIMED_OUT
:
886 UMA_HISTOGRAM_LONG_TIMES(
887 "Net.RequestTime2.ErrTimedOut", request_loading_time
);
890 UMA_HISTOGRAM_LONG_TIMES(
891 "Net.RequestTime2.MiscError", request_loading_time
);
895 if (loader
->request()->url().SchemeIsCryptographic()) {
896 if (loader
->request()->url().host() == "www.google.com") {
897 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2",
898 -loader
->request()->status().error());
901 int num_valid_scts
= std::count_if(
902 loader
->request()->ssl_info().signed_certificate_timestamps
.begin(),
903 loader
->request()->ssl_info().signed_certificate_timestamps
.end(),
905 UMA_HISTOGRAM_COUNTS_100(
906 "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts
);
909 if (info
->GetResourceType() == RESOURCE_TYPE_IMAGE
) {
910 UMA_HISTOGRAM_SPARSE_SLOWLY(
911 "Net.ErrorCodesForImages",
912 -loader
->request()->status().error());
914 // This enumeration has "2" appended to distinguish it from older versions.
915 UMA_HISTOGRAM_SPARSE_SLOWLY(
916 "Net.ErrorCodesForSubresources2",
917 -loader
->request()->status().error());
920 if (loader
->request()->url().SchemeIsCryptographic()) {
921 RecordCertificateHistograms(loader
->request()->ssl_info(),
922 info
->GetResourceType());
926 delegate_
->RequestComplete(loader
->request());
928 // Destroy the ResourceLoader.
929 RemovePendingRequest(info
->GetChildID(), info
->GetRequestID());
932 void ResourceDispatcherHostImpl::OnInit() {
933 scheduler_
.reset(new ResourceScheduler
);
936 void ResourceDispatcherHostImpl::OnShutdown() {
937 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
940 pending_loaders_
.clear();
942 // Make sure we shutdown the timer now, otherwise by the time our destructor
943 // runs if the timer is still running the Task is deleted twice (once by
944 // the MessageLoop and the second time by RepeatingTimer).
945 update_load_states_timer_
.reset();
947 // Clear blocked requests if any left.
948 // Note that we have to do this in 2 passes as we cannot call
949 // CancelBlockedRequestsForRoute while iterating over
950 // blocked_loaders_map_, as it modifies it.
951 std::set
<GlobalRoutingID
> ids
;
952 for (BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.begin();
953 iter
!= blocked_loaders_map_
.end(); ++iter
) {
954 std::pair
<std::set
<GlobalRoutingID
>::iterator
, bool> result
=
955 ids
.insert(iter
->first
);
956 // We should not have duplicates.
957 DCHECK(result
.second
);
959 for (std::set
<GlobalRoutingID
>::const_iterator iter
= ids
.begin();
960 iter
!= ids
.end(); ++iter
) {
961 CancelBlockedRequestsForRoute(iter
->child_id
, iter
->route_id
);
967 bool ResourceDispatcherHostImpl::OnMessageReceived(
968 const IPC::Message
& message
,
969 ResourceMessageFilter
* filter
) {
972 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcherHostImpl
, message
)
973 IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource
, OnRequestResource
)
974 IPC_MESSAGE_HANDLER_DELAY_REPLY(ResourceHostMsg_SyncLoad
, OnSyncLoad
)
975 IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile
,
976 OnReleaseDownloadedFile
)
977 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataDownloaded_ACK
, OnDataDownloadedACK
)
978 IPC_MESSAGE_HANDLER(ResourceHostMsg_UploadProgress_ACK
, OnUploadProgressACK
)
979 IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest
, OnCancelRequest
)
980 IPC_MESSAGE_UNHANDLED(handled
= false)
981 IPC_END_MESSAGE_MAP()
983 if (!handled
&& IPC_MESSAGE_ID_CLASS(message
.type()) == ResourceMsgStart
) {
984 base::PickleIterator
iter(message
);
986 bool ok
= iter
.ReadInt(&request_id
);
988 GlobalRequestID
id(filter_
->child_id(), request_id
);
989 DelegateMap::iterator it
= delegate_map_
.find(id
);
990 if (it
!= delegate_map_
.end()) {
991 base::ObserverList
<ResourceMessageDelegate
>::Iterator
del_it(it
->second
);
992 ResourceMessageDelegate
* delegate
;
993 while (!handled
&& (delegate
= del_it
.GetNext()) != NULL
) {
994 handled
= delegate
->OnMessageReceived(message
);
998 // As the unhandled resource message effectively has no consumer, mark it as
999 // handled to prevent needless propagation through the filter pipeline.
1007 void ResourceDispatcherHostImpl::OnRequestResource(
1010 const ResourceHostMsg_Request
& request_data
) {
1011 // TODO(pkasting): Remove ScopedTracker below once crbug.com/477117 is fixed.
1012 tracked_objects::ScopedTracker
tracking_profile(
1013 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1014 "477117 ResourceDispatcherHostImpl::OnRequestResource"));
1015 // When logging time-to-network only care about main frame and non-transfer
1017 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
&&
1018 request_data
.transferred_request_request_id
== -1 &&
1019 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1020 switches::kEnableBrowserSideNavigation
)) {
1021 BrowserThread::PostTask(
1024 base::Bind(&LogResourceRequestTimeOnUI
,
1026 filter_
->child_id(),
1027 request_data
.render_frame_id
,
1030 BeginRequest(request_id
, request_data
, NULL
, routing_id
);
1033 // Begins a resource request with the given params on behalf of the specified
1034 // child process. Responses will be dispatched through the given receiver. The
1035 // process ID is used to lookup WebContentsImpl from routing_id's in the case of
1036 // a request from a renderer. request_context is the cookie/cache context to be
1037 // used for this request.
1039 // If sync_result is non-null, then a SyncLoad reply will be generated, else
1040 // a normal asynchronous set of response messages will be generated.
1041 void ResourceDispatcherHostImpl::OnSyncLoad(
1043 const ResourceHostMsg_Request
& request_data
,
1044 IPC::Message
* sync_result
) {
1045 BeginRequest(request_id
, request_data
, sync_result
,
1046 sync_result
->routing_id());
1049 void ResourceDispatcherHostImpl::UpdateRequestForTransfer(
1053 const ResourceHostMsg_Request
& request_data
,
1054 const linked_ptr
<ResourceLoader
>& loader
) {
1055 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
1056 GlobalRoutingID
old_routing_id(
1057 request_data
.transferred_request_child_id
, info
->GetRouteID());
1058 GlobalRequestID
old_request_id(request_data
.transferred_request_child_id
,
1059 request_data
.transferred_request_request_id
);
1060 GlobalRoutingID
new_routing_id(child_id
, route_id
);
1061 GlobalRequestID
new_request_id(child_id
, request_id
);
1063 // Clear out data that depends on |info| before updating it.
1064 // We always need to move the memory stats to the new process. In contrast,
1065 // stats.num_requests is only tracked for some requests (those that require
1066 // file descriptors for their shared memory buffer).
1067 IncrementOutstandingRequestsMemory(-1, *info
);
1068 bool should_update_count
= info
->counted_as_in_flight_request();
1069 if (should_update_count
)
1070 IncrementOutstandingRequestsCount(-1, info
);
1071 pending_loaders_
.erase(old_request_id
);
1073 // ResourceHandlers should always get state related to the request from the
1074 // ResourceRequestInfo rather than caching it locally. This lets us update
1075 // the info object when a transfer occurs.
1076 info
->UpdateForTransfer(child_id
, route_id
, request_data
.origin_pid
,
1077 request_id
, request_data
.parent_render_frame_id
,
1078 filter_
->GetWeakPtr());
1080 // Update maps that used the old IDs, if necessary. Some transfers in tests
1081 // do not actually use a different ID, so not all maps need to be updated.
1082 pending_loaders_
[new_request_id
] = loader
;
1083 IncrementOutstandingRequestsMemory(1, *info
);
1084 if (should_update_count
)
1085 IncrementOutstandingRequestsCount(1, info
);
1086 if (old_routing_id
!= new_routing_id
) {
1087 if (blocked_loaders_map_
.find(old_routing_id
) !=
1088 blocked_loaders_map_
.end()) {
1089 blocked_loaders_map_
[new_routing_id
] =
1090 blocked_loaders_map_
[old_routing_id
];
1091 blocked_loaders_map_
.erase(old_routing_id
);
1094 if (old_request_id
!= new_request_id
) {
1095 DelegateMap::iterator it
= delegate_map_
.find(old_request_id
);
1096 if (it
!= delegate_map_
.end()) {
1097 // Tell each delegate that the request ID has changed.
1098 base::ObserverList
<ResourceMessageDelegate
>::Iterator
del_it(it
->second
);
1099 ResourceMessageDelegate
* delegate
;
1100 while ((delegate
= del_it
.GetNext()) != NULL
) {
1101 delegate
->set_request_id(new_request_id
);
1103 // Now store the observer list under the new request ID.
1104 delegate_map_
[new_request_id
] = delegate_map_
[old_request_id
];
1105 delegate_map_
.erase(old_request_id
);
1109 AppCacheInterceptor::CompleteCrossSiteTransfer(
1112 request_data
.appcache_host_id
);
1114 ServiceWorkerRequestHandler
* handler
=
1115 ServiceWorkerRequestHandler::GetHandler(loader
->request());
1117 handler
->CompleteCrossSiteTransfer(
1118 child_id
, request_data
.service_worker_provider_id
);
1121 // We should have a CrossSiteResourceHandler to finish the transfer.
1122 DCHECK(info
->cross_site_handler());
1125 void ResourceDispatcherHostImpl::BeginRequest(
1127 const ResourceHostMsg_Request
& request_data
,
1128 IPC::Message
* sync_result
, // only valid for sync
1130 int process_type
= filter_
->process_type();
1131 int child_id
= filter_
->child_id();
1133 // Reject invalid priority.
1134 if (request_data
.priority
< net::MINIMUM_PRIORITY
||
1135 request_data
.priority
> net::MAXIMUM_PRIORITY
) {
1136 bad_message::ReceivedBadMessage(filter_
, bad_message::RDH_INVALID_PRIORITY
);
1140 // If we crash here, figure out what URL the renderer was requesting.
1141 // http://crbug.com/91398
1143 base::strlcpy(url_buf
, request_data
.url
.spec().c_str(), arraysize(url_buf
));
1144 base::debug::Alias(url_buf
);
1146 // If the request that's coming in is being transferred from another process,
1147 // we want to reuse and resume the old loader rather than start a new one.
1148 LoaderMap::iterator it
= pending_loaders_
.find(
1149 GlobalRequestID(request_data
.transferred_request_child_id
,
1150 request_data
.transferred_request_request_id
));
1151 if (it
!= pending_loaders_
.end()) {
1152 // If the request is transferring to a new process, we can update our
1153 // state and let it resume with its existing ResourceHandlers.
1154 if (it
->second
->is_transferring()) {
1155 linked_ptr
<ResourceLoader
> deferred_loader
= it
->second
;
1156 UpdateRequestForTransfer(child_id
, route_id
, request_id
,
1157 request_data
, deferred_loader
);
1159 deferred_loader
->CompleteTransfer();
1161 bad_message::ReceivedBadMessage(
1162 filter_
, bad_message::RDH_REQUEST_NOT_TRANSFERRING
);
1167 ResourceContext
* resource_context
= NULL
;
1168 net::URLRequestContext
* request_context
= NULL
;
1169 filter_
->GetContexts(request_data
, &resource_context
, &request_context
);
1170 // http://crbug.com/90971
1171 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1174 !ShouldServiceRequest(process_type
, child_id
, request_data
,
1175 filter_
->file_system_context())) {
1176 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1180 // Allow the observer to block/handle the request.
1181 if (delegate_
&& !delegate_
->ShouldBeginRequest(request_data
.method
,
1183 request_data
.resource_type
,
1184 resource_context
)) {
1185 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1189 // Construct the request.
1190 scoped_ptr
<net::URLRequest
> new_request
= request_context
->CreateRequest(
1191 request_data
.url
, request_data
.priority
, NULL
);
1193 new_request
->set_method(request_data
.method
);
1194 new_request
->set_first_party_for_cookies(
1195 request_data
.first_party_for_cookies
);
1197 // If the request is a MAIN_FRAME request, the first-party URL gets updated on
1199 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
1200 new_request
->set_first_party_url_policy(
1201 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1204 const Referrer
referrer(request_data
.referrer
, request_data
.referrer_policy
);
1205 SetReferrerForRequest(new_request
.get(), referrer
);
1207 net::HttpRequestHeaders headers
;
1208 headers
.AddHeadersFromString(request_data
.headers
);
1209 new_request
->SetExtraRequestHeaders(headers
);
1211 storage::BlobStorageContext
* blob_context
=
1212 GetBlobStorageContext(filter_
->blob_storage_context());
1213 // Resolve elements from request_body and prepare upload data.
1214 if (request_data
.request_body
.get()) {
1215 // |blob_context| could be null when the request is from the plugins because
1216 // ResourceMessageFilters created in PluginProcessHost don't have the blob
1219 // Attaches the BlobDataHandles to request_body not to free the blobs and
1220 // any attached shareable files until upload completion. These data will
1221 // be used in UploadDataStream and ServiceWorkerURLRequestJob.
1222 AttachRequestBodyBlobDataHandles(
1223 request_data
.request_body
.get(),
1226 new_request
->set_upload(UploadDataStreamBuilder::Build(
1227 request_data
.request_body
.get(),
1229 filter_
->file_system_context(),
1230 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1234 bool allow_download
= request_data
.allow_download
&&
1235 IsResourceTypeFrame(request_data
.resource_type
);
1236 bool do_not_prompt_for_login
= request_data
.do_not_prompt_for_login
;
1237 bool is_sync_load
= sync_result
!= NULL
;
1239 BuildLoadFlagsForRequest(request_data
, child_id
, is_sync_load
);
1240 if (request_data
.resource_type
== RESOURCE_TYPE_PREFETCH
||
1241 request_data
.resource_type
== RESOURCE_TYPE_FAVICON
) {
1242 do_not_prompt_for_login
= true;
1244 if (request_data
.resource_type
== RESOURCE_TYPE_IMAGE
&&
1245 HTTP_AUTH_RELATION_BLOCKED_CROSS
==
1246 HttpAuthRelationTypeOf(request_data
.url
,
1247 request_data
.first_party_for_cookies
)) {
1248 // Prevent third-party image content from prompting for login, as this
1249 // is often a scam to extract credentials for another domain from the user.
1250 // Only block image loads, as the attack applies largely to the "src"
1251 // property of the <img> tag. It is common for web properties to allow
1252 // untrusted values for <img src>; this is considered a fair thing for an
1253 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
1254 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
1255 // would be considered vulnerable in and of itself.
1256 do_not_prompt_for_login
= true;
1257 load_flags
|= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY
;
1260 // Sync loads should have maximum priority and should be the only
1261 // requets that have the ignore limits flag set.
1263 DCHECK_EQ(request_data
.priority
, net::MAXIMUM_PRIORITY
);
1264 DCHECK_NE(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1266 DCHECK_EQ(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1268 new_request
->SetLoadFlags(load_flags
);
1270 // Make extra info and read footer (contains request ID).
1271 ResourceRequestInfoImpl
* extra_info
= new ResourceRequestInfoImpl(
1272 process_type
, child_id
, route_id
,
1273 -1, // frame_tree_node_id
1274 request_data
.origin_pid
,
1276 request_data
.render_frame_id
,
1277 request_data
.is_main_frame
,
1278 request_data
.parent_is_main_frame
,
1279 request_data
.parent_render_frame_id
,
1280 request_data
.resource_type
,
1281 request_data
.transition_type
,
1282 request_data
.should_replace_current_entry
,
1283 false, // is download
1286 request_data
.has_user_gesture
,
1287 request_data
.enable_load_timing
,
1288 request_data
.enable_upload_progress
,
1289 do_not_prompt_for_login
,
1290 request_data
.referrer_policy
,
1291 request_data
.visiblity_state
,
1292 resource_context
, filter_
->GetWeakPtr(),
1294 // Request takes ownership.
1295 extra_info
->AssociateWithRequest(new_request
.get());
1297 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
1298 // Hang on to a reference to ensure the blob is not released prior
1299 // to the job being started.
1300 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1302 filter_
->blob_storage_context()->context()->GetBlobDataFromPublicURL(
1303 new_request
->url()));
1306 // Initialize the service worker handler for the request. We don't use
1307 // ServiceWorker for synchronous loads to avoid renderer deadlocks.
1308 ServiceWorkerRequestHandler::InitializeHandler(
1310 filter_
->service_worker_context(),
1313 request_data
.service_worker_provider_id
,
1314 request_data
.skip_service_worker
|| is_sync_load
,
1315 request_data
.fetch_request_mode
,
1316 request_data
.fetch_credentials_mode
,
1317 request_data
.resource_type
,
1318 request_data
.fetch_request_context_type
,
1319 request_data
.fetch_frame_type
,
1320 request_data
.request_body
);
1322 // Have the appcache associate its extra info with the request.
1323 AppCacheInterceptor::SetExtraRequestInfo(
1324 new_request
.get(), filter_
->appcache_service(), child_id
,
1325 request_data
.appcache_host_id
, request_data
.resource_type
,
1326 request_data
.should_reset_appcache
);
1328 scoped_ptr
<ResourceHandler
> handler(
1329 CreateResourceHandler(
1331 request_data
, sync_result
, route_id
, process_type
, child_id
,
1335 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
1338 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::CreateResourceHandler(
1339 net::URLRequest
* request
,
1340 const ResourceHostMsg_Request
& request_data
,
1341 IPC::Message
* sync_result
,
1345 ResourceContext
* resource_context
) {
1346 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1347 tracked_objects::ScopedTracker
tracking_profile(
1348 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1349 "456331 ResourceDispatcherHostImpl::CreateResourceHandler"));
1350 // Construct the IPC resource handler.
1351 scoped_ptr
<ResourceHandler
> handler
;
1353 // download_to_file is not supported for synchronous requests.
1354 if (request_data
.download_to_file
) {
1355 bad_message::ReceivedBadMessage(filter_
, bad_message::RDH_BAD_DOWNLOAD
);
1356 return scoped_ptr
<ResourceHandler
>();
1359 handler
.reset(new SyncResourceHandler(request
, sync_result
, this));
1361 handler
.reset(new AsyncResourceHandler(request
, this));
1363 // The RedirectToFileResourceHandler depends on being next in the chain.
1364 if (request_data
.download_to_file
) {
1366 new RedirectToFileResourceHandler(handler
.Pass(), request
));
1370 // Prefetches and <a ping> requests outlive their child process.
1371 if (!sync_result
&& IsDetachableResourceType(request_data
.resource_type
)) {
1372 handler
.reset(new DetachableResourceHandler(
1374 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs
),
1378 // PlzNavigate: If using --enable-browser-side-navigation, the
1379 // CrossSiteResourceHandler is not needed. This codepath is not used for the
1380 // actual navigation request, but only the subsequent blob URL load. This does
1381 // not require request transfers.
1382 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1383 switches::kEnableBrowserSideNavigation
)) {
1384 // Install a CrossSiteResourceHandler for all main frame requests. This will
1385 // check whether a transfer is required and, if so, pause for the UI thread
1386 // to drive the transfer.
1387 bool is_swappable_navigation
=
1388 request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
;
1389 // If we are using --site-per-process, install it for subframes as well.
1390 if (!is_swappable_navigation
&&
1391 base::CommandLine::ForCurrentProcess()->HasSwitch(
1392 switches::kSitePerProcess
)) {
1393 is_swappable_navigation
=
1394 request_data
.resource_type
== RESOURCE_TYPE_SUB_FRAME
;
1396 if (is_swappable_navigation
&& process_type
== PROCESS_TYPE_RENDERER
)
1397 handler
.reset(new CrossSiteResourceHandler(handler
.Pass(), request
));
1400 return AddStandardHandlers(request
, request_data
.resource_type
,
1401 resource_context
, filter_
->appcache_service(),
1402 child_id
, route_id
, handler
.Pass());
1405 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::AddStandardHandlers(
1406 net::URLRequest
* request
,
1407 ResourceType resource_type
,
1408 ResourceContext
* resource_context
,
1409 AppCacheService
* appcache_service
,
1412 scoped_ptr
<ResourceHandler
> handler
) {
1414 PluginService
* plugin_service
= nullptr;
1415 #if defined(ENABLE_PLUGINS)
1416 plugin_service
= PluginService::GetInstance();
1418 // Insert a buffered event handler before the actual one.
1419 handler
.reset(new MimeTypeResourceHandler(handler
.Pass(), this,
1420 plugin_service
, request
));
1422 ScopedVector
<ResourceThrottle
> throttles
;
1424 delegate_
->RequestBeginning(request
,
1431 if (request
->has_upload()) {
1432 // Block power save while uploading data.
1433 throttles
.push_back(new PowerSaveBlockResourceThrottle());
1436 throttles
.push_back(
1437 scheduler_
->ScheduleRequest(child_id
, route_id
, request
).release());
1440 new ThrottlingResourceHandler(handler
.Pass(), request
, throttles
.Pass()));
1442 return handler
.Pass();
1445 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id
) {
1446 UnregisterDownloadedTempFile(filter_
->child_id(), request_id
);
1449 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id
) {
1450 // TODO(michaeln): maybe throttle DataDownloaded messages
1453 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1454 int child_id
, int request_id
, const base::FilePath
& file_path
) {
1455 scoped_refptr
<ShareableFileReference
> reference
=
1456 ShareableFileReference::Get(file_path
);
1457 DCHECK(reference
.get());
1459 registered_temp_files_
[child_id
][request_id
] = reference
;
1460 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1461 child_id
, reference
->path());
1463 // When the temp file is deleted, revoke permissions that the renderer has
1464 // to that file. This covers an edge case where the file is deleted and then
1465 // the same name is re-used for some other purpose, we don't want the old
1466 // renderer to still have access to it.
1468 // We do this when the file is deleted because the renderer can take a blob
1469 // reference to the temp file that outlives the url loaded that it was
1470 // loaded with to keep the file (and permissions) alive.
1471 reference
->AddFinalReleaseCallback(
1472 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy
,
1476 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1477 int child_id
, int request_id
) {
1478 DeletableFilesMap
& map
= registered_temp_files_
[child_id
];
1479 DeletableFilesMap::iterator found
= map
.find(request_id
);
1480 if (found
== map
.end())
1485 // Note that we don't remove the security bits here. This will be done
1486 // when all file refs are deleted (see RegisterDownloadedTempFile).
1489 bool ResourceDispatcherHostImpl::Send(IPC::Message
* message
) {
1494 void ResourceDispatcherHostImpl::OnUploadProgressACK(int request_id
) {
1495 ResourceLoader
* loader
= GetLoader(filter_
->child_id(), request_id
);
1497 loader
->OnUploadProgressACK();
1500 // Note that this cancel is subtly different from the other
1501 // CancelRequest methods in this file, which also tear down the loader.
1502 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id
) {
1503 int child_id
= filter_
->child_id();
1505 // When the old renderer dies, it sends a message to us to cancel its
1507 if (IsTransferredNavigation(GlobalRequestID(child_id
, request_id
)))
1510 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1512 // We probably want to remove this warning eventually, but I wanted to be
1513 // able to notice when this happens during initial development since it
1514 // should be rare and may indicate a bug.
1515 DVLOG(1) << "Canceling a request that wasn't found";
1519 loader
->CancelRequest(true);
1522 ResourceRequestInfoImpl
* ResourceDispatcherHostImpl::CreateRequestInfo(
1526 ResourceContext
* context
) {
1527 return new ResourceRequestInfoImpl(
1528 PROCESS_TYPE_RENDERER
,
1531 -1, // frame_tree_node_id
1534 MSG_ROUTING_NONE
, // render_frame_id
1535 false, // is_main_frame
1536 false, // parent_is_main_frame
1537 -1, // parent_render_frame_id
1538 RESOURCE_TYPE_SUB_RESOURCE
,
1539 ui::PAGE_TRANSITION_LINK
,
1540 false, // should_replace_current_entry
1541 download
, // is_download
1543 download
, // allow_download
1544 false, // has_user_gesture
1545 false, // enable_load_timing
1546 false, // enable_upload_progress
1547 false, // do_not_prompt_for_login
1548 blink::WebReferrerPolicyDefault
,
1549 blink::WebPageVisibilityStateVisible
,
1551 base::WeakPtr
<ResourceMessageFilter
>(), // filter
1555 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(int child_id
,
1559 scheduler_
->OnClientCreated(child_id
, route_id
, is_visible
, is_audible
);
1562 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1565 scheduler_
->OnClientDeleted(child_id
, route_id
);
1566 CancelRequestsForRoute(child_id
, route_id
);
1569 void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id
,
1572 scheduler_
->OnLoadingStateChanged(child_id
, route_id
, !is_loading
);
1575 void ResourceDispatcherHostImpl::OnRenderViewHostWasHidden(
1578 scheduler_
->OnVisibilityChanged(child_id
, route_id
, false);
1581 void ResourceDispatcherHostImpl::OnRenderViewHostWasShown(
1584 scheduler_
->OnVisibilityChanged(child_id
, route_id
, true);
1587 void ResourceDispatcherHostImpl::OnAudioRenderHostStreamStateChanged(
1591 // The ResourceDispatcherHost may have already been shut down.
1592 // See http://crbug.com/455098
1595 scheduler_
->OnAudibilityChanged(child_id
, route_id
, is_playing
);
1598 // This function is only used for saving feature.
1599 void ResourceDispatcherHostImpl::BeginSaveFile(
1601 const Referrer
& referrer
,
1604 ResourceContext
* context
) {
1608 // http://crbug.com/90971
1610 base::strlcpy(url_buf
, url
.spec().c_str(), arraysize(url_buf
));
1611 base::debug::Alias(url_buf
);
1612 CHECK(ContainsKey(active_resource_contexts_
, context
));
1616 const net::URLRequestContext
* request_context
= context
->GetRequestContext();
1618 request_context
->job_factory()->IsHandledURL(url
);
1620 // Since any URLs which have non-standard scheme have been filtered
1621 // by save manager(see GURL::SchemeIsStandard). This situation
1622 // should not happen.
1627 scoped_ptr
<net::URLRequest
> request(
1628 request_context
->CreateRequest(url
, net::DEFAULT_PRIORITY
, NULL
));
1629 request
->set_method("GET");
1630 SetReferrerForRequest(request
.get(), referrer
);
1632 // So far, for saving page, we need fetch content from cache, in the
1633 // future, maybe we can use a configuration to configure this behavior.
1634 request
->SetLoadFlags(net::LOAD_PREFERRING_CACHE
);
1636 // Since we're just saving some resources we need, disallow downloading.
1637 ResourceRequestInfoImpl
* extra_info
=
1638 CreateRequestInfo(child_id
, route_id
, false, context
);
1639 extra_info
->AssociateWithRequest(request
.get()); // Request takes ownership.
1641 scoped_ptr
<ResourceHandler
> handler(
1642 new SaveFileResourceHandler(request
.get(),
1646 save_file_manager_
.get()));
1648 BeginRequestInternal(request
.Pass(), handler
.Pass());
1651 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1652 const GlobalRequestID
& id
) {
1653 GetLoader(id
)->MarkAsTransferring();
1656 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1657 const GlobalRequestID
& id
) {
1658 // Request should still exist and be in the middle of a transfer.
1659 DCHECK(IsTransferredNavigation(id
));
1660 RemovePendingRequest(id
.child_id
, id
.request_id
);
1663 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1664 const GlobalRequestID
& id
) {
1665 ResourceLoader
* loader
= GetLoader(id
);
1666 // The response we were meant to resume could have already been canceled.
1668 loader
->CompleteTransfer();
1671 // The object died, so cancel and detach all requests associated with it except
1672 // for downloads and detachable resources, which belong to the browser process
1673 // even if initiated via a renderer.
1674 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id
) {
1675 CancelRequestsForRoute(child_id
, -1 /* cancel all */);
1676 registered_temp_files_
.erase(child_id
);
1679 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id
,
1681 // Since pending_requests_ is a map, we first build up a list of all of the
1682 // matching requests to be cancelled, and then we cancel them. Since there
1683 // may be more than one request to cancel, we cannot simply hold onto the map
1684 // iterators found in the first loop.
1686 // Find the global ID of all matching elements.
1687 bool any_requests_transferring
= false;
1688 std::vector
<GlobalRequestID
> matching_requests
;
1689 for (LoaderMap::const_iterator i
= pending_loaders_
.begin();
1690 i
!= pending_loaders_
.end(); ++i
) {
1691 if (i
->first
.child_id
!= child_id
)
1694 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
1696 GlobalRequestID
id(child_id
, i
->first
.request_id
);
1697 DCHECK(id
== i
->first
);
1698 // Don't cancel navigations that are expected to live beyond this process.
1699 if (IsTransferredNavigation(id
))
1700 any_requests_transferring
= true;
1701 if (info
->detachable_handler()) {
1702 info
->detachable_handler()->Detach();
1703 } else if (!info
->IsDownload() && !info
->is_stream() &&
1704 !IsTransferredNavigation(id
) &&
1705 (route_id
== -1 || route_id
== info
->GetRouteID())) {
1706 matching_requests
.push_back(id
);
1711 for (size_t i
= 0; i
< matching_requests
.size(); ++i
) {
1712 LoaderMap::iterator iter
= pending_loaders_
.find(matching_requests
[i
]);
1713 // Although every matching request was in pending_requests_ when we built
1714 // matching_requests, it is normal for a matching request to be not found
1715 // in pending_requests_ after we have removed some matching requests from
1716 // pending_requests_. For example, deleting a net::URLRequest that has
1717 // exclusive (write) access to an HTTP cache entry may unblock another
1718 // net::URLRequest that needs exclusive access to the same cache entry, and
1719 // that net::URLRequest may complete and remove itself from
1720 // pending_requests_. So we need to check that iter is not equal to
1721 // pending_requests_.end().
1722 if (iter
!= pending_loaders_
.end())
1723 RemovePendingLoader(iter
);
1726 // Don't clear the blocked loaders or offline policy maps if any of the
1727 // requests in route_id are being transferred to a new process, since those
1728 // maps will be updated with the new route_id after the transfer. Otherwise
1729 // we will lose track of this info when the old route goes away, before the
1730 // new one is created.
1731 if (any_requests_transferring
)
1734 // Now deal with blocked requests if any.
1735 if (route_id
!= -1) {
1736 if (blocked_loaders_map_
.find(GlobalRoutingID(child_id
, route_id
)) !=
1737 blocked_loaders_map_
.end()) {
1738 CancelBlockedRequestsForRoute(child_id
, route_id
);
1741 // We have to do all render views for the process |child_id|.
1742 // Note that we have to do this in 2 passes as we cannot call
1743 // CancelBlockedRequestsForRoute while iterating over
1744 // blocked_loaders_map_, as it modifies it.
1745 std::set
<int> route_ids
;
1746 for (BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.begin();
1747 iter
!= blocked_loaders_map_
.end(); ++iter
) {
1748 if (iter
->first
.child_id
== child_id
)
1749 route_ids
.insert(iter
->first
.route_id
);
1751 for (std::set
<int>::const_iterator iter
= route_ids
.begin();
1752 iter
!= route_ids
.end(); ++iter
) {
1753 CancelBlockedRequestsForRoute(child_id
, *iter
);
1758 // Cancels the request and removes it from the list.
1759 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id
,
1761 LoaderMap::iterator i
= pending_loaders_
.find(
1762 GlobalRequestID(child_id
, request_id
));
1763 if (i
== pending_loaders_
.end()) {
1764 NOTREACHED() << "Trying to remove a request that's not here";
1767 RemovePendingLoader(i
);
1770 void ResourceDispatcherHostImpl::RemovePendingLoader(
1771 const LoaderMap::iterator
& iter
) {
1772 ResourceRequestInfoImpl
* info
= iter
->second
->GetRequestInfo();
1774 // Remove the memory credit that we added when pushing the request onto
1775 // the pending list.
1776 IncrementOutstandingRequestsMemory(-1, *info
);
1778 pending_loaders_
.erase(iter
);
1781 void ResourceDispatcherHostImpl::CancelRequest(int child_id
,
1783 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1785 // We probably want to remove this warning eventually, but I wanted to be
1786 // able to notice when this happens during initial development since it
1787 // should be rare and may indicate a bug.
1788 DVLOG(1) << "Canceling a request that wasn't found";
1792 RemovePendingRequest(child_id
, request_id
);
1795 ResourceDispatcherHostImpl::OustandingRequestsStats
1796 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1797 const ResourceRequestInfoImpl
& info
) {
1798 OutstandingRequestsStatsMap::iterator entry
=
1799 outstanding_requests_stats_map_
.find(info
.GetChildID());
1800 OustandingRequestsStats stats
= { 0, 0 };
1801 if (entry
!= outstanding_requests_stats_map_
.end())
1802 stats
= entry
->second
;
1806 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1807 const ResourceRequestInfoImpl
& info
,
1808 const OustandingRequestsStats
& stats
) {
1809 if (stats
.memory_cost
== 0 && stats
.num_requests
== 0)
1810 outstanding_requests_stats_map_
.erase(info
.GetChildID());
1812 outstanding_requests_stats_map_
[info
.GetChildID()] = stats
;
1815 ResourceDispatcherHostImpl::OustandingRequestsStats
1816 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1818 const ResourceRequestInfoImpl
& info
) {
1819 DCHECK_EQ(1, abs(count
));
1821 // Retrieve the previous value (defaulting to 0 if not found).
1822 OustandingRequestsStats stats
= GetOutstandingRequestsStats(info
);
1824 // Insert/update the total; delete entries when their count reaches 0.
1825 stats
.memory_cost
+= count
* info
.memory_cost();
1826 DCHECK_GE(stats
.memory_cost
, 0);
1827 UpdateOutstandingRequestsStats(info
, stats
);
1832 ResourceDispatcherHostImpl::OustandingRequestsStats
1833 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1835 ResourceRequestInfoImpl
* info
) {
1836 DCHECK_EQ(1, abs(count
));
1837 num_in_flight_requests_
+= count
;
1839 // Keep track of whether this request is counting toward the number of
1840 // in-flight requests for this process, in case we need to transfer it to
1841 // another process. This should be a toggle.
1842 DCHECK_NE(info
->counted_as_in_flight_request(), count
> 0);
1843 info
->set_counted_as_in_flight_request(count
> 0);
1845 OustandingRequestsStats stats
= GetOutstandingRequestsStats(*info
);
1846 stats
.num_requests
+= count
;
1847 DCHECK_GE(stats
.num_requests
, 0);
1848 UpdateOutstandingRequestsStats(*info
, stats
);
1853 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1854 net::URLRequest
* request
) {
1855 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1856 OustandingRequestsStats stats
= IncrementOutstandingRequestsCount(1, info
);
1858 if (stats
.num_requests
> max_num_in_flight_requests_per_process_
)
1860 if (num_in_flight_requests_
> max_num_in_flight_requests_
)
1866 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1867 net::URLRequest
* request
) {
1868 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1869 IncrementOutstandingRequestsCount(-1, info
);
1872 void ResourceDispatcherHostImpl::BeginNavigationRequest(
1873 ResourceContext
* resource_context
,
1874 int frame_tree_node_id
,
1875 const NavigationRequestInfo
& info
,
1876 NavigationURLLoaderImplCore
* loader
) {
1877 // PlzNavigate: BeginNavigationRequest currently should only be used for the
1878 // browser-side navigations project.
1879 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1880 switches::kEnableBrowserSideNavigation
));
1882 ResourceType resource_type
= info
.is_main_frame
?
1883 RESOURCE_TYPE_MAIN_FRAME
: RESOURCE_TYPE_SUB_FRAME
;
1886 // TODO(davidben): Check ShouldServiceRequest here. This is important; it
1887 // needs to be checked relative to the child that /requested/ the
1888 // navigation. It's where file upload checks, etc., come in.
1889 (delegate_
&& !delegate_
->ShouldBeginRequest(
1890 info
.begin_params
.method
,
1891 info
.common_params
.url
,
1893 resource_context
))) {
1894 loader
->NotifyRequestFailed(false, net::ERR_ABORTED
);
1898 // Save the URL on the stack to help catch URLRequests which outlive their
1899 // URLRequestContexts. See https://crbug.com/90971
1902 url_buf
, info
.common_params
.url
.spec().c_str(), arraysize(url_buf
));
1903 base::debug::Alias(url_buf
);
1904 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1906 const net::URLRequestContext
* request_context
=
1907 resource_context
->GetRequestContext();
1909 int load_flags
= info
.begin_params
.load_flags
;
1910 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
1911 if (info
.is_main_frame
)
1912 load_flags
|= net::LOAD_MAIN_FRAME
;
1914 // TODO(davidben): BuildLoadFlagsForRequest includes logic for
1915 // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here?
1917 // Sync loads should have maximum priority and should be the only
1918 // requests that have the ignore limits flag set.
1919 DCHECK(!(load_flags
& net::LOAD_IGNORE_LIMITS
));
1921 scoped_ptr
<net::URLRequest
> new_request
;
1922 new_request
= request_context
->CreateRequest(
1923 info
.common_params
.url
, net::HIGHEST
, nullptr);
1925 new_request
->set_method(info
.begin_params
.method
);
1926 new_request
->set_first_party_for_cookies(
1927 info
.first_party_for_cookies
);
1928 if (info
.is_main_frame
) {
1929 new_request
->set_first_party_url_policy(
1930 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1933 SetReferrerForRequest(new_request
.get(), info
.common_params
.referrer
);
1935 net::HttpRequestHeaders headers
;
1936 headers
.AddHeadersFromString(info
.begin_params
.headers
);
1937 new_request
->SetExtraRequestHeaders(headers
);
1939 new_request
->SetLoadFlags(load_flags
);
1941 // Resolve elements from request_body and prepare upload data.
1942 if (info
.request_body
.get()) {
1943 storage::BlobStorageContext
* blob_context
= GetBlobStorageContext(
1944 GetChromeBlobStorageContextForResourceContext(resource_context
));
1945 AttachRequestBodyBlobDataHandles(
1946 info
.request_body
.get(),
1948 // TODO(davidben): The FileSystemContext is null here. In the case where
1949 // another renderer requested this navigation, this should be the same
1950 // FileSystemContext passed into ShouldServiceRequest.
1951 new_request
->set_upload(UploadDataStreamBuilder::Build(
1952 info
.request_body
.get(),
1954 nullptr, // file_system_context
1955 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1961 // Make extra info and read footer (contains request ID).
1963 // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so
1964 // that IO thread -> UI thread hops will work.
1965 ResourceRequestInfoImpl
* extra_info
= new ResourceRequestInfoImpl(
1966 PROCESS_TYPE_BROWSER
,
1969 info
.frame_tree_node_id
,
1970 -1, // request_data.origin_pid,
1972 -1, // request_data.render_frame_id,
1974 info
.parent_is_main_frame
,
1975 -1, // request_data.parent_render_frame_id,
1977 info
.common_params
.transition
,
1978 // should_replace_current_entry. This was only maintained at layer for
1979 // request transfers and isn't needed for browser-side navigations.
1981 false, // is download
1983 info
.common_params
.allow_download
,
1984 info
.begin_params
.has_user_gesture
,
1985 true, // enable_load_timing
1986 false, // enable_upload_progress
1987 false, // do_not_prompt_for_login
1988 info
.common_params
.referrer
.policy
,
1989 // TODO(davidben): This is only used for prerenders. Replace
1990 // is_showing with something for that. Or maybe it just comes from the
1991 // same mechanism as the cookie one.
1992 blink::WebPageVisibilityStateVisible
,
1994 base::WeakPtr
<ResourceMessageFilter
>(), // filter
1996 // Request takes ownership.
1997 extra_info
->AssociateWithRequest(new_request
.get());
1999 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
2000 // Hang on to a reference to ensure the blob is not released prior
2001 // to the job being started.
2002 ChromeBlobStorageContext
* blob_context
=
2003 GetChromeBlobStorageContextForResourceContext(resource_context
);
2004 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
2006 blob_context
->context()->GetBlobDataFromPublicURL(new_request
->url()));
2009 // TODO(davidben): Attach ServiceWorkerRequestHandler.
2010 // TODO(michaeln): Help out with this and that.
2011 // TODO(davidben): Attach AppCacheInterceptor.
2013 scoped_ptr
<ResourceHandler
> handler(new NavigationResourceHandler(
2014 new_request
.get(), loader
));
2016 // TODO(davidben): Pass in the appropriate appcache_service. Also fix the
2017 // dependency on child_id/route_id. Those are used by the ResourceScheduler;
2018 // currently it's a no-op.
2019 handler
= AddStandardHandlers(new_request
.get(), resource_type
,
2021 nullptr, // appcache_service
2026 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
2030 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
2031 net::URLRequest
* request
) {
2032 // The following fields should be a minor size contribution (experimentally
2033 // on the order of 100). However since they are variable length, it could
2034 // in theory be a sizeable contribution.
2035 int strings_cost
= request
->extra_request_headers().ToString().size() +
2036 request
->original_url().spec().size() +
2037 request
->referrer().size() +
2038 request
->method().size();
2040 // Note that this expression will typically be dominated by:
2041 // |kAvgBytesPerOutstandingRequest|.
2042 return kAvgBytesPerOutstandingRequest
+ strings_cost
;
2045 void ResourceDispatcherHostImpl::BeginRequestInternal(
2046 scoped_ptr
<net::URLRequest
> request
,
2047 scoped_ptr
<ResourceHandler
> handler
) {
2048 DCHECK(!request
->is_pending());
2049 ResourceRequestInfoImpl
* info
=
2050 ResourceRequestInfoImpl::ForRequest(request
.get());
2052 if ((TimeTicks::Now() - last_user_gesture_time_
) <
2053 TimeDelta::FromMilliseconds(kUserGestureWindowMs
)) {
2054 request
->SetLoadFlags(
2055 request
->load_flags() | net::LOAD_MAYBE_USER_GESTURE
);
2058 // Add the memory estimate that starting this request will consume.
2059 info
->set_memory_cost(CalculateApproximateMemoryCost(request
.get()));
2061 // If enqueing/starting this request will exceed our per-process memory
2062 // bound, abort it right away.
2063 OustandingRequestsStats stats
= IncrementOutstandingRequestsMemory(1, *info
);
2064 if (stats
.memory_cost
> max_outstanding_requests_cost_per_process_
) {
2065 // We call "CancelWithError()" as a way of setting the net::URLRequest's
2066 // status -- it has no effect beyond this, since the request hasn't started.
2067 request
->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES
);
2070 handler
->OnResponseCompleted(request
->status(), std::string(), &defer
);
2072 // TODO(darin): The handler is not ready for us to kill the request. Oops!
2076 IncrementOutstandingRequestsMemory(-1, *info
);
2078 // A ResourceHandler must not outlive its associated URLRequest.
2083 linked_ptr
<ResourceLoader
> loader(
2084 new ResourceLoader(request
.Pass(), handler
.Pass(), this));
2086 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2087 BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.find(id
);
2088 if (iter
!= blocked_loaders_map_
.end()) {
2089 // The request should be blocked.
2090 iter
->second
->push_back(loader
);
2094 StartLoading(info
, loader
);
2097 void ResourceDispatcherHostImpl::StartLoading(
2098 ResourceRequestInfoImpl
* info
,
2099 const linked_ptr
<ResourceLoader
>& loader
) {
2100 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
2101 tracked_objects::ScopedTracker
tracking_profile(
2102 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2103 "456331 ResourceDispatcherHostImpl::StartLoading"));
2104 pending_loaders_
[info
->GetGlobalRequestID()] = loader
;
2106 loader
->StartRequest();
2109 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl
* contents
) {
2110 last_user_gesture_time_
= TimeTicks::Now();
2113 net::URLRequest
* ResourceDispatcherHostImpl::GetURLRequest(
2114 const GlobalRequestID
& id
) {
2115 ResourceLoader
* loader
= GetLoader(id
);
2119 return loader
->request();
2123 bool ResourceDispatcherHostImpl::LoadInfoIsMoreInteresting(const LoadInfo
& a
,
2124 const LoadInfo
& b
) {
2125 // Set |*_uploading_size| to be the size of the corresponding upload body if
2126 // it's currently being uploaded.
2128 uint64 a_uploading_size
= 0;
2129 if (a
.load_state
.state
== net::LOAD_STATE_SENDING_REQUEST
)
2130 a_uploading_size
= a
.upload_size
;
2132 uint64 b_uploading_size
= 0;
2133 if (b
.load_state
.state
== net::LOAD_STATE_SENDING_REQUEST
)
2134 b_uploading_size
= b
.upload_size
;
2136 if (a_uploading_size
!= b_uploading_size
)
2137 return a_uploading_size
> b_uploading_size
;
2139 return a
.load_state
.state
> b
.load_state
.state
;
2143 void ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread(
2144 scoped_ptr
<LoadInfoMap
> info_map
) {
2145 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
2147 tracked_objects::ScopedTracker
tracking_profile(
2148 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2149 "466285 ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread"));
2150 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2151 for (const auto& load_info
: *info_map
) {
2152 RenderViewHostImpl
* view
= RenderViewHostImpl::FromID(
2153 load_info
.first
.child_id
, load_info
.first
.route_id
);
2154 // The view could be gone at this point.
2156 view
->LoadStateChanged(load_info
.second
.url
, load_info
.second
.load_state
,
2157 load_info
.second
.upload_position
,
2158 load_info
.second
.upload_size
);
2163 scoped_ptr
<ResourceDispatcherHostImpl::LoadInfoMap
>
2164 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes() {
2165 // Populate this map with load state changes, and then send them on to the UI
2166 // thread where they can be passed along to the respective RVHs.
2167 scoped_ptr
<LoadInfoMap
> info_map(new LoadInfoMap());
2169 for (const auto& loader
: pending_loaders_
) {
2170 net::URLRequest
* request
= loader
.second
->request();
2171 net::UploadProgress upload_progress
= request
->GetUploadProgress();
2174 load_info
.url
= request
->url();
2175 load_info
.load_state
= request
->GetLoadState();
2176 load_info
.upload_size
= upload_progress
.size();
2177 load_info
.upload_position
= upload_progress
.position();
2179 GlobalRoutingID
id(loader
.second
->GetRequestInfo()->GetGlobalRoutingID());
2180 LoadInfoMap::iterator existing
= info_map
->find(id
);
2182 if (existing
== info_map
->end() ||
2183 LoadInfoIsMoreInteresting(load_info
, existing
->second
)) {
2184 (*info_map
)[id
] = load_info
;
2187 return info_map
.Pass();
2190 void ResourceDispatcherHostImpl::UpdateLoadInfo() {
2191 scoped_ptr
<LoadInfoMap
> info_map(GetLoadInfoForAllRoutes());
2193 // Stop the timer if there are no more pending requests. Future new requests
2194 // will restart it as necessary.
2195 // Also stop the timer if there are no loading clients, to avoid waking up
2196 // unnecessarily when there is a long running (hanging get) request.
2197 if (info_map
->empty() || !scheduler_
->HasLoadingClients()) {
2198 update_load_states_timer_
->Stop();
2202 BrowserThread::PostTask(
2203 BrowserThread::UI
, FROM_HERE
,
2204 base::Bind(&ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread
,
2205 base::Passed(&info_map
)));
2208 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id
,
2210 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
2211 GlobalRoutingID
key(child_id
, route_id
);
2212 DCHECK(blocked_loaders_map_
.find(key
) == blocked_loaders_map_
.end()) <<
2213 "BlockRequestsForRoute called multiple time for the same RVH";
2214 blocked_loaders_map_
[key
] = new BlockedLoadersList();
2217 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id
,
2219 ProcessBlockedRequestsForRoute(child_id
, route_id
, false);
2222 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id
,
2224 ProcessBlockedRequestsForRoute(child_id
, route_id
, true);
2227 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
2230 bool cancel_requests
) {
2231 BlockedLoadersMap::iterator iter
= blocked_loaders_map_
.find(
2232 GlobalRoutingID(child_id
, route_id
));
2233 if (iter
== blocked_loaders_map_
.end()) {
2234 // It's possible to reach here if the renderer crashed while an interstitial
2235 // page was showing.
2239 BlockedLoadersList
* loaders
= iter
->second
;
2241 // Removing the vector from the map unblocks any subsequent requests.
2242 blocked_loaders_map_
.erase(iter
);
2244 for (BlockedLoadersList::iterator loaders_iter
= loaders
->begin();
2245 loaders_iter
!= loaders
->end(); ++loaders_iter
) {
2246 linked_ptr
<ResourceLoader
> loader
= *loaders_iter
;
2247 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
2248 if (cancel_requests
) {
2249 IncrementOutstandingRequestsMemory(-1, *info
);
2251 StartLoading(info
, loader
);
2258 ResourceDispatcherHostImpl::HttpAuthRelationType
2259 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
2260 const GURL
& request_url
,
2261 const GURL
& first_party
) {
2262 if (!first_party
.is_valid())
2263 return HTTP_AUTH_RELATION_TOP
;
2265 if (net::registry_controlled_domains::SameDomainOrHost(
2266 first_party
, request_url
,
2267 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
))
2268 return HTTP_AUTH_RELATION_SAME_DOMAIN
;
2270 if (allow_cross_origin_auth_prompt())
2271 return HTTP_AUTH_RELATION_ALLOWED_CROSS
;
2273 return HTTP_AUTH_RELATION_BLOCKED_CROSS
;
2276 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
2277 return allow_cross_origin_auth_prompt_
;
2280 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
2281 const GlobalRequestID
& id
) const {
2282 ResourceLoader
* loader
= GetLoader(id
);
2283 return loader
? loader
->is_transferring() : false;
2286 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(
2287 const GlobalRequestID
& id
) const {
2288 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
2290 LoaderMap::const_iterator i
= pending_loaders_
.find(id
);
2291 if (i
== pending_loaders_
.end())
2294 return i
->second
.get();
2297 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(int child_id
,
2298 int request_id
) const {
2299 return GetLoader(GlobalRequestID(child_id
, request_id
));
2302 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
2303 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2304 DelegateMap::iterator it
= delegate_map_
.find(id
);
2305 if (it
== delegate_map_
.end()) {
2306 it
= delegate_map_
.insert(
2309 new base::ObserverList
<ResourceMessageDelegate
>))
2312 it
->second
->AddObserver(delegate
);
2315 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
2316 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2317 DCHECK(ContainsKey(delegate_map_
, id
));
2318 DelegateMap::iterator it
= delegate_map_
.find(id
);
2319 DCHECK(it
->second
->HasObserver(delegate
));
2320 it
->second
->RemoveObserver(delegate
);
2321 if (!it
->second
->might_have_observers()) {
2323 delegate_map_
.erase(it
);
2327 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
2328 const ResourceHostMsg_Request
& request_data
,
2330 bool is_sync_load
) {
2331 int load_flags
= request_data
.load_flags
;
2333 // Although EV status is irrelevant to sub-frames and sub-resources, we have
2334 // to perform EV certificate verification on all resources because an HTTP
2335 // keep-alive connection created to load a sub-frame or a sub-resource could
2336 // be reused to load a main frame.
2337 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
2338 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
2339 load_flags
|= net::LOAD_MAIN_FRAME
;
2340 } else if (request_data
.resource_type
== RESOURCE_TYPE_PREFETCH
) {
2341 load_flags
|= net::LOAD_PREFETCH
;
2345 load_flags
|= net::LOAD_IGNORE_LIMITS
;
2347 ChildProcessSecurityPolicyImpl
* policy
=
2348 ChildProcessSecurityPolicyImpl::GetInstance();
2350 // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only
2351 // allow requesting them if requester has ReadRawCookies permission.
2352 if ((load_flags
& net::LOAD_REPORT_RAW_HEADERS
)
2353 && !policy
->CanReadRawCookies(child_id
)) {
2354 VLOG(1) << "Denied unauthorized request for raw headers";
2355 load_flags
&= ~net::LOAD_REPORT_RAW_HEADERS
;
2361 } // namespace content