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.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 "content/browser/appcache/appcache_interceptor.h"
28 #include "content/browser/appcache/chrome_appcache_service.h"
29 #include "content/browser/cert_store_impl.h"
30 #include "content/browser/child_process_security_policy_impl.h"
31 #include "content/browser/download/download_resource_handler.h"
32 #include "content/browser/download/save_file_manager.h"
33 #include "content/browser/download/save_file_resource_handler.h"
34 #include "content/browser/fileapi/chrome_blob_storage_context.h"
35 #include "content/browser/frame_host/navigation_request_info.h"
36 #include "content/browser/frame_host/navigator.h"
37 #include "content/browser/loader/async_resource_handler.h"
38 #include "content/browser/loader/buffered_resource_handler.h"
39 #include "content/browser/loader/cross_site_resource_handler.h"
40 #include "content/browser/loader/detachable_resource_handler.h"
41 #include "content/browser/loader/navigation_resource_handler.h"
42 #include "content/browser/loader/navigation_url_loader_impl_core.h"
43 #include "content/browser/loader/power_save_block_resource_throttle.h"
44 #include "content/browser/loader/redirect_to_file_resource_handler.h"
45 #include "content/browser/loader/resource_message_filter.h"
46 #include "content/browser/loader/resource_request_info_impl.h"
47 #include "content/browser/loader/stream_resource_handler.h"
48 #include "content/browser/loader/sync_resource_handler.h"
49 #include "content/browser/loader/throttling_resource_handler.h"
50 #include "content/browser/loader/upload_data_stream_builder.h"
51 #include "content/browser/renderer_host/render_view_host_delegate.h"
52 #include "content/browser/renderer_host/render_view_host_impl.h"
53 #include "content/browser/resource_context_impl.h"
54 #include "content/browser/service_worker/service_worker_request_handler.h"
55 #include "content/browser/streams/stream.h"
56 #include "content/browser/streams/stream_context.h"
57 #include "content/browser/streams/stream_registry.h"
58 #include "content/browser/web_contents/web_contents_impl.h"
59 #include "content/common/appcache_interfaces.h"
60 #include "content/common/navigation_params.h"
61 #include "content/common/resource_messages.h"
62 #include "content/common/ssl_status_serialization.h"
63 #include "content/common/view_messages.h"
64 #include "content/public/browser/browser_thread.h"
65 #include "content/public/browser/content_browser_client.h"
66 #include "content/public/browser/download_manager.h"
67 #include "content/public/browser/download_url_parameters.h"
68 #include "content/public/browser/global_request_id.h"
69 #include "content/public/browser/plugin_service.h"
70 #include "content/public/browser/resource_dispatcher_host_delegate.h"
71 #include "content/public/browser/resource_request_details.h"
72 #include "content/public/browser/resource_throttle.h"
73 #include "content/public/browser/stream_handle.h"
74 #include "content/public/browser/stream_info.h"
75 #include "content/public/browser/user_metrics.h"
76 #include "content/public/common/content_switches.h"
77 #include "content/public/common/process_type.h"
78 #include "ipc/ipc_message_macros.h"
79 #include "ipc/ipc_message_start.h"
80 #include "net/base/auth.h"
81 #include "net/base/load_flags.h"
82 #include "net/base/mime_util.h"
83 #include "net/base/net_errors.h"
84 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
85 #include "net/base/request_priority.h"
86 #include "net/base/upload_data_stream.h"
87 #include "net/cert/cert_status_flags.h"
88 #include "net/cookies/cookie_monster.h"
89 #include "net/http/http_response_headers.h"
90 #include "net/http/http_response_info.h"
91 #include "net/ssl/ssl_cert_request_info.h"
92 #include "net/url_request/url_request.h"
93 #include "net/url_request/url_request_context.h"
94 #include "net/url_request/url_request_job_factory.h"
95 #include "storage/browser/blob/blob_data_handle.h"
96 #include "storage/browser/blob/blob_storage_context.h"
97 #include "storage/browser/blob/blob_url_request_job_factory.h"
98 #include "storage/browser/blob/shareable_file_reference.h"
99 #include "storage/browser/fileapi/file_permission_policy.h"
100 #include "storage/browser/fileapi/file_system_context.h"
101 #include "url/url_constants.h"
104 using base::TimeDelta
;
105 using base::TimeTicks
;
106 using storage::ShareableFileReference
;
108 // ----------------------------------------------------------------------------
114 static ResourceDispatcherHostImpl
* g_resource_dispatcher_host
;
116 // The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates
117 const int kUpdateLoadStatesIntervalMsec
= 100;
119 // Maximum byte "cost" of all the outstanding requests for a renderer.
120 // See delcaration of |max_outstanding_requests_cost_per_process_| for details.
121 // This bound is 25MB, which allows for around 6000 outstanding requests.
122 const int kMaxOutstandingRequestsCostPerProcess
= 26214400;
124 // The number of milliseconds after noting a user gesture that we will
125 // tag newly-created URLRequest objects with the
126 // net::LOAD_MAYBE_USER_GESTURE load flag. This is a fairly arbitrary
127 // guess at how long to expect direct impact from a user gesture, but
128 // this should be OK as the load flag is a best-effort thing only,
129 // rather than being intended as fully accurate.
130 const int kUserGestureWindowMs
= 3500;
132 // Ratio of |max_num_in_flight_requests_| that any one renderer is allowed to
133 // use. Arbitrarily chosen.
134 const double kMaxRequestsPerProcessRatio
= 0.45;
136 // TODO(jkarlin): The value is high to reduce the chance of the detachable
137 // request timing out, forcing a blocked second request to open a new connection
138 // and start over. Reduce this value once we have a better idea of what it
139 // should be and once we stop blocking multiple simultaneous requests for the
140 // same resource (see bugs 46104 and 31014).
141 const int kDefaultDetachableCancelDelayMs
= 30000;
143 enum SHA1HistogramTypes
{
144 // SHA-1 is not present in the certificate chain.
145 SHA1_NOT_PRESENT
= 0,
146 // SHA-1 is present in the certificate chain, and the leaf expires on or
147 // after January 1, 2017.
148 SHA1_EXPIRES_AFTER_JANUARY_2017
= 1,
149 // SHA-1 is present in the certificate chain, and the leaf expires on or
150 // after June 1, 2016.
151 SHA1_EXPIRES_AFTER_JUNE_2016
= 2,
152 // SHA-1 is present in the certificate chain, and the leaf expires on or
153 // after January 1, 2016.
154 SHA1_EXPIRES_AFTER_JANUARY_2016
= 3,
155 // SHA-1 is present in the certificate chain, but the leaf expires before
158 // Always keep this at the end.
159 SHA1_HISTOGRAM_TYPES_MAX
,
162 void RecordCertificateHistograms(const net::SSLInfo
& ssl_info
,
163 ResourceType resource_type
) {
164 // The internal representation of the dates for UI treatment of SHA-1.
165 // See http://crbug.com/401365 for details
166 static const int64_t kJanuary2017
= INT64_C(13127702400000000);
167 static const int64_t kJune2016
= INT64_C(13109213000000000);
168 static const int64_t kJanuary2016
= INT64_C(13096080000000000);
170 SHA1HistogramTypes sha1_histogram
= SHA1_NOT_PRESENT
;
171 if (ssl_info
.cert_status
& net::CERT_STATUS_SHA1_SIGNATURE_PRESENT
) {
172 DCHECK(ssl_info
.cert
.get());
173 if (ssl_info
.cert
->valid_expiry() >=
174 base::Time::FromInternalValue(kJanuary2017
)) {
175 sha1_histogram
= SHA1_EXPIRES_AFTER_JANUARY_2017
;
176 } else if (ssl_info
.cert
->valid_expiry() >=
177 base::Time::FromInternalValue(kJune2016
)) {
178 sha1_histogram
= SHA1_EXPIRES_AFTER_JUNE_2016
;
179 } else if (ssl_info
.cert
->valid_expiry() >=
180 base::Time::FromInternalValue(kJanuary2016
)) {
181 sha1_histogram
= SHA1_EXPIRES_AFTER_JANUARY_2016
;
183 sha1_histogram
= SHA1_PRESENT
;
186 if (resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
187 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.MainFrame",
189 SHA1_HISTOGRAM_TYPES_MAX
);
191 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.Subresource",
193 SHA1_HISTOGRAM_TYPES_MAX
);
197 bool IsDetachableResourceType(ResourceType type
) {
199 case RESOURCE_TYPE_PREFETCH
:
200 case RESOURCE_TYPE_PING
:
207 // Aborts a request before an URLRequest has actually been created.
208 void AbortRequestBeforeItStarts(ResourceMessageFilter
* filter
,
209 IPC::Message
* sync_result
,
212 SyncLoadResult result
;
213 result
.error_code
= net::ERR_ABORTED
;
214 ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result
, result
);
215 filter
->Send(sync_result
);
217 // Tell the renderer that this request was disallowed.
218 ResourceMsg_RequestCompleteData request_complete_data
;
219 request_complete_data
.error_code
= net::ERR_ABORTED
;
220 request_complete_data
.was_ignored_by_handler
= false;
221 request_complete_data
.exists_in_cache
= false;
222 // No security info needed, connection not established.
223 request_complete_data
.completion_time
= base::TimeTicks();
224 request_complete_data
.encoded_data_length
= 0;
225 filter
->Send(new ResourceMsg_RequestComplete(
226 request_id
, request_complete_data
));
230 void SetReferrerForRequest(net::URLRequest
* request
, const Referrer
& referrer
) {
231 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
232 if (!referrer
.url
.is_valid() ||
233 command_line
->HasSwitch(switches::kNoReferrers
)) {
234 request
->SetReferrer(std::string());
236 request
->SetReferrer(referrer
.url
.spec());
239 net::URLRequest::ReferrerPolicy net_referrer_policy
=
240 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
241 switch (referrer
.policy
) {
242 case blink::WebReferrerPolicyAlways
:
243 case blink::WebReferrerPolicyNever
:
244 case blink::WebReferrerPolicyOrigin
:
245 net_referrer_policy
= net::URLRequest::NEVER_CLEAR_REFERRER
;
247 case blink::WebReferrerPolicyNoReferrerWhenDowngrade
:
248 net_referrer_policy
=
249 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
251 case blink::WebReferrerPolicyOriginWhenCrossOrigin
:
252 net_referrer_policy
=
253 net::URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
;
255 case blink::WebReferrerPolicyDefault
:
257 net_referrer_policy
=
258 command_line
->HasSwitch(switches::kReducedReferrerGranularity
)
260 REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
262 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
265 request
->set_referrer_policy(net_referrer_policy
);
268 // Consults the RendererSecurity policy to determine whether the
269 // ResourceDispatcherHostImpl should service this request. A request might be
270 // disallowed if the renderer is not authorized to retrieve the request URL or
271 // if the renderer is attempting to upload an unauthorized file.
272 bool ShouldServiceRequest(int process_type
,
274 const ResourceHostMsg_Request
& request_data
,
275 storage::FileSystemContext
* file_system_context
) {
276 if (process_type
== PROCESS_TYPE_PLUGIN
)
279 ChildProcessSecurityPolicyImpl
* policy
=
280 ChildProcessSecurityPolicyImpl::GetInstance();
282 // Check if the renderer is permitted to request the requested URL.
283 if (!policy
->CanRequestURL(child_id
, request_data
.url
)) {
284 VLOG(1) << "Denied unauthorized request for "
285 << request_data
.url
.possibly_invalid_spec();
289 // Check if the renderer is permitted to upload the requested files.
290 if (request_data
.request_body
.get()) {
291 const std::vector
<ResourceRequestBody::Element
>* uploads
=
292 request_data
.request_body
->elements();
293 std::vector
<ResourceRequestBody::Element
>::const_iterator iter
;
294 for (iter
= uploads
->begin(); iter
!= uploads
->end(); ++iter
) {
295 if (iter
->type() == ResourceRequestBody::Element::TYPE_FILE
&&
296 !policy
->CanReadFile(child_id
, iter
->path())) {
297 NOTREACHED() << "Denied unauthorized upload of "
298 << iter
->path().value();
301 if (iter
->type() == ResourceRequestBody::Element::TYPE_FILE_FILESYSTEM
) {
302 storage::FileSystemURL url
=
303 file_system_context
->CrackURL(iter
->filesystem_url());
304 if (!policy
->CanReadFileSystemFile(child_id
, url
)) {
305 NOTREACHED() << "Denied unauthorized upload of "
306 << iter
->filesystem_url().spec();
316 void RemoveDownloadFileFromChildSecurityPolicy(int child_id
,
317 const base::FilePath
& path
) {
318 ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile(
322 DownloadInterruptReason
CallbackAndReturn(
323 const DownloadUrlParameters::OnStartedCallback
& started_cb
,
324 DownloadInterruptReason interrupt_reason
) {
325 if (started_cb
.is_null())
326 return interrupt_reason
;
327 BrowserThread::PostTask(
331 started_cb
, static_cast<DownloadItem
*>(NULL
), interrupt_reason
));
333 return interrupt_reason
;
336 int GetCertID(net::URLRequest
* request
, int child_id
) {
337 if (request
->ssl_info().cert
.get()) {
338 return CertStore::GetInstance()->StoreCert(request
->ssl_info().cert
.get(),
344 void NotifyRedirectOnUI(int render_process_id
,
345 int render_frame_host
,
346 scoped_ptr
<ResourceRedirectDetails
> details
) {
347 RenderFrameHostImpl
* host
=
348 RenderFrameHostImpl::FromID(render_process_id
, render_frame_host
);
349 WebContentsImpl
* web_contents
=
350 static_cast<WebContentsImpl
*>(WebContents::FromRenderFrameHost(host
));
353 web_contents
->DidGetRedirectForResourceRequest(host
, *details
.get());
356 void NotifyResponseOnUI(int render_process_id
,
357 int render_frame_host
,
358 scoped_ptr
<ResourceRequestDetails
> details
) {
359 RenderFrameHostImpl
* host
=
360 RenderFrameHostImpl::FromID(render_process_id
, render_frame_host
);
361 WebContentsImpl
* web_contents
=
362 static_cast<WebContentsImpl
*>(WebContents::FromRenderFrameHost(host
));
365 web_contents
->DidGetResourceResponseStart(*details
.get());
369 const net::SignedCertificateTimestampAndStatus
& sct_status
) {
370 return sct_status
.status
== net::ct::SCT_STATUS_OK
;
373 storage::BlobStorageContext
* GetBlobStorageContext(
374 ChromeBlobStorageContext
* blob_storage_context
) {
375 if (!blob_storage_context
)
377 return blob_storage_context
->context();
380 void AttachRequestBodyBlobDataHandles(
381 ResourceRequestBody
* body
,
382 storage::BlobStorageContext
* blob_context
) {
383 DCHECK(blob_context
);
384 for (size_t i
= 0; i
< body
->elements()->size(); ++i
) {
385 const ResourceRequestBody::Element
& element
= (*body
->elements())[i
];
386 if (element
.type() != ResourceRequestBody::Element::TYPE_BLOB
)
388 scoped_ptr
<storage::BlobDataHandle
> handle
=
389 blob_context
->GetBlobDataFromUUID(element
.blob_uuid());
393 // Ensure the blob and any attached shareable files survive until
394 // upload completion. The |body| takes ownership of |handle|.
395 const void* key
= handle
.get();
396 body
->SetUserData(key
, handle
.release());
401 // This method is called in the UI thread to send the timestamp of a resource
402 // request to the respective Navigator (for an UMA histogram).
403 void LogResourceRequestTimeOnUI(
404 base::TimeTicks timestamp
,
405 int render_process_id
,
408 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
409 RenderFrameHostImpl
* host
=
410 RenderFrameHostImpl::FromID(render_process_id
, render_frame_id
);
412 DCHECK(host
->frame_tree_node()->IsMainFrame());
413 host
->frame_tree_node()->navigator()->LogResourceRequestTime(
421 ResourceDispatcherHost
* ResourceDispatcherHost::Get() {
422 return g_resource_dispatcher_host
;
425 ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
426 : save_file_manager_(new SaveFileManager()),
429 num_in_flight_requests_(0),
430 max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()),
431 max_num_in_flight_requests_per_process_(
433 max_num_in_flight_requests_
* kMaxRequestsPerProcessRatio
)),
434 max_outstanding_requests_cost_per_process_(
435 kMaxOutstandingRequestsCostPerProcess
),
438 allow_cross_origin_auth_prompt_(false) {
439 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
440 DCHECK(!g_resource_dispatcher_host
);
441 g_resource_dispatcher_host
= this;
443 GetContentClient()->browser()->ResourceDispatcherHostCreated();
445 ANNOTATE_BENIGN_RACE(
446 &last_user_gesture_time_
,
447 "We don't care about the precise value, see http://crbug.com/92889");
449 BrowserThread::PostTask(BrowserThread::IO
,
451 base::Bind(&ResourceDispatcherHostImpl::OnInit
,
452 base::Unretained(this)));
454 update_load_states_timer_
.reset(
455 new base::RepeatingTimer
<ResourceDispatcherHostImpl
>());
458 ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() {
459 DCHECK(outstanding_requests_stats_map_
.empty());
460 DCHECK(g_resource_dispatcher_host
);
461 g_resource_dispatcher_host
= NULL
;
465 ResourceDispatcherHostImpl
* ResourceDispatcherHostImpl::Get() {
466 return g_resource_dispatcher_host
;
469 void ResourceDispatcherHostImpl::SetDelegate(
470 ResourceDispatcherHostDelegate
* delegate
) {
471 delegate_
= delegate
;
474 void ResourceDispatcherHostImpl::SetAllowCrossOriginAuthPrompt(bool value
) {
475 allow_cross_origin_auth_prompt_
= value
;
478 void ResourceDispatcherHostImpl::AddResourceContext(ResourceContext
* context
) {
479 active_resource_contexts_
.insert(context
);
482 void ResourceDispatcherHostImpl::RemoveResourceContext(
483 ResourceContext
* context
) {
484 CHECK(ContainsKey(active_resource_contexts_
, context
));
485 active_resource_contexts_
.erase(context
);
488 void ResourceDispatcherHostImpl::ResumeResponseDeferredAtStart(
489 const GlobalRequestID
& id
) {
490 ResourceLoader
* loader
= GetLoader(id
);
492 // The response we were meant to resume could have already been canceled.
493 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
494 if (info
->cross_site_handler())
495 info
->cross_site_handler()->ResumeResponseDeferredAtStart(id
.request_id
);
499 void ResourceDispatcherHostImpl::CancelRequestsForContext(
500 ResourceContext
* context
) {
501 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
504 CHECK(ContainsKey(active_resource_contexts_
, context
));
506 // Note that request cancellation has side effects. Therefore, we gather all
507 // the requests to cancel first, and then we start cancelling. We assert at
508 // the end that there are no more to cancel since the context is about to go
510 typedef std::vector
<linked_ptr
<ResourceLoader
>> LoaderList
;
511 LoaderList loaders_to_cancel
;
513 for (LoaderMap::iterator i
= pending_loaders_
.begin();
514 i
!= pending_loaders_
.end();) {
515 if (i
->second
->GetRequestInfo()->GetContext() == context
) {
516 loaders_to_cancel
.push_back(i
->second
);
517 IncrementOutstandingRequestsMemory(-1, *i
->second
->GetRequestInfo());
518 pending_loaders_
.erase(i
++);
524 for (BlockedLoadersMap::iterator i
= blocked_loaders_map_
.begin();
525 i
!= blocked_loaders_map_
.end();) {
526 BlockedLoadersList
* loaders
= i
->second
;
527 if (loaders
->empty()) {
528 // This can happen if BlockRequestsForRoute() has been called for a route,
529 // but we haven't blocked any matching requests yet.
533 ResourceRequestInfoImpl
* info
= loaders
->front()->GetRequestInfo();
534 if (info
->GetContext() == context
) {
535 blocked_loaders_map_
.erase(i
++);
536 for (BlockedLoadersList::const_iterator it
= loaders
->begin();
537 it
!= loaders
->end(); ++it
) {
538 linked_ptr
<ResourceLoader
> loader
= *it
;
539 info
= loader
->GetRequestInfo();
540 // We make the assumption that all requests on the list have the same
542 DCHECK_EQ(context
, info
->GetContext());
543 IncrementOutstandingRequestsMemory(-1, *info
);
544 loaders_to_cancel
.push_back(loader
);
553 for (LoaderList::iterator i
= loaders_to_cancel
.begin();
554 i
!= loaders_to_cancel
.end(); ++i
) {
555 // There is no strict requirement that this be the case, but currently
556 // downloads, streams, detachable requests, transferred requests, and
557 // browser-owned requests are the only requests that aren't cancelled when
558 // the associated processes go away. It may be OK for this invariant to
559 // change in the future, but if this assertion fires without the invariant
560 // changing, then it's indicative of a leak.
561 DCHECK((*i
)->GetRequestInfo()->IsDownload() ||
562 (*i
)->GetRequestInfo()->is_stream() ||
563 ((*i
)->GetRequestInfo()->detachable_handler() &&
564 (*i
)->GetRequestInfo()->detachable_handler()->is_detached()) ||
565 (*i
)->GetRequestInfo()->GetProcessType() == PROCESS_TYPE_BROWSER
||
566 (*i
)->is_transferring());
570 loaders_to_cancel
.clear();
572 // Validate that no more requests for this context were added.
573 for (LoaderMap::const_iterator i
= pending_loaders_
.begin();
574 i
!= pending_loaders_
.end(); ++i
) {
575 // http://crbug.com/90971
576 CHECK_NE(i
->second
->GetRequestInfo()->GetContext(), context
);
579 for (BlockedLoadersMap::const_iterator i
= blocked_loaders_map_
.begin();
580 i
!= blocked_loaders_map_
.end(); ++i
) {
581 BlockedLoadersList
* loaders
= i
->second
;
582 if (!loaders
->empty()) {
583 ResourceRequestInfoImpl
* info
= loaders
->front()->GetRequestInfo();
584 // http://crbug.com/90971
585 CHECK_NE(info
->GetContext(), context
);
590 DownloadInterruptReason
ResourceDispatcherHostImpl::BeginDownload(
591 scoped_ptr
<net::URLRequest
> request
,
592 const Referrer
& referrer
,
593 bool is_content_initiated
,
594 ResourceContext
* context
,
598 bool do_not_prompt_for_login
,
599 scoped_ptr
<DownloadSaveInfo
> save_info
,
601 const DownloadStartedCallback
& started_callback
) {
603 return CallbackAndReturn(started_callback
,
604 DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN
);
606 const GURL
& url
= request
->original_url();
608 // http://crbug.com/90971
610 base::strlcpy(url_buf
, url
.spec().c_str(), arraysize(url_buf
));
611 base::debug::Alias(url_buf
);
612 CHECK(ContainsKey(active_resource_contexts_
, context
));
614 SetReferrerForRequest(request
.get(), referrer
);
616 int extra_load_flags
= net::LOAD_IS_DOWNLOAD
;
618 // If there is upload data attached, only retrieve from cache because there
619 // is no current mechanism to prompt the user for their consent for a
620 // re-post. For GETs, try to retrieve data from the cache and skip
621 // validating the entry if present.
622 if (request
->get_upload() != NULL
)
623 extra_load_flags
|= net::LOAD_ONLY_FROM_CACHE
;
625 extra_load_flags
|= net::LOAD_PREFERRING_CACHE
;
627 extra_load_flags
|= net::LOAD_DISABLE_CACHE
;
629 request
->SetLoadFlags(request
->load_flags() | extra_load_flags
);
631 // We treat a download as a main frame load, and thus update the policy URL on
634 // TODO(davidben): Is this correct? If this came from a
635 // ViewHostMsg_DownloadUrl in a frame, should it have first-party URL set
637 request
->set_first_party_url_policy(
638 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
640 // Check if the renderer is permitted to request the requested URL.
641 if (!ChildProcessSecurityPolicyImpl::GetInstance()->
642 CanRequestURL(child_id
, url
)) {
643 VLOG(1) << "Denied unauthorized download request for "
644 << url
.possibly_invalid_spec();
645 return CallbackAndReturn(started_callback
,
646 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST
);
651 const net::URLRequestContext
* request_context
= context
->GetRequestContext();
652 if (!request_context
->job_factory()->IsHandledURL(url
)) {
653 VLOG(1) << "Download request for unsupported protocol: "
654 << url
.possibly_invalid_spec();
655 return CallbackAndReturn(started_callback
,
656 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST
);
659 ResourceRequestInfoImpl
* extra_info
=
660 CreateRequestInfo(child_id
, route_id
, true, context
);
661 extra_info
->set_do_not_prompt_for_login(do_not_prompt_for_login
);
662 extra_info
->AssociateWithRequest(request
.get()); // Request takes ownership.
664 if (request
->url().SchemeIs(url::kBlobScheme
)) {
665 ChromeBlobStorageContext
* blob_context
=
666 GetChromeBlobStorageContextForResourceContext(context
);
667 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
669 blob_context
->context()->GetBlobDataFromPublicURL(request
->url()));
672 // From this point forward, the |DownloadResourceHandler| is responsible for
673 // |started_callback|.
674 scoped_ptr
<ResourceHandler
> handler(
675 CreateResourceHandlerForDownload(request
.get(), is_content_initiated
,
676 true, download_id
, save_info
.Pass(),
679 BeginRequestInternal(request
.Pass(), handler
.Pass());
681 return DOWNLOAD_INTERRUPT_REASON_NONE
;
684 void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest(
685 net::URLRequest
* request
) {
686 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
688 ResourceLoader
* loader
= GetLoader(info
->GetGlobalRequestID());
690 loader
->ClearLoginDelegate();
694 void ResourceDispatcherHostImpl::Shutdown() {
695 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
696 BrowserThread::PostTask(BrowserThread::IO
,
698 base::Bind(&ResourceDispatcherHostImpl::OnShutdown
,
699 base::Unretained(this)));
702 scoped_ptr
<ResourceHandler
>
703 ResourceDispatcherHostImpl::CreateResourceHandlerForDownload(
704 net::URLRequest
* request
,
705 bool is_content_initiated
,
708 scoped_ptr
<DownloadSaveInfo
> save_info
,
709 const DownloadUrlParameters::OnStartedCallback
& started_cb
) {
710 scoped_ptr
<ResourceHandler
> handler(
711 new DownloadResourceHandler(id
, request
, started_cb
, save_info
.Pass()));
713 const ResourceRequestInfo
* request_info(
714 ResourceRequestInfo::ForRequest(request
));
716 ScopedVector
<ResourceThrottle
> throttles
;
717 delegate_
->DownloadStarting(
718 request
, request_info
->GetContext(), request_info
->GetChildID(),
719 request_info
->GetRouteID(), request_info
->GetRequestID(),
720 is_content_initiated
, must_download
, &throttles
);
721 if (!throttles
.empty()) {
723 new ThrottlingResourceHandler(
724 handler
.Pass(), request
, throttles
.Pass()));
727 return handler
.Pass();
730 scoped_ptr
<ResourceHandler
>
731 ResourceDispatcherHostImpl::MaybeInterceptAsStream(net::URLRequest
* request
,
732 ResourceResponse
* response
,
733 std::string
* payload
) {
734 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
735 const std::string
& mime_type
= response
->head
.mime_type
;
739 !delegate_
->ShouldInterceptResourceAsStream(request
,
743 return scoped_ptr
<ResourceHandler
>();
746 StreamContext
* stream_context
=
747 GetStreamContextForResourceContext(info
->GetContext());
749 scoped_ptr
<StreamResourceHandler
> handler(
750 new StreamResourceHandler(request
,
751 stream_context
->registry(),
754 info
->set_is_stream(true);
755 scoped_ptr
<StreamInfo
> stream_info(new StreamInfo
);
756 stream_info
->handle
= handler
->stream()->CreateHandle();
757 stream_info
->original_url
= request
->url();
758 stream_info
->mime_type
= mime_type
;
759 // Make a copy of the response headers so it is safe to pass across threads;
760 // the old handler (AsyncResourceHandler) may modify it in parallel via the
761 // ResourceDispatcherHostDelegate.
762 if (response
->head
.headers
.get()) {
763 stream_info
->response_headers
=
764 new net::HttpResponseHeaders(response
->head
.headers
->raw_headers());
766 delegate_
->OnStreamCreated(request
, stream_info
.Pass());
767 return handler
.Pass();
770 ResourceDispatcherHostLoginDelegate
*
771 ResourceDispatcherHostImpl::CreateLoginDelegate(
772 ResourceLoader
* loader
,
773 net::AuthChallengeInfo
* auth_info
) {
777 return delegate_
->CreateLoginDelegate(auth_info
, loader
->request());
780 bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader
* loader
,
785 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
787 if (!IsResourceTypeFrame(info
->GetResourceType()))
790 const net::URLRequestJobFactory
* job_factory
=
791 info
->GetContext()->GetRequestContext()->job_factory();
792 if (job_factory
->IsHandledURL(url
))
795 return delegate_
->HandleExternalProtocol(
796 url
, info
->GetChildID(), info
->GetRouteID());
799 void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader
* loader
) {
800 // Make sure we have the load state monitor running
801 if (!update_load_states_timer_
->IsRunning()) {
802 update_load_states_timer_
->Start(FROM_HERE
,
803 TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec
),
804 this, &ResourceDispatcherHostImpl::UpdateLoadStates
);
808 void ResourceDispatcherHostImpl::DidReceiveRedirect(ResourceLoader
* loader
,
809 const GURL
& new_url
) {
810 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
812 int render_process_id
, render_frame_host
;
813 if (!info
->GetAssociatedRenderFrame(&render_process_id
, &render_frame_host
))
816 // Notify the observers on the UI thread.
817 scoped_ptr
<ResourceRedirectDetails
> detail(new ResourceRedirectDetails(
819 GetCertID(loader
->request(), info
->GetChildID()),
821 BrowserThread::PostTask(
822 BrowserThread::UI
, FROM_HERE
,
825 render_process_id
, render_frame_host
, base::Passed(&detail
)));
828 void ResourceDispatcherHostImpl::DidReceiveResponse(ResourceLoader
* loader
) {
829 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
831 if (loader
->request()->was_fetched_via_proxy() &&
832 loader
->request()->was_fetched_via_spdy() &&
833 loader
->request()->url().SchemeIs(url::kHttpScheme
)) {
834 scheduler_
->OnReceivedSpdyProxiedHttpResponse(
835 info
->GetChildID(), info
->GetRouteID());
838 int render_process_id
, render_frame_host
;
839 if (!info
->GetAssociatedRenderFrame(&render_process_id
, &render_frame_host
))
842 // Notify the observers on the UI thread.
843 scoped_ptr
<ResourceRequestDetails
> detail(new ResourceRequestDetails(
845 GetCertID(loader
->request(), info
->GetChildID())));
846 BrowserThread::PostTask(
847 BrowserThread::UI
, FROM_HERE
,
850 render_process_id
, render_frame_host
, base::Passed(&detail
)));
853 void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader
* loader
) {
854 ResourceRequestInfo
* info
= loader
->GetRequestInfo();
856 // Record final result of all resource loads.
857 if (info
->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME
) {
858 // This enumeration has "3" appended to its name to distinguish it from
860 UMA_HISTOGRAM_SPARSE_SLOWLY(
861 "Net.ErrorCodesForMainFrame3",
862 -loader
->request()->status().error());
864 if (loader
->request()->url().SchemeIsSecure()) {
865 if (loader
->request()->url().host() == "www.google.com") {
866 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2",
867 -loader
->request()->status().error());
870 int num_valid_scts
= std::count_if(
871 loader
->request()->ssl_info().signed_certificate_timestamps
.begin(),
872 loader
->request()->ssl_info().signed_certificate_timestamps
.end(),
874 UMA_HISTOGRAM_COUNTS_100(
875 "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts
);
878 if (info
->GetResourceType() == RESOURCE_TYPE_IMAGE
) {
879 UMA_HISTOGRAM_SPARSE_SLOWLY(
880 "Net.ErrorCodesForImages",
881 -loader
->request()->status().error());
883 // This enumeration has "2" appended to distinguish it from older versions.
884 UMA_HISTOGRAM_SPARSE_SLOWLY(
885 "Net.ErrorCodesForSubresources2",
886 -loader
->request()->status().error());
889 if (loader
->request()->url().SchemeIsSecure()) {
890 RecordCertificateHistograms(loader
->request()->ssl_info(),
891 info
->GetResourceType());
895 delegate_
->RequestComplete(loader
->request());
897 // Destroy the ResourceLoader.
898 RemovePendingRequest(info
->GetChildID(), info
->GetRequestID());
901 void ResourceDispatcherHostImpl::OnInit() {
902 scheduler_
.reset(new ResourceScheduler
);
905 void ResourceDispatcherHostImpl::OnShutdown() {
906 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
909 pending_loaders_
.clear();
911 // Make sure we shutdown the timer now, otherwise by the time our destructor
912 // runs if the timer is still running the Task is deleted twice (once by
913 // the MessageLoop and the second time by RepeatingTimer).
914 update_load_states_timer_
.reset();
916 // Clear blocked requests if any left.
917 // Note that we have to do this in 2 passes as we cannot call
918 // CancelBlockedRequestsForRoute while iterating over
919 // blocked_loaders_map_, as it modifies it.
920 std::set
<GlobalRoutingID
> ids
;
921 for (BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.begin();
922 iter
!= blocked_loaders_map_
.end(); ++iter
) {
923 std::pair
<std::set
<GlobalRoutingID
>::iterator
, bool> result
=
924 ids
.insert(iter
->first
);
925 // We should not have duplicates.
926 DCHECK(result
.second
);
928 for (std::set
<GlobalRoutingID
>::const_iterator iter
= ids
.begin();
929 iter
!= ids
.end(); ++iter
) {
930 CancelBlockedRequestsForRoute(iter
->child_id
, iter
->route_id
);
936 bool ResourceDispatcherHostImpl::OnMessageReceived(
937 const IPC::Message
& message
,
938 ResourceMessageFilter
* filter
) {
941 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcherHostImpl
, message
)
942 IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource
, OnRequestResource
)
943 IPC_MESSAGE_HANDLER_DELAY_REPLY(ResourceHostMsg_SyncLoad
, OnSyncLoad
)
944 IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile
,
945 OnReleaseDownloadedFile
)
946 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataDownloaded_ACK
, OnDataDownloadedACK
)
947 IPC_MESSAGE_HANDLER(ResourceHostMsg_UploadProgress_ACK
, OnUploadProgressACK
)
948 IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest
, OnCancelRequest
)
949 IPC_MESSAGE_UNHANDLED(handled
= false)
950 IPC_END_MESSAGE_MAP()
952 if (!handled
&& IPC_MESSAGE_ID_CLASS(message
.type()) == ResourceMsgStart
) {
953 PickleIterator
iter(message
);
955 bool ok
= iter
.ReadInt(&request_id
);
957 GlobalRequestID
id(filter_
->child_id(), request_id
);
958 DelegateMap::iterator it
= delegate_map_
.find(id
);
959 if (it
!= delegate_map_
.end()) {
960 ObserverList
<ResourceMessageDelegate
>::Iterator
del_it(*it
->second
);
961 ResourceMessageDelegate
* delegate
;
962 while (!handled
&& (delegate
= del_it
.GetNext()) != NULL
) {
963 handled
= delegate
->OnMessageReceived(message
);
967 // As the unhandled resource message effectively has no consumer, mark it as
968 // handled to prevent needless propagation through the filter pipeline.
976 void ResourceDispatcherHostImpl::OnRequestResource(
979 const ResourceHostMsg_Request
& request_data
) {
980 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
981 tracked_objects::ScopedTracker
tracking_profile(
982 FROM_HERE_WITH_EXPLICIT_FUNCTION(
983 "456331 ResourceDispatcherHostImpl::OnRequestResource"));
984 // When logging time-to-network only care about main frame and non-transfer
986 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
&&
987 request_data
.transferred_request_request_id
== -1 &&
988 !base::CommandLine::ForCurrentProcess()->HasSwitch(
989 switches::kEnableBrowserSideNavigation
)) {
990 BrowserThread::PostTask(
993 base::Bind(&LogResourceRequestTimeOnUI
,
996 request_data
.render_frame_id
,
999 BeginRequest(request_id
, request_data
, NULL
, routing_id
);
1002 // Begins a resource request with the given params on behalf of the specified
1003 // child process. Responses will be dispatched through the given receiver. The
1004 // process ID is used to lookup WebContentsImpl from routing_id's in the case of
1005 // a request from a renderer. request_context is the cookie/cache context to be
1006 // used for this request.
1008 // If sync_result is non-null, then a SyncLoad reply will be generated, else
1009 // a normal asynchronous set of response messages will be generated.
1010 void ResourceDispatcherHostImpl::OnSyncLoad(
1012 const ResourceHostMsg_Request
& request_data
,
1013 IPC::Message
* sync_result
) {
1014 BeginRequest(request_id
, request_data
, sync_result
,
1015 sync_result
->routing_id());
1018 void ResourceDispatcherHostImpl::UpdateRequestForTransfer(
1022 const ResourceHostMsg_Request
& request_data
,
1023 const linked_ptr
<ResourceLoader
>& loader
) {
1024 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
1025 GlobalRoutingID
old_routing_id(
1026 request_data
.transferred_request_child_id
, info
->GetRouteID());
1027 GlobalRequestID
old_request_id(request_data
.transferred_request_child_id
,
1028 request_data
.transferred_request_request_id
);
1029 GlobalRoutingID
new_routing_id(child_id
, route_id
);
1030 GlobalRequestID
new_request_id(child_id
, request_id
);
1032 // Clear out data that depends on |info| before updating it.
1033 // We always need to move the memory stats to the new process. In contrast,
1034 // stats.num_requests is only tracked for some requests (those that require
1035 // file descriptors for their shared memory buffer).
1036 IncrementOutstandingRequestsMemory(-1, *info
);
1037 bool should_update_count
= info
->counted_as_in_flight_request();
1038 if (should_update_count
)
1039 IncrementOutstandingRequestsCount(-1, info
);
1040 pending_loaders_
.erase(old_request_id
);
1042 // ResourceHandlers should always get state related to the request from the
1043 // ResourceRequestInfo rather than caching it locally. This lets us update
1044 // the info object when a transfer occurs.
1045 info
->UpdateForTransfer(child_id
, route_id
, request_data
.origin_pid
,
1046 request_id
, request_data
.parent_render_frame_id
,
1047 filter_
->GetWeakPtr());
1049 // Update maps that used the old IDs, if necessary. Some transfers in tests
1050 // do not actually use a different ID, so not all maps need to be updated.
1051 pending_loaders_
[new_request_id
] = loader
;
1052 IncrementOutstandingRequestsMemory(1, *info
);
1053 if (should_update_count
)
1054 IncrementOutstandingRequestsCount(1, info
);
1055 if (old_routing_id
!= new_routing_id
) {
1056 if (blocked_loaders_map_
.find(old_routing_id
) !=
1057 blocked_loaders_map_
.end()) {
1058 blocked_loaders_map_
[new_routing_id
] =
1059 blocked_loaders_map_
[old_routing_id
];
1060 blocked_loaders_map_
.erase(old_routing_id
);
1063 if (old_request_id
!= new_request_id
) {
1064 DelegateMap::iterator it
= delegate_map_
.find(old_request_id
);
1065 if (it
!= delegate_map_
.end()) {
1066 // Tell each delegate that the request ID has changed.
1067 ObserverList
<ResourceMessageDelegate
>::Iterator
del_it(*it
->second
);
1068 ResourceMessageDelegate
* delegate
;
1069 while ((delegate
= del_it
.GetNext()) != NULL
) {
1070 delegate
->set_request_id(new_request_id
);
1072 // Now store the observer list under the new request ID.
1073 delegate_map_
[new_request_id
] = delegate_map_
[old_request_id
];
1074 delegate_map_
.erase(old_request_id
);
1078 AppCacheInterceptor::CompleteCrossSiteTransfer(
1081 request_data
.appcache_host_id
);
1083 ServiceWorkerRequestHandler
* handler
=
1084 ServiceWorkerRequestHandler::GetHandler(loader
->request());
1086 handler
->CompleteCrossSiteTransfer(
1087 child_id
, request_data
.service_worker_provider_id
);
1090 // We should have a CrossSiteResourceHandler to finish the transfer.
1091 DCHECK(info
->cross_site_handler());
1094 void ResourceDispatcherHostImpl::BeginRequest(
1096 const ResourceHostMsg_Request
& request_data
,
1097 IPC::Message
* sync_result
, // only valid for sync
1099 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1100 tracked_objects::ScopedTracker
tracking_profile1(
1101 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1102 "456331 ResourceDispatcherHostImpl::BeginRequest1"));
1103 int process_type
= filter_
->process_type();
1104 int child_id
= filter_
->child_id();
1106 // Reject invalid priority.
1107 if (request_data
.priority
< net::MINIMUM_PRIORITY
||
1108 request_data
.priority
> net::MAXIMUM_PRIORITY
) {
1109 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1110 filter_
->BadMessageReceived();
1114 // If we crash here, figure out what URL the renderer was requesting.
1115 // http://crbug.com/91398
1117 base::strlcpy(url_buf
, request_data
.url
.spec().c_str(), arraysize(url_buf
));
1118 base::debug::Alias(url_buf
);
1120 // If the request that's coming in is being transferred from another process,
1121 // we want to reuse and resume the old loader rather than start a new one.
1123 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is
1125 tracked_objects::ScopedTracker
tracking_profile2(
1126 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1127 "456331 ResourceDispatcherHostImpl::BeginRequest2"));
1128 LoaderMap::iterator it
= pending_loaders_
.find(
1129 GlobalRequestID(request_data
.transferred_request_child_id
,
1130 request_data
.transferred_request_request_id
));
1131 if (it
!= pending_loaders_
.end()) {
1132 // If the request is transferring to a new process, we can update our
1133 // state and let it resume with its existing ResourceHandlers.
1134 if (it
->second
->is_transferring()) {
1135 linked_ptr
<ResourceLoader
> deferred_loader
= it
->second
;
1136 UpdateRequestForTransfer(child_id
, route_id
, request_id
,
1137 request_data
, deferred_loader
);
1139 deferred_loader
->CompleteTransfer();
1141 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1142 filter_
->BadMessageReceived();
1148 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1149 tracked_objects::ScopedTracker
tracking_profile3(
1150 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1151 "456331 ResourceDispatcherHostImpl::BeginRequest3"));
1152 ResourceContext
* resource_context
= NULL
;
1153 net::URLRequestContext
* request_context
= NULL
;
1154 filter_
->GetContexts(request_data
, &resource_context
, &request_context
);
1155 // http://crbug.com/90971
1156 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1159 !ShouldServiceRequest(process_type
, child_id
, request_data
,
1160 filter_
->file_system_context())) {
1161 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1165 // Allow the observer to block/handle the request.
1166 if (delegate_
&& !delegate_
->ShouldBeginRequest(request_data
.method
,
1168 request_data
.resource_type
,
1169 resource_context
)) {
1170 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1174 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1175 tracked_objects::ScopedTracker
tracking_profile4(
1176 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1177 "456331 ResourceDispatcherHostImpl::BeginRequest4"));
1178 // Construct the request.
1179 net::CookieStore
* cookie_store
=
1180 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1182 scoped_ptr
<net::URLRequest
> new_request
;
1183 new_request
= request_context
->CreateRequest(
1184 request_data
.url
, request_data
.priority
, NULL
, cookie_store
);
1186 new_request
->set_method(request_data
.method
);
1187 new_request
->set_first_party_for_cookies(
1188 request_data
.first_party_for_cookies
);
1190 // If the request is a MAIN_FRAME request, the first-party URL gets updated on
1192 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
1193 new_request
->set_first_party_url_policy(
1194 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1197 const Referrer
referrer(request_data
.referrer
, request_data
.referrer_policy
);
1198 SetReferrerForRequest(new_request
.get(), referrer
);
1200 net::HttpRequestHeaders headers
;
1201 headers
.AddHeadersFromString(request_data
.headers
);
1202 new_request
->SetExtraRequestHeaders(headers
);
1204 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1205 tracked_objects::ScopedTracker
tracking_profile5(
1206 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1207 "456331 ResourceDispatcherHostImpl::BeginRequest5"));
1208 storage::BlobStorageContext
* blob_context
=
1209 GetBlobStorageContext(filter_
->blob_storage_context());
1210 // Resolve elements from request_body and prepare upload data.
1211 if (request_data
.request_body
.get()) {
1212 // |blob_context| could be null when the request is from the plugins because
1213 // ResourceMessageFilters created in PluginProcessHost don't have the blob
1216 // Attaches the BlobDataHandles to request_body not to free the blobs and
1217 // any attached shareable files until upload completion. These data will
1218 // be used in UploadDataStream and ServiceWorkerURLRequestJob.
1219 AttachRequestBodyBlobDataHandles(
1220 request_data
.request_body
.get(),
1223 new_request
->set_upload(UploadDataStreamBuilder::Build(
1224 request_data
.request_body
.get(),
1226 filter_
->file_system_context(),
1227 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1231 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1232 tracked_objects::ScopedTracker
tracking_profile6(
1233 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1234 "456331 ResourceDispatcherHostImpl::BeginRequest6"));
1235 bool allow_download
= request_data
.allow_download
&&
1236 IsResourceTypeFrame(request_data
.resource_type
);
1237 bool do_not_prompt_for_login
= request_data
.do_not_prompt_for_login
;
1238 bool is_sync_load
= sync_result
!= NULL
;
1240 BuildLoadFlagsForRequest(request_data
, child_id
, is_sync_load
);
1241 if (request_data
.resource_type
== RESOURCE_TYPE_PREFETCH
||
1242 request_data
.resource_type
== RESOURCE_TYPE_FAVICON
) {
1243 do_not_prompt_for_login
= true;
1245 if (request_data
.resource_type
== RESOURCE_TYPE_IMAGE
&&
1246 HTTP_AUTH_RELATION_BLOCKED_CROSS
==
1247 HttpAuthRelationTypeOf(request_data
.url
,
1248 request_data
.first_party_for_cookies
)) {
1249 // Prevent third-party image content from prompting for login, as this
1250 // is often a scam to extract credentials for another domain from the user.
1251 // Only block image loads, as the attack applies largely to the "src"
1252 // property of the <img> tag. It is common for web properties to allow
1253 // untrusted values for <img src>; this is considered a fair thing for an
1254 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
1255 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
1256 // would be considered vulnerable in and of itself.
1257 do_not_prompt_for_login
= true;
1258 load_flags
|= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY
;
1261 // Sync loads should have maximum priority and should be the only
1262 // requets that have the ignore limits flag set.
1264 DCHECK_EQ(request_data
.priority
, net::MAXIMUM_PRIORITY
);
1265 DCHECK_NE(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1267 DCHECK_EQ(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1269 new_request
->SetLoadFlags(load_flags
);
1271 // Make extra info and read footer (contains request ID).
1272 ResourceRequestInfoImpl
* extra_info
=
1273 new ResourceRequestInfoImpl(
1277 request_data
.origin_pid
,
1279 request_data
.render_frame_id
,
1280 request_data
.is_main_frame
,
1281 request_data
.parent_is_main_frame
,
1282 request_data
.parent_render_frame_id
,
1283 request_data
.resource_type
,
1284 request_data
.transition_type
,
1285 request_data
.should_replace_current_entry
,
1286 false, // is download
1289 request_data
.has_user_gesture
,
1290 request_data
.enable_load_timing
,
1291 request_data
.enable_upload_progress
,
1292 do_not_prompt_for_login
,
1293 request_data
.referrer_policy
,
1294 request_data
.visiblity_state
,
1296 filter_
->GetWeakPtr(),
1298 // Request takes ownership.
1299 extra_info
->AssociateWithRequest(new_request
.get());
1301 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
1302 // Hang on to a reference to ensure the blob is not released prior
1303 // to the job being started.
1304 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1306 filter_
->blob_storage_context()->context()->GetBlobDataFromPublicURL(
1307 new_request
->url()));
1310 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1311 tracked_objects::ScopedTracker
tracking_profile7(
1312 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1313 "456331 ResourceDispatcherHostImpl::BeginRequest7"));
1314 // Initialize the service worker handler for the request. We don't use
1315 // ServiceWorker for synchronous loads to avoid renderer deadlocks.
1316 ServiceWorkerRequestHandler::InitializeHandler(
1318 filter_
->service_worker_context(),
1321 request_data
.service_worker_provider_id
,
1322 request_data
.skip_service_worker
|| is_sync_load
,
1323 request_data
.fetch_request_mode
,
1324 request_data
.fetch_credentials_mode
,
1325 request_data
.resource_type
,
1326 request_data
.fetch_request_context_type
,
1327 request_data
.fetch_frame_type
,
1328 request_data
.request_body
);
1330 // Have the appcache associate its extra info with the request.
1331 AppCacheInterceptor::SetExtraRequestInfo(
1332 new_request
.get(), filter_
->appcache_service(), child_id
,
1333 request_data
.appcache_host_id
, request_data
.resource_type
,
1334 request_data
.should_reset_appcache
);
1336 scoped_ptr
<ResourceHandler
> handler(
1337 CreateResourceHandler(
1339 request_data
, sync_result
, route_id
, process_type
, child_id
,
1343 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
1346 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::CreateResourceHandler(
1347 net::URLRequest
* request
,
1348 const ResourceHostMsg_Request
& request_data
,
1349 IPC::Message
* sync_result
,
1353 ResourceContext
* resource_context
) {
1354 // Construct the IPC resource handler.
1355 scoped_ptr
<ResourceHandler
> handler
;
1357 // download_to_file is not supported for synchronous requests.
1358 if (request_data
.download_to_file
) {
1359 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1360 filter_
->BadMessageReceived();
1361 return scoped_ptr
<ResourceHandler
>();
1364 handler
.reset(new SyncResourceHandler(request
, sync_result
, this));
1366 handler
.reset(new AsyncResourceHandler(request
, this));
1368 // The RedirectToFileResourceHandler depends on being next in the chain.
1369 if (request_data
.download_to_file
) {
1371 new RedirectToFileResourceHandler(handler
.Pass(), request
));
1375 // Prefetches and <a ping> requests outlive their child process.
1376 if (!sync_result
&& IsDetachableResourceType(request_data
.resource_type
)) {
1377 handler
.reset(new DetachableResourceHandler(
1379 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs
),
1383 // PlzNavigate: If using --enable-browser-side-navigation, the
1384 // CrossSiteResourceHandler is not needed. This codepath is not used for the
1385 // actual navigation request, but only the subsequent blob URL load. This does
1386 // not require request transfers.
1387 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1388 switches::kEnableBrowserSideNavigation
)) {
1389 // Install a CrossSiteResourceHandler for all main frame requests. This will
1390 // check whether a transfer is required and, if so, pause for the UI thread
1391 // to drive the transfer.
1392 bool is_swappable_navigation
=
1393 request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
;
1394 // If we are using --site-per-process, install it for subframes as well.
1395 if (!is_swappable_navigation
&&
1396 base::CommandLine::ForCurrentProcess()->HasSwitch(
1397 switches::kSitePerProcess
)) {
1398 is_swappable_navigation
=
1399 request_data
.resource_type
== RESOURCE_TYPE_SUB_FRAME
;
1401 if (is_swappable_navigation
&& process_type
== PROCESS_TYPE_RENDERER
)
1402 handler
.reset(new CrossSiteResourceHandler(handler
.Pass(), request
));
1405 return AddStandardHandlers(request
, request_data
.resource_type
,
1406 resource_context
, filter_
->appcache_service(),
1407 child_id
, route_id
, handler
.Pass());
1410 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::AddStandardHandlers(
1411 net::URLRequest
* request
,
1412 ResourceType resource_type
,
1413 ResourceContext
* resource_context
,
1414 AppCacheService
* appcache_service
,
1417 scoped_ptr
<ResourceHandler
> handler
) {
1419 PluginService
* plugin_service
= nullptr;
1420 #if defined(ENABLE_PLUGINS)
1421 plugin_service
= PluginService::GetInstance();
1423 // Insert a buffered event handler before the actual one.
1425 new BufferedResourceHandler(
1426 handler
.Pass(), this, plugin_service
, request
));
1428 ScopedVector
<ResourceThrottle
> throttles
;
1430 delegate_
->RequestBeginning(request
,
1437 if (request
->has_upload()) {
1438 // Block power save while uploading data.
1439 throttles
.push_back(new PowerSaveBlockResourceThrottle());
1442 throttles
.push_back(
1443 scheduler_
->ScheduleRequest(child_id
, route_id
, request
).release());
1446 new ThrottlingResourceHandler(handler
.Pass(), request
, throttles
.Pass()));
1448 return handler
.Pass();
1451 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id
) {
1452 UnregisterDownloadedTempFile(filter_
->child_id(), request_id
);
1455 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id
) {
1456 // TODO(michaeln): maybe throttle DataDownloaded messages
1459 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1460 int child_id
, int request_id
, const base::FilePath
& file_path
) {
1461 scoped_refptr
<ShareableFileReference
> reference
=
1462 ShareableFileReference::Get(file_path
);
1463 DCHECK(reference
.get());
1465 registered_temp_files_
[child_id
][request_id
] = reference
;
1466 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1467 child_id
, reference
->path());
1469 // When the temp file is deleted, revoke permissions that the renderer has
1470 // to that file. This covers an edge case where the file is deleted and then
1471 // the same name is re-used for some other purpose, we don't want the old
1472 // renderer to still have access to it.
1474 // We do this when the file is deleted because the renderer can take a blob
1475 // reference to the temp file that outlives the url loaded that it was
1476 // loaded with to keep the file (and permissions) alive.
1477 reference
->AddFinalReleaseCallback(
1478 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy
,
1482 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1483 int child_id
, int request_id
) {
1484 DeletableFilesMap
& map
= registered_temp_files_
[child_id
];
1485 DeletableFilesMap::iterator found
= map
.find(request_id
);
1486 if (found
== map
.end())
1491 // Note that we don't remove the security bits here. This will be done
1492 // when all file refs are deleted (see RegisterDownloadedTempFile).
1495 bool ResourceDispatcherHostImpl::Send(IPC::Message
* message
) {
1500 void ResourceDispatcherHostImpl::OnUploadProgressACK(int request_id
) {
1501 ResourceLoader
* loader
= GetLoader(filter_
->child_id(), request_id
);
1503 loader
->OnUploadProgressACK();
1506 // Note that this cancel is subtly different from the other
1507 // CancelRequest methods in this file, which also tear down the loader.
1508 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id
) {
1509 int child_id
= filter_
->child_id();
1511 // When the old renderer dies, it sends a message to us to cancel its
1513 if (IsTransferredNavigation(GlobalRequestID(child_id
, request_id
)))
1516 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1518 // We probably want to remove this warning eventually, but I wanted to be
1519 // able to notice when this happens during initial development since it
1520 // should be rare and may indicate a bug.
1521 DVLOG(1) << "Canceling a request that wasn't found";
1525 loader
->CancelRequest(true);
1528 ResourceRequestInfoImpl
* ResourceDispatcherHostImpl::CreateRequestInfo(
1532 ResourceContext
* context
) {
1533 return new ResourceRequestInfoImpl(
1534 PROCESS_TYPE_RENDERER
,
1539 MSG_ROUTING_NONE
, // render_frame_id
1540 false, // is_main_frame
1541 false, // parent_is_main_frame
1542 -1, // parent_render_frame_id
1543 RESOURCE_TYPE_SUB_RESOURCE
,
1544 ui::PAGE_TRANSITION_LINK
,
1545 false, // should_replace_current_entry
1546 download
, // is_download
1548 download
, // allow_download
1549 false, // has_user_gesture
1550 false, // enable_load_timing
1551 false, // enable_upload_progress
1552 false, // do_not_prompt_for_login
1553 blink::WebReferrerPolicyDefault
,
1554 blink::WebPageVisibilityStateVisible
,
1556 base::WeakPtr
<ResourceMessageFilter
>(), // filter
1560 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(int child_id
,
1564 scheduler_
->OnClientCreated(child_id
, route_id
, is_visible
, is_audible
);
1567 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1570 scheduler_
->OnClientDeleted(child_id
, route_id
);
1571 CancelRequestsForRoute(child_id
, route_id
);
1574 void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id
,
1577 scheduler_
->OnLoadingStateChanged(child_id
, route_id
, !is_loading
);
1580 void ResourceDispatcherHostImpl::OnRenderViewHostWasHidden(
1583 scheduler_
->OnVisibilityChanged(child_id
, route_id
, false);
1586 void ResourceDispatcherHostImpl::OnRenderViewHostWasShown(
1589 scheduler_
->OnVisibilityChanged(child_id
, route_id
, true);
1592 void ResourceDispatcherHostImpl::OnAudioRenderHostStreamStateChanged(
1596 scheduler_
->OnAudibilityChanged(child_id
, route_id
, is_playing
);
1599 // This function is only used for saving feature.
1600 void ResourceDispatcherHostImpl::BeginSaveFile(
1602 const Referrer
& referrer
,
1605 ResourceContext
* context
) {
1609 // http://crbug.com/90971
1611 base::strlcpy(url_buf
, url
.spec().c_str(), arraysize(url_buf
));
1612 base::debug::Alias(url_buf
);
1613 CHECK(ContainsKey(active_resource_contexts_
, context
));
1617 const net::URLRequestContext
* request_context
= context
->GetRequestContext();
1619 request_context
->job_factory()->IsHandledURL(url
);
1621 // Since any URLs which have non-standard scheme have been filtered
1622 // by save manager(see GURL::SchemeIsStandard). This situation
1623 // should not happen.
1628 net::CookieStore
* cookie_store
=
1629 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1631 scoped_ptr
<net::URLRequest
> request(
1632 request_context
->CreateRequest(url
, net::DEFAULT_PRIORITY
, NULL
,
1635 request
->set_method("GET");
1636 SetReferrerForRequest(request
.get(), referrer
);
1638 // So far, for saving page, we need fetch content from cache, in the
1639 // future, maybe we can use a configuration to configure this behavior.
1640 request
->SetLoadFlags(net::LOAD_PREFERRING_CACHE
);
1642 // Since we're just saving some resources we need, disallow downloading.
1643 ResourceRequestInfoImpl
* extra_info
=
1644 CreateRequestInfo(child_id
, route_id
, false, context
);
1645 extra_info
->AssociateWithRequest(request
.get()); // Request takes ownership.
1647 scoped_ptr
<ResourceHandler
> handler(
1648 new SaveFileResourceHandler(request
.get(),
1652 save_file_manager_
.get()));
1654 BeginRequestInternal(request
.Pass(), handler
.Pass());
1657 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1658 const GlobalRequestID
& id
) {
1659 GetLoader(id
)->MarkAsTransferring();
1662 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1663 const GlobalRequestID
& id
) {
1664 // Request should still exist and be in the middle of a transfer.
1665 DCHECK(IsTransferredNavigation(id
));
1666 RemovePendingRequest(id
.child_id
, id
.request_id
);
1669 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1670 const GlobalRequestID
& id
) {
1671 ResourceLoader
* loader
= GetLoader(id
);
1672 // The response we were meant to resume could have already been canceled.
1674 loader
->CompleteTransfer();
1677 // The object died, so cancel and detach all requests associated with it except
1678 // for downloads and detachable resources, which belong to the browser process
1679 // even if initiated via a renderer.
1680 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id
) {
1681 CancelRequestsForRoute(child_id
, -1 /* cancel all */);
1682 registered_temp_files_
.erase(child_id
);
1685 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id
,
1687 // Since pending_requests_ is a map, we first build up a list of all of the
1688 // matching requests to be cancelled, and then we cancel them. Since there
1689 // may be more than one request to cancel, we cannot simply hold onto the map
1690 // iterators found in the first loop.
1692 // Find the global ID of all matching elements.
1693 bool any_requests_transferring
= false;
1694 std::vector
<GlobalRequestID
> matching_requests
;
1695 for (LoaderMap::const_iterator i
= pending_loaders_
.begin();
1696 i
!= pending_loaders_
.end(); ++i
) {
1697 if (i
->first
.child_id
!= child_id
)
1700 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
1702 GlobalRequestID
id(child_id
, i
->first
.request_id
);
1703 DCHECK(id
== i
->first
);
1704 // Don't cancel navigations that are expected to live beyond this process.
1705 if (IsTransferredNavigation(id
))
1706 any_requests_transferring
= true;
1707 if (info
->detachable_handler()) {
1708 info
->detachable_handler()->Detach();
1709 } else if (!info
->IsDownload() && !info
->is_stream() &&
1710 !IsTransferredNavigation(id
) &&
1711 (route_id
== -1 || route_id
== info
->GetRouteID())) {
1712 matching_requests
.push_back(id
);
1717 for (size_t i
= 0; i
< matching_requests
.size(); ++i
) {
1718 LoaderMap::iterator iter
= pending_loaders_
.find(matching_requests
[i
]);
1719 // Although every matching request was in pending_requests_ when we built
1720 // matching_requests, it is normal for a matching request to be not found
1721 // in pending_requests_ after we have removed some matching requests from
1722 // pending_requests_. For example, deleting a net::URLRequest that has
1723 // exclusive (write) access to an HTTP cache entry may unblock another
1724 // net::URLRequest that needs exclusive access to the same cache entry, and
1725 // that net::URLRequest may complete and remove itself from
1726 // pending_requests_. So we need to check that iter is not equal to
1727 // pending_requests_.end().
1728 if (iter
!= pending_loaders_
.end())
1729 RemovePendingLoader(iter
);
1732 // Don't clear the blocked loaders or offline policy maps if any of the
1733 // requests in route_id are being transferred to a new process, since those
1734 // maps will be updated with the new route_id after the transfer. Otherwise
1735 // we will lose track of this info when the old route goes away, before the
1736 // new one is created.
1737 if (any_requests_transferring
)
1740 // Now deal with blocked requests if any.
1741 if (route_id
!= -1) {
1742 if (blocked_loaders_map_
.find(GlobalRoutingID(child_id
, route_id
)) !=
1743 blocked_loaders_map_
.end()) {
1744 CancelBlockedRequestsForRoute(child_id
, route_id
);
1747 // We have to do all render views for the process |child_id|.
1748 // Note that we have to do this in 2 passes as we cannot call
1749 // CancelBlockedRequestsForRoute while iterating over
1750 // blocked_loaders_map_, as it modifies it.
1751 std::set
<int> route_ids
;
1752 for (BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.begin();
1753 iter
!= blocked_loaders_map_
.end(); ++iter
) {
1754 if (iter
->first
.child_id
== child_id
)
1755 route_ids
.insert(iter
->first
.route_id
);
1757 for (std::set
<int>::const_iterator iter
= route_ids
.begin();
1758 iter
!= route_ids
.end(); ++iter
) {
1759 CancelBlockedRequestsForRoute(child_id
, *iter
);
1764 // Cancels the request and removes it from the list.
1765 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id
,
1767 LoaderMap::iterator i
= pending_loaders_
.find(
1768 GlobalRequestID(child_id
, request_id
));
1769 if (i
== pending_loaders_
.end()) {
1770 NOTREACHED() << "Trying to remove a request that's not here";
1773 RemovePendingLoader(i
);
1776 void ResourceDispatcherHostImpl::RemovePendingLoader(
1777 const LoaderMap::iterator
& iter
) {
1778 ResourceRequestInfoImpl
* info
= iter
->second
->GetRequestInfo();
1780 // Remove the memory credit that we added when pushing the request onto
1781 // the pending list.
1782 IncrementOutstandingRequestsMemory(-1, *info
);
1784 pending_loaders_
.erase(iter
);
1786 // If we have no more pending requests, then stop the load state monitor
1787 if (pending_loaders_
.empty() && update_load_states_timer_
)
1788 update_load_states_timer_
->Stop();
1791 void ResourceDispatcherHostImpl::CancelRequest(int child_id
,
1793 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1795 // We probably want to remove this warning eventually, but I wanted to be
1796 // able to notice when this happens during initial development since it
1797 // should be rare and may indicate a bug.
1798 DVLOG(1) << "Canceling a request that wasn't found";
1802 RemovePendingRequest(child_id
, request_id
);
1805 ResourceDispatcherHostImpl::OustandingRequestsStats
1806 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1807 const ResourceRequestInfoImpl
& info
) {
1808 OutstandingRequestsStatsMap::iterator entry
=
1809 outstanding_requests_stats_map_
.find(info
.GetChildID());
1810 OustandingRequestsStats stats
= { 0, 0 };
1811 if (entry
!= outstanding_requests_stats_map_
.end())
1812 stats
= entry
->second
;
1816 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1817 const ResourceRequestInfoImpl
& info
,
1818 const OustandingRequestsStats
& stats
) {
1819 if (stats
.memory_cost
== 0 && stats
.num_requests
== 0)
1820 outstanding_requests_stats_map_
.erase(info
.GetChildID());
1822 outstanding_requests_stats_map_
[info
.GetChildID()] = stats
;
1825 ResourceDispatcherHostImpl::OustandingRequestsStats
1826 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1828 const ResourceRequestInfoImpl
& info
) {
1829 DCHECK_EQ(1, abs(count
));
1831 // Retrieve the previous value (defaulting to 0 if not found).
1832 OustandingRequestsStats stats
= GetOutstandingRequestsStats(info
);
1834 // Insert/update the total; delete entries when their count reaches 0.
1835 stats
.memory_cost
+= count
* info
.memory_cost();
1836 DCHECK_GE(stats
.memory_cost
, 0);
1837 UpdateOutstandingRequestsStats(info
, stats
);
1842 ResourceDispatcherHostImpl::OustandingRequestsStats
1843 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1845 ResourceRequestInfoImpl
* info
) {
1846 DCHECK_EQ(1, abs(count
));
1847 num_in_flight_requests_
+= count
;
1849 // Keep track of whether this request is counting toward the number of
1850 // in-flight requests for this process, in case we need to transfer it to
1851 // another process. This should be a toggle.
1852 DCHECK_NE(info
->counted_as_in_flight_request(), count
> 0);
1853 info
->set_counted_as_in_flight_request(count
> 0);
1855 OustandingRequestsStats stats
= GetOutstandingRequestsStats(*info
);
1856 stats
.num_requests
+= count
;
1857 DCHECK_GE(stats
.num_requests
, 0);
1858 UpdateOutstandingRequestsStats(*info
, stats
);
1863 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1864 net::URLRequest
* request
) {
1865 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1866 OustandingRequestsStats stats
= IncrementOutstandingRequestsCount(1, info
);
1868 if (stats
.num_requests
> max_num_in_flight_requests_per_process_
)
1870 if (num_in_flight_requests_
> max_num_in_flight_requests_
)
1876 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1877 net::URLRequest
* request
) {
1878 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1879 IncrementOutstandingRequestsCount(-1, info
);
1882 void ResourceDispatcherHostImpl::BeginNavigationRequest(
1883 ResourceContext
* resource_context
,
1884 int64 frame_tree_node_id
,
1885 const NavigationRequestInfo
& info
,
1886 NavigationURLLoaderImplCore
* loader
) {
1887 // PlzNavigate: BeginNavigationRequest currently should only be used for the
1888 // browser-side navigations project.
1889 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1890 switches::kEnableBrowserSideNavigation
));
1892 ResourceType resource_type
= info
.is_main_frame
?
1893 RESOURCE_TYPE_MAIN_FRAME
: RESOURCE_TYPE_SUB_FRAME
;
1896 // TODO(davidben): Check ShouldServiceRequest here. This is important; it
1897 // needs to be checked relative to the child that /requested/ the
1898 // navigation. It's where file upload checks, etc., come in.
1899 (delegate_
&& !delegate_
->ShouldBeginRequest(
1900 info
.begin_params
.method
,
1901 info
.common_params
.url
,
1903 resource_context
))) {
1904 loader
->NotifyRequestFailed(net::ERR_ABORTED
);
1908 // Save the URL on the stack to help catch URLRequests which outlive their
1909 // URLRequestContexts. See https://crbug.com/90971
1912 url_buf
, info
.common_params
.url
.spec().c_str(), arraysize(url_buf
));
1913 base::debug::Alias(url_buf
);
1914 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1916 const net::URLRequestContext
* request_context
=
1917 resource_context
->GetRequestContext();
1919 int load_flags
= info
.begin_params
.load_flags
;
1920 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
1921 if (info
.is_main_frame
) {
1922 load_flags
|= net::LOAD_MAIN_FRAME
;
1924 load_flags
|= net::LOAD_SUB_FRAME
;
1926 // Add a flag to selectively bypass the data reduction proxy if the resource
1927 // type is not an image.
1928 load_flags
|= net::LOAD_BYPASS_DATA_REDUCTION_PROXY
;
1930 // TODO(davidben): BuildLoadFlagsForRequest includes logic for
1931 // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here?
1933 // Sync loads should have maximum priority and should be the only
1934 // requests that have the ignore limits flag set.
1935 DCHECK(!(load_flags
& net::LOAD_IGNORE_LIMITS
));
1937 // TODO(davidben): OverrideCookieStoreForRenderProcess handling for
1938 // prerender. There may not be a renderer process yet, so we need to use the
1939 // ResourceContext or something.
1940 scoped_ptr
<net::URLRequest
> new_request
;
1941 new_request
= request_context
->CreateRequest(
1942 info
.common_params
.url
, net::HIGHEST
, nullptr, nullptr);
1944 new_request
->set_method(info
.begin_params
.method
);
1945 new_request
->set_first_party_for_cookies(
1946 info
.first_party_for_cookies
);
1947 if (info
.is_main_frame
) {
1948 new_request
->set_first_party_url_policy(
1949 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1952 SetReferrerForRequest(new_request
.get(), info
.common_params
.referrer
);
1954 net::HttpRequestHeaders headers
;
1955 headers
.AddHeadersFromString(info
.begin_params
.headers
);
1956 new_request
->SetExtraRequestHeaders(headers
);
1958 new_request
->SetLoadFlags(load_flags
);
1960 // Resolve elements from request_body and prepare upload data.
1961 if (info
.request_body
.get()) {
1962 storage::BlobStorageContext
* blob_context
= GetBlobStorageContext(
1963 GetChromeBlobStorageContextForResourceContext(resource_context
));
1964 AttachRequestBodyBlobDataHandles(
1965 info
.request_body
.get(),
1967 // TODO(davidben): The FileSystemContext is null here. In the case where
1968 // another renderer requested this navigation, this should be the same
1969 // FileSystemContext passed into ShouldServiceRequest.
1970 new_request
->set_upload(UploadDataStreamBuilder::Build(
1971 info
.request_body
.get(),
1973 nullptr, // file_system_context
1974 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1980 // Make extra info and read footer (contains request ID).
1982 // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so
1983 // that IO thread -> UI thread hops will work.
1984 ResourceRequestInfoImpl
* extra_info
=
1985 new ResourceRequestInfoImpl(
1986 PROCESS_TYPE_BROWSER
,
1989 -1, // request_data.origin_pid,
1991 -1, // request_data.render_frame_id,
1993 info
.parent_is_main_frame
,
1994 -1, // request_data.parent_render_frame_id,
1996 info
.common_params
.transition
,
1997 // should_replace_current_entry. This was only maintained at layer for
1998 // request transfers and isn't needed for browser-side navigations.
2000 false, // is download
2002 info
.common_params
.allow_download
,
2003 info
.begin_params
.has_user_gesture
,
2004 true, // enable_load_timing
2005 false, // enable_upload_progress
2006 false, // do_not_prompt_for_login
2007 info
.common_params
.referrer
.policy
,
2008 // TODO(davidben): This is only used for prerenders. Replace
2009 // is_showing with something for that. Or maybe it just comes from the
2010 // same mechanism as the cookie one.
2011 blink::WebPageVisibilityStateVisible
,
2013 base::WeakPtr
<ResourceMessageFilter
>(), // filter
2015 // Request takes ownership.
2016 extra_info
->AssociateWithRequest(new_request
.get());
2018 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
2019 // Hang on to a reference to ensure the blob is not released prior
2020 // to the job being started.
2021 ChromeBlobStorageContext
* blob_context
=
2022 GetChromeBlobStorageContextForResourceContext(resource_context
);
2023 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
2025 blob_context
->context()->GetBlobDataFromPublicURL(new_request
->url()));
2028 // TODO(davidben): Attach ServiceWorkerRequestHandler.
2029 // TODO(michaeln): Help out with this and that.
2030 // TODO(davidben): Attach AppCacheInterceptor.
2032 scoped_ptr
<ResourceHandler
> handler(new NavigationResourceHandler(
2033 new_request
.get(), loader
));
2035 // TODO(davidben): Pass in the appropriate appcache_service. Also fix the
2036 // dependency on child_id/route_id. Those are used by the ResourceScheduler;
2037 // currently it's a no-op.
2038 handler
= AddStandardHandlers(new_request
.get(), resource_type
,
2040 nullptr, // appcache_service
2045 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
2049 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
2050 net::URLRequest
* request
) {
2051 // The following fields should be a minor size contribution (experimentally
2052 // on the order of 100). However since they are variable length, it could
2053 // in theory be a sizeable contribution.
2054 int strings_cost
= request
->extra_request_headers().ToString().size() +
2055 request
->original_url().spec().size() +
2056 request
->referrer().size() +
2057 request
->method().size();
2059 // Note that this expression will typically be dominated by:
2060 // |kAvgBytesPerOutstandingRequest|.
2061 return kAvgBytesPerOutstandingRequest
+ strings_cost
;
2064 void ResourceDispatcherHostImpl::BeginRequestInternal(
2065 scoped_ptr
<net::URLRequest
> request
,
2066 scoped_ptr
<ResourceHandler
> handler
) {
2067 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
2068 tracked_objects::ScopedTracker
tracking_profile(
2069 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2070 "456331 ResourceDispatcherHostImpl::BeginRequestInternal"));
2071 DCHECK(!request
->is_pending());
2072 ResourceRequestInfoImpl
* info
=
2073 ResourceRequestInfoImpl::ForRequest(request
.get());
2075 if ((TimeTicks::Now() - last_user_gesture_time_
) <
2076 TimeDelta::FromMilliseconds(kUserGestureWindowMs
)) {
2077 request
->SetLoadFlags(
2078 request
->load_flags() | net::LOAD_MAYBE_USER_GESTURE
);
2081 // Add the memory estimate that starting this request will consume.
2082 info
->set_memory_cost(CalculateApproximateMemoryCost(request
.get()));
2084 // If enqueing/starting this request will exceed our per-process memory
2085 // bound, abort it right away.
2086 OustandingRequestsStats stats
= IncrementOutstandingRequestsMemory(1, *info
);
2087 if (stats
.memory_cost
> max_outstanding_requests_cost_per_process_
) {
2088 // We call "CancelWithError()" as a way of setting the net::URLRequest's
2089 // status -- it has no effect beyond this, since the request hasn't started.
2090 request
->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES
);
2093 handler
->OnResponseCompleted(request
->status(), std::string(), &defer
);
2095 // TODO(darin): The handler is not ready for us to kill the request. Oops!
2099 IncrementOutstandingRequestsMemory(-1, *info
);
2101 // A ResourceHandler must not outlive its associated URLRequest.
2106 linked_ptr
<ResourceLoader
> loader(
2107 new ResourceLoader(request
.Pass(), handler
.Pass(), this));
2109 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2110 BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.find(id
);
2111 if (iter
!= blocked_loaders_map_
.end()) {
2112 // The request should be blocked.
2113 iter
->second
->push_back(loader
);
2117 StartLoading(info
, loader
);
2120 void ResourceDispatcherHostImpl::StartLoading(
2121 ResourceRequestInfoImpl
* info
,
2122 const linked_ptr
<ResourceLoader
>& loader
) {
2123 pending_loaders_
[info
->GetGlobalRequestID()] = loader
;
2125 loader
->StartRequest();
2128 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl
* contents
) {
2129 last_user_gesture_time_
= TimeTicks::Now();
2132 net::URLRequest
* ResourceDispatcherHostImpl::GetURLRequest(
2133 const GlobalRequestID
& id
) {
2134 ResourceLoader
* loader
= GetLoader(id
);
2138 return loader
->request();
2143 // This function attempts to return the "more interesting" load state of |a|
2144 // and |b|. We don't have temporal information about these load states
2145 // (meaning we don't know when we transitioned into these states), so we just
2146 // rank them according to how "interesting" the states are.
2148 // We take advantage of the fact that the load states are an enumeration listed
2149 // in the order in which they occur during the lifetime of a request, so we can
2150 // regard states with larger numeric values as being further along toward
2151 // completion. We regard those states as more interesting to report since they
2152 // represent progress.
2154 // For example, by this measure "tranferring data" is a more interesting state
2155 // than "resolving host" because when we are transferring data we are actually
2156 // doing something that corresponds to changes that the user might observe,
2157 // whereas waiting for a host name to resolve implies being stuck.
2159 const net::LoadStateWithParam
& MoreInterestingLoadState(
2160 const net::LoadStateWithParam
& a
, const net::LoadStateWithParam
& b
) {
2161 return (a
.state
< b
.state
) ? b
: a
;
2164 // Carries information about a load state change.
2167 net::LoadStateWithParam load_state
;
2168 uint64 upload_position
;
2172 // Map from ProcessID+RouteID pair to LoadState
2173 typedef std::map
<GlobalRoutingID
, LoadInfo
> LoadInfoMap
;
2175 // Used to marshal calls to LoadStateChanged from the IO to UI threads. We do
2176 // them all as a single callback to avoid spamming the UI thread.
2177 void LoadInfoUpdateCallback(const LoadInfoMap
& info_map
) {
2178 LoadInfoMap::const_iterator i
;
2179 for (i
= info_map
.begin(); i
!= info_map
.end(); ++i
) {
2180 RenderViewHostImpl
* view
=
2181 RenderViewHostImpl::FromID(i
->first
.child_id
, i
->first
.route_id
);
2182 if (view
) // The view could be gone at this point.
2183 view
->LoadStateChanged(i
->second
.url
, i
->second
.load_state
,
2184 i
->second
.upload_position
,
2185 i
->second
.upload_size
);
2191 void ResourceDispatcherHostImpl::UpdateLoadStates() {
2192 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is
2194 tracked_objects::ScopedTracker
tracking_profile(
2195 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2196 "455952 ResourceDispatcherHostImpl::UpdateLoadStates"));
2197 // Populate this map with load state changes, and then send them on to the UI
2198 // thread where they can be passed along to the respective RVHs.
2199 LoadInfoMap info_map
;
2201 LoaderMap::const_iterator i
;
2203 // Determine the largest upload size of all requests
2204 // in each View (good chance it's zero).
2205 std::map
<GlobalRoutingID
, uint64
> largest_upload_size
;
2206 for (i
= pending_loaders_
.begin(); i
!= pending_loaders_
.end(); ++i
) {
2207 net::URLRequest
* request
= i
->second
->request();
2208 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
2209 uint64 upload_size
= request
->GetUploadProgress().size();
2210 if (request
->GetLoadState().state
!= net::LOAD_STATE_SENDING_REQUEST
)
2212 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2213 if (upload_size
&& largest_upload_size
[id
] < upload_size
)
2214 largest_upload_size
[id
] = upload_size
;
2217 for (i
= pending_loaders_
.begin(); i
!= pending_loaders_
.end(); ++i
) {
2218 net::URLRequest
* request
= i
->second
->request();
2219 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
2220 net::LoadStateWithParam load_state
= request
->GetLoadState();
2221 net::UploadProgress progress
= request
->GetUploadProgress();
2223 // We also poll for upload progress on this timer and send upload
2224 // progress ipc messages to the plugin process.
2225 i
->second
->ReportUploadProgress();
2227 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2229 // If a request is uploading data, ignore all other requests so that the
2230 // upload progress takes priority for being shown in the status bar.
2231 if (largest_upload_size
.find(id
) != largest_upload_size
.end() &&
2232 progress
.size() < largest_upload_size
[id
])
2235 net::LoadStateWithParam to_insert
= load_state
;
2236 LoadInfoMap::iterator existing
= info_map
.find(id
);
2237 if (existing
!= info_map
.end()) {
2239 MoreInterestingLoadState(existing
->second
.load_state
, load_state
);
2240 if (to_insert
.state
== existing
->second
.load_state
.state
)
2243 LoadInfo
& load_info
= info_map
[id
];
2244 load_info
.url
= request
->url();
2245 load_info
.load_state
= to_insert
;
2246 load_info
.upload_size
= progress
.size();
2247 load_info
.upload_position
= progress
.position();
2250 if (info_map
.empty())
2253 BrowserThread::PostTask(
2254 BrowserThread::UI
, FROM_HERE
,
2255 base::Bind(&LoadInfoUpdateCallback
, info_map
));
2258 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id
,
2260 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
2261 GlobalRoutingID
key(child_id
, route_id
);
2262 DCHECK(blocked_loaders_map_
.find(key
) == blocked_loaders_map_
.end()) <<
2263 "BlockRequestsForRoute called multiple time for the same RVH";
2264 blocked_loaders_map_
[key
] = new BlockedLoadersList();
2267 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id
,
2269 ProcessBlockedRequestsForRoute(child_id
, route_id
, false);
2272 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id
,
2274 ProcessBlockedRequestsForRoute(child_id
, route_id
, true);
2277 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
2280 bool cancel_requests
) {
2281 BlockedLoadersMap::iterator iter
= blocked_loaders_map_
.find(
2282 GlobalRoutingID(child_id
, route_id
));
2283 if (iter
== blocked_loaders_map_
.end()) {
2284 // It's possible to reach here if the renderer crashed while an interstitial
2285 // page was showing.
2289 BlockedLoadersList
* loaders
= iter
->second
;
2291 // Removing the vector from the map unblocks any subsequent requests.
2292 blocked_loaders_map_
.erase(iter
);
2294 for (BlockedLoadersList::iterator loaders_iter
= loaders
->begin();
2295 loaders_iter
!= loaders
->end(); ++loaders_iter
) {
2296 linked_ptr
<ResourceLoader
> loader
= *loaders_iter
;
2297 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
2298 if (cancel_requests
) {
2299 IncrementOutstandingRequestsMemory(-1, *info
);
2301 StartLoading(info
, loader
);
2308 ResourceDispatcherHostImpl::HttpAuthRelationType
2309 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
2310 const GURL
& request_url
,
2311 const GURL
& first_party
) {
2312 if (!first_party
.is_valid())
2313 return HTTP_AUTH_RELATION_TOP
;
2315 if (net::registry_controlled_domains::SameDomainOrHost(
2316 first_party
, request_url
,
2317 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
))
2318 return HTTP_AUTH_RELATION_SAME_DOMAIN
;
2320 if (allow_cross_origin_auth_prompt())
2321 return HTTP_AUTH_RELATION_ALLOWED_CROSS
;
2323 return HTTP_AUTH_RELATION_BLOCKED_CROSS
;
2326 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
2327 return allow_cross_origin_auth_prompt_
;
2330 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
2331 const GlobalRequestID
& id
) const {
2332 ResourceLoader
* loader
= GetLoader(id
);
2333 return loader
? loader
->is_transferring() : false;
2336 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(
2337 const GlobalRequestID
& id
) const {
2338 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
2340 LoaderMap::const_iterator i
= pending_loaders_
.find(id
);
2341 if (i
== pending_loaders_
.end())
2344 return i
->second
.get();
2347 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(int child_id
,
2348 int request_id
) const {
2349 return GetLoader(GlobalRequestID(child_id
, request_id
));
2352 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
2353 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2354 DelegateMap::iterator it
= delegate_map_
.find(id
);
2355 if (it
== delegate_map_
.end()) {
2356 it
= delegate_map_
.insert(
2357 std::make_pair(id
, new ObserverList
<ResourceMessageDelegate
>)).first
;
2359 it
->second
->AddObserver(delegate
);
2362 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
2363 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2364 DCHECK(ContainsKey(delegate_map_
, id
));
2365 DelegateMap::iterator it
= delegate_map_
.find(id
);
2366 DCHECK(it
->second
->HasObserver(delegate
));
2367 it
->second
->RemoveObserver(delegate
);
2368 if (!it
->second
->might_have_observers()) {
2370 delegate_map_
.erase(it
);
2374 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
2375 const ResourceHostMsg_Request
& request_data
,
2377 bool is_sync_load
) {
2378 int load_flags
= request_data
.load_flags
;
2380 // Although EV status is irrelevant to sub-frames and sub-resources, we have
2381 // to perform EV certificate verification on all resources because an HTTP
2382 // keep-alive connection created to load a sub-frame or a sub-resource could
2383 // be reused to load a main frame.
2384 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
2385 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
2386 load_flags
|= net::LOAD_MAIN_FRAME
;
2387 } else if (request_data
.resource_type
== RESOURCE_TYPE_SUB_FRAME
) {
2388 load_flags
|= net::LOAD_SUB_FRAME
;
2389 } else if (request_data
.resource_type
== RESOURCE_TYPE_PREFETCH
) {
2390 load_flags
|= net::LOAD_PREFETCH
;
2394 load_flags
|= net::LOAD_IGNORE_LIMITS
;
2396 ChildProcessSecurityPolicyImpl
* policy
=
2397 ChildProcessSecurityPolicyImpl::GetInstance();
2398 if (!policy
->CanSendCookiesForOrigin(child_id
, request_data
.url
)) {
2399 load_flags
|= (net::LOAD_DO_NOT_SEND_COOKIES
|
2400 net::LOAD_DO_NOT_SEND_AUTH_DATA
|
2401 net::LOAD_DO_NOT_SAVE_COOKIES
);
2404 // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only
2405 // allow requesting them if requester has ReadRawCookies permission.
2406 if ((load_flags
& net::LOAD_REPORT_RAW_HEADERS
)
2407 && !policy
->CanReadRawCookies(child_id
)) {
2408 VLOG(1) << "Denied unauthorized request for raw headers";
2409 load_flags
&= ~net::LOAD_REPORT_RAW_HEADERS
;
2412 // Add a flag to selectively bypass the data reduction proxy if the resource
2413 // type is not an image.
2414 if (request_data
.resource_type
!= RESOURCE_TYPE_IMAGE
)
2415 load_flags
|= net::LOAD_BYPASS_DATA_REDUCTION_PROXY
;
2420 } // namespace content