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(
803 FROM_HERE
, TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec
),
804 this, &ResourceDispatcherHostImpl::UpdateLoadInfo
);
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 // When logging time-to-network only care about main frame and non-transfer
982 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
&&
983 request_data
.transferred_request_request_id
== -1 &&
984 !base::CommandLine::ForCurrentProcess()->HasSwitch(
985 switches::kEnableBrowserSideNavigation
)) {
986 BrowserThread::PostTask(
989 base::Bind(&LogResourceRequestTimeOnUI
,
992 request_data
.render_frame_id
,
995 BeginRequest(request_id
, request_data
, NULL
, routing_id
);
998 // Begins a resource request with the given params on behalf of the specified
999 // child process. Responses will be dispatched through the given receiver. The
1000 // process ID is used to lookup WebContentsImpl from routing_id's in the case of
1001 // a request from a renderer. request_context is the cookie/cache context to be
1002 // used for this request.
1004 // If sync_result is non-null, then a SyncLoad reply will be generated, else
1005 // a normal asynchronous set of response messages will be generated.
1006 void ResourceDispatcherHostImpl::OnSyncLoad(
1008 const ResourceHostMsg_Request
& request_data
,
1009 IPC::Message
* sync_result
) {
1010 BeginRequest(request_id
, request_data
, sync_result
,
1011 sync_result
->routing_id());
1014 void ResourceDispatcherHostImpl::UpdateRequestForTransfer(
1018 const ResourceHostMsg_Request
& request_data
,
1019 const linked_ptr
<ResourceLoader
>& loader
) {
1020 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
1021 GlobalRoutingID
old_routing_id(
1022 request_data
.transferred_request_child_id
, info
->GetRouteID());
1023 GlobalRequestID
old_request_id(request_data
.transferred_request_child_id
,
1024 request_data
.transferred_request_request_id
);
1025 GlobalRoutingID
new_routing_id(child_id
, route_id
);
1026 GlobalRequestID
new_request_id(child_id
, request_id
);
1028 // Clear out data that depends on |info| before updating it.
1029 // We always need to move the memory stats to the new process. In contrast,
1030 // stats.num_requests is only tracked for some requests (those that require
1031 // file descriptors for their shared memory buffer).
1032 IncrementOutstandingRequestsMemory(-1, *info
);
1033 bool should_update_count
= info
->counted_as_in_flight_request();
1034 if (should_update_count
)
1035 IncrementOutstandingRequestsCount(-1, info
);
1036 pending_loaders_
.erase(old_request_id
);
1038 // ResourceHandlers should always get state related to the request from the
1039 // ResourceRequestInfo rather than caching it locally. This lets us update
1040 // the info object when a transfer occurs.
1041 info
->UpdateForTransfer(child_id
, route_id
, request_data
.origin_pid
,
1042 request_id
, request_data
.parent_render_frame_id
,
1043 filter_
->GetWeakPtr());
1045 // Update maps that used the old IDs, if necessary. Some transfers in tests
1046 // do not actually use a different ID, so not all maps need to be updated.
1047 pending_loaders_
[new_request_id
] = loader
;
1048 IncrementOutstandingRequestsMemory(1, *info
);
1049 if (should_update_count
)
1050 IncrementOutstandingRequestsCount(1, info
);
1051 if (old_routing_id
!= new_routing_id
) {
1052 if (blocked_loaders_map_
.find(old_routing_id
) !=
1053 blocked_loaders_map_
.end()) {
1054 blocked_loaders_map_
[new_routing_id
] =
1055 blocked_loaders_map_
[old_routing_id
];
1056 blocked_loaders_map_
.erase(old_routing_id
);
1059 if (old_request_id
!= new_request_id
) {
1060 DelegateMap::iterator it
= delegate_map_
.find(old_request_id
);
1061 if (it
!= delegate_map_
.end()) {
1062 // Tell each delegate that the request ID has changed.
1063 ObserverList
<ResourceMessageDelegate
>::Iterator
del_it(*it
->second
);
1064 ResourceMessageDelegate
* delegate
;
1065 while ((delegate
= del_it
.GetNext()) != NULL
) {
1066 delegate
->set_request_id(new_request_id
);
1068 // Now store the observer list under the new request ID.
1069 delegate_map_
[new_request_id
] = delegate_map_
[old_request_id
];
1070 delegate_map_
.erase(old_request_id
);
1074 AppCacheInterceptor::CompleteCrossSiteTransfer(
1077 request_data
.appcache_host_id
);
1079 ServiceWorkerRequestHandler
* handler
=
1080 ServiceWorkerRequestHandler::GetHandler(loader
->request());
1082 handler
->CompleteCrossSiteTransfer(
1083 child_id
, request_data
.service_worker_provider_id
);
1086 // We should have a CrossSiteResourceHandler to finish the transfer.
1087 DCHECK(info
->cross_site_handler());
1090 void ResourceDispatcherHostImpl::BeginRequest(
1092 const ResourceHostMsg_Request
& request_data
,
1093 IPC::Message
* sync_result
, // only valid for sync
1095 int process_type
= filter_
->process_type();
1096 int child_id
= filter_
->child_id();
1098 // Reject invalid priority.
1099 if (request_data
.priority
< net::MINIMUM_PRIORITY
||
1100 request_data
.priority
> net::MAXIMUM_PRIORITY
) {
1101 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1102 filter_
->BadMessageReceived();
1106 // If we crash here, figure out what URL the renderer was requesting.
1107 // http://crbug.com/91398
1109 base::strlcpy(url_buf
, request_data
.url
.spec().c_str(), arraysize(url_buf
));
1110 base::debug::Alias(url_buf
);
1112 // If the request that's coming in is being transferred from another process,
1113 // we want to reuse and resume the old loader rather than start a new one.
1114 LoaderMap::iterator it
= pending_loaders_
.find(
1115 GlobalRequestID(request_data
.transferred_request_child_id
,
1116 request_data
.transferred_request_request_id
));
1117 if (it
!= pending_loaders_
.end()) {
1118 // If the request is transferring to a new process, we can update our
1119 // state and let it resume with its existing ResourceHandlers.
1120 if (it
->second
->is_transferring()) {
1121 linked_ptr
<ResourceLoader
> deferred_loader
= it
->second
;
1122 UpdateRequestForTransfer(child_id
, route_id
, request_id
,
1123 request_data
, deferred_loader
);
1125 deferred_loader
->CompleteTransfer();
1127 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1128 filter_
->BadMessageReceived();
1133 ResourceContext
* resource_context
= NULL
;
1134 net::URLRequestContext
* request_context
= NULL
;
1135 filter_
->GetContexts(request_data
, &resource_context
, &request_context
);
1136 // http://crbug.com/90971
1137 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1140 !ShouldServiceRequest(process_type
, child_id
, request_data
,
1141 filter_
->file_system_context())) {
1142 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1146 // Allow the observer to block/handle the request.
1147 if (delegate_
&& !delegate_
->ShouldBeginRequest(request_data
.method
,
1149 request_data
.resource_type
,
1150 resource_context
)) {
1151 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1155 // Construct the request.
1156 net::CookieStore
* cookie_store
=
1157 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1159 scoped_ptr
<net::URLRequest
> new_request
;
1160 new_request
= request_context
->CreateRequest(
1161 request_data
.url
, request_data
.priority
, NULL
, cookie_store
);
1163 new_request
->set_method(request_data
.method
);
1164 new_request
->set_first_party_for_cookies(
1165 request_data
.first_party_for_cookies
);
1167 // If the request is a MAIN_FRAME request, the first-party URL gets updated on
1169 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
1170 new_request
->set_first_party_url_policy(
1171 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1174 const Referrer
referrer(request_data
.referrer
, request_data
.referrer_policy
);
1175 SetReferrerForRequest(new_request
.get(), referrer
);
1177 net::HttpRequestHeaders headers
;
1178 headers
.AddHeadersFromString(request_data
.headers
);
1179 new_request
->SetExtraRequestHeaders(headers
);
1181 storage::BlobStorageContext
* blob_context
=
1182 GetBlobStorageContext(filter_
->blob_storage_context());
1183 // Resolve elements from request_body and prepare upload data.
1184 if (request_data
.request_body
.get()) {
1185 // |blob_context| could be null when the request is from the plugins because
1186 // ResourceMessageFilters created in PluginProcessHost don't have the blob
1189 // Attaches the BlobDataHandles to request_body not to free the blobs and
1190 // any attached shareable files until upload completion. These data will
1191 // be used in UploadDataStream and ServiceWorkerURLRequestJob.
1192 AttachRequestBodyBlobDataHandles(
1193 request_data
.request_body
.get(),
1196 new_request
->set_upload(UploadDataStreamBuilder::Build(
1197 request_data
.request_body
.get(),
1199 filter_
->file_system_context(),
1200 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1204 bool allow_download
= request_data
.allow_download
&&
1205 IsResourceTypeFrame(request_data
.resource_type
);
1206 bool do_not_prompt_for_login
= request_data
.do_not_prompt_for_login
;
1207 bool is_sync_load
= sync_result
!= NULL
;
1209 BuildLoadFlagsForRequest(request_data
, child_id
, is_sync_load
);
1210 if (request_data
.resource_type
== RESOURCE_TYPE_PREFETCH
||
1211 request_data
.resource_type
== RESOURCE_TYPE_FAVICON
) {
1212 do_not_prompt_for_login
= true;
1214 if (request_data
.resource_type
== RESOURCE_TYPE_IMAGE
&&
1215 HTTP_AUTH_RELATION_BLOCKED_CROSS
==
1216 HttpAuthRelationTypeOf(request_data
.url
,
1217 request_data
.first_party_for_cookies
)) {
1218 // Prevent third-party image content from prompting for login, as this
1219 // is often a scam to extract credentials for another domain from the user.
1220 // Only block image loads, as the attack applies largely to the "src"
1221 // property of the <img> tag. It is common for web properties to allow
1222 // untrusted values for <img src>; this is considered a fair thing for an
1223 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
1224 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
1225 // would be considered vulnerable in and of itself.
1226 do_not_prompt_for_login
= true;
1227 load_flags
|= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY
;
1230 // Sync loads should have maximum priority and should be the only
1231 // requets that have the ignore limits flag set.
1233 DCHECK_EQ(request_data
.priority
, net::MAXIMUM_PRIORITY
);
1234 DCHECK_NE(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1236 DCHECK_EQ(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1238 new_request
->SetLoadFlags(load_flags
);
1240 // Make extra info and read footer (contains request ID).
1241 ResourceRequestInfoImpl
* extra_info
=
1242 new ResourceRequestInfoImpl(
1246 request_data
.origin_pid
,
1248 request_data
.render_frame_id
,
1249 request_data
.is_main_frame
,
1250 request_data
.parent_is_main_frame
,
1251 request_data
.parent_render_frame_id
,
1252 request_data
.resource_type
,
1253 request_data
.transition_type
,
1254 request_data
.should_replace_current_entry
,
1255 false, // is download
1258 request_data
.has_user_gesture
,
1259 request_data
.enable_load_timing
,
1260 request_data
.enable_upload_progress
,
1261 do_not_prompt_for_login
,
1262 request_data
.referrer_policy
,
1263 request_data
.visiblity_state
,
1265 filter_
->GetWeakPtr(),
1267 // Request takes ownership.
1268 extra_info
->AssociateWithRequest(new_request
.get());
1270 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
1271 // Hang on to a reference to ensure the blob is not released prior
1272 // to the job being started.
1273 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1275 filter_
->blob_storage_context()->context()->GetBlobDataFromPublicURL(
1276 new_request
->url()));
1279 // Initialize the service worker handler for the request. We don't use
1280 // ServiceWorker for synchronous loads to avoid renderer deadlocks.
1281 ServiceWorkerRequestHandler::InitializeHandler(
1283 filter_
->service_worker_context(),
1286 request_data
.service_worker_provider_id
,
1287 request_data
.skip_service_worker
|| is_sync_load
,
1288 request_data
.fetch_request_mode
,
1289 request_data
.fetch_credentials_mode
,
1290 request_data
.resource_type
,
1291 request_data
.fetch_request_context_type
,
1292 request_data
.fetch_frame_type
,
1293 request_data
.request_body
);
1295 // Have the appcache associate its extra info with the request.
1296 AppCacheInterceptor::SetExtraRequestInfo(
1297 new_request
.get(), filter_
->appcache_service(), child_id
,
1298 request_data
.appcache_host_id
, request_data
.resource_type
,
1299 request_data
.should_reset_appcache
);
1301 scoped_ptr
<ResourceHandler
> handler(
1302 CreateResourceHandler(
1304 request_data
, sync_result
, route_id
, process_type
, child_id
,
1308 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
1311 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::CreateResourceHandler(
1312 net::URLRequest
* request
,
1313 const ResourceHostMsg_Request
& request_data
,
1314 IPC::Message
* sync_result
,
1318 ResourceContext
* resource_context
) {
1319 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
1320 tracked_objects::ScopedTracker
tracking_profile(
1321 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1322 "456331 ResourceDispatcherHostImpl::CreateResourceHandler"));
1323 // Construct the IPC resource handler.
1324 scoped_ptr
<ResourceHandler
> handler
;
1326 // download_to_file is not supported for synchronous requests.
1327 if (request_data
.download_to_file
) {
1328 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1329 filter_
->BadMessageReceived();
1330 return scoped_ptr
<ResourceHandler
>();
1333 handler
.reset(new SyncResourceHandler(request
, sync_result
, this));
1335 handler
.reset(new AsyncResourceHandler(request
, this));
1337 // The RedirectToFileResourceHandler depends on being next in the chain.
1338 if (request_data
.download_to_file
) {
1340 new RedirectToFileResourceHandler(handler
.Pass(), request
));
1344 // Prefetches and <a ping> requests outlive their child process.
1345 if (!sync_result
&& IsDetachableResourceType(request_data
.resource_type
)) {
1346 handler
.reset(new DetachableResourceHandler(
1348 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs
),
1352 // PlzNavigate: If using --enable-browser-side-navigation, the
1353 // CrossSiteResourceHandler is not needed. This codepath is not used for the
1354 // actual navigation request, but only the subsequent blob URL load. This does
1355 // not require request transfers.
1356 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1357 switches::kEnableBrowserSideNavigation
)) {
1358 // Install a CrossSiteResourceHandler for all main frame requests. This will
1359 // check whether a transfer is required and, if so, pause for the UI thread
1360 // to drive the transfer.
1361 bool is_swappable_navigation
=
1362 request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
;
1363 // If we are using --site-per-process, install it for subframes as well.
1364 if (!is_swappable_navigation
&&
1365 base::CommandLine::ForCurrentProcess()->HasSwitch(
1366 switches::kSitePerProcess
)) {
1367 is_swappable_navigation
=
1368 request_data
.resource_type
== RESOURCE_TYPE_SUB_FRAME
;
1370 if (is_swappable_navigation
&& process_type
== PROCESS_TYPE_RENDERER
)
1371 handler
.reset(new CrossSiteResourceHandler(handler
.Pass(), request
));
1374 return AddStandardHandlers(request
, request_data
.resource_type
,
1375 resource_context
, filter_
->appcache_service(),
1376 child_id
, route_id
, handler
.Pass());
1379 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::AddStandardHandlers(
1380 net::URLRequest
* request
,
1381 ResourceType resource_type
,
1382 ResourceContext
* resource_context
,
1383 AppCacheService
* appcache_service
,
1386 scoped_ptr
<ResourceHandler
> handler
) {
1388 PluginService
* plugin_service
= nullptr;
1389 #if defined(ENABLE_PLUGINS)
1390 plugin_service
= PluginService::GetInstance();
1392 // Insert a buffered event handler before the actual one.
1394 new BufferedResourceHandler(
1395 handler
.Pass(), this, plugin_service
, request
));
1397 ScopedVector
<ResourceThrottle
> throttles
;
1399 delegate_
->RequestBeginning(request
,
1406 if (request
->has_upload()) {
1407 // Block power save while uploading data.
1408 throttles
.push_back(new PowerSaveBlockResourceThrottle());
1411 throttles
.push_back(
1412 scheduler_
->ScheduleRequest(child_id
, route_id
, request
).release());
1415 new ThrottlingResourceHandler(handler
.Pass(), request
, throttles
.Pass()));
1417 return handler
.Pass();
1420 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id
) {
1421 UnregisterDownloadedTempFile(filter_
->child_id(), request_id
);
1424 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id
) {
1425 // TODO(michaeln): maybe throttle DataDownloaded messages
1428 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1429 int child_id
, int request_id
, const base::FilePath
& file_path
) {
1430 scoped_refptr
<ShareableFileReference
> reference
=
1431 ShareableFileReference::Get(file_path
);
1432 DCHECK(reference
.get());
1434 registered_temp_files_
[child_id
][request_id
] = reference
;
1435 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1436 child_id
, reference
->path());
1438 // When the temp file is deleted, revoke permissions that the renderer has
1439 // to that file. This covers an edge case where the file is deleted and then
1440 // the same name is re-used for some other purpose, we don't want the old
1441 // renderer to still have access to it.
1443 // We do this when the file is deleted because the renderer can take a blob
1444 // reference to the temp file that outlives the url loaded that it was
1445 // loaded with to keep the file (and permissions) alive.
1446 reference
->AddFinalReleaseCallback(
1447 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy
,
1451 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1452 int child_id
, int request_id
) {
1453 DeletableFilesMap
& map
= registered_temp_files_
[child_id
];
1454 DeletableFilesMap::iterator found
= map
.find(request_id
);
1455 if (found
== map
.end())
1460 // Note that we don't remove the security bits here. This will be done
1461 // when all file refs are deleted (see RegisterDownloadedTempFile).
1464 bool ResourceDispatcherHostImpl::Send(IPC::Message
* message
) {
1469 void ResourceDispatcherHostImpl::OnUploadProgressACK(int request_id
) {
1470 ResourceLoader
* loader
= GetLoader(filter_
->child_id(), request_id
);
1472 loader
->OnUploadProgressACK();
1475 // Note that this cancel is subtly different from the other
1476 // CancelRequest methods in this file, which also tear down the loader.
1477 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id
) {
1478 int child_id
= filter_
->child_id();
1480 // When the old renderer dies, it sends a message to us to cancel its
1482 if (IsTransferredNavigation(GlobalRequestID(child_id
, request_id
)))
1485 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1487 // We probably want to remove this warning eventually, but I wanted to be
1488 // able to notice when this happens during initial development since it
1489 // should be rare and may indicate a bug.
1490 DVLOG(1) << "Canceling a request that wasn't found";
1494 loader
->CancelRequest(true);
1497 ResourceRequestInfoImpl
* ResourceDispatcherHostImpl::CreateRequestInfo(
1501 ResourceContext
* context
) {
1502 return new ResourceRequestInfoImpl(
1503 PROCESS_TYPE_RENDERER
,
1508 MSG_ROUTING_NONE
, // render_frame_id
1509 false, // is_main_frame
1510 false, // parent_is_main_frame
1511 -1, // parent_render_frame_id
1512 RESOURCE_TYPE_SUB_RESOURCE
,
1513 ui::PAGE_TRANSITION_LINK
,
1514 false, // should_replace_current_entry
1515 download
, // is_download
1517 download
, // allow_download
1518 false, // has_user_gesture
1519 false, // enable_load_timing
1520 false, // enable_upload_progress
1521 false, // do_not_prompt_for_login
1522 blink::WebReferrerPolicyDefault
,
1523 blink::WebPageVisibilityStateVisible
,
1525 base::WeakPtr
<ResourceMessageFilter
>(), // filter
1529 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(int child_id
,
1533 scheduler_
->OnClientCreated(child_id
, route_id
, is_visible
, is_audible
);
1536 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1539 scheduler_
->OnClientDeleted(child_id
, route_id
);
1540 CancelRequestsForRoute(child_id
, route_id
);
1543 void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id
,
1546 scheduler_
->OnLoadingStateChanged(child_id
, route_id
, !is_loading
);
1549 void ResourceDispatcherHostImpl::OnRenderViewHostWasHidden(
1552 scheduler_
->OnVisibilityChanged(child_id
, route_id
, false);
1555 void ResourceDispatcherHostImpl::OnRenderViewHostWasShown(
1558 scheduler_
->OnVisibilityChanged(child_id
, route_id
, true);
1561 void ResourceDispatcherHostImpl::OnAudioRenderHostStreamStateChanged(
1565 scheduler_
->OnAudibilityChanged(child_id
, route_id
, is_playing
);
1568 // This function is only used for saving feature.
1569 void ResourceDispatcherHostImpl::BeginSaveFile(
1571 const Referrer
& referrer
,
1574 ResourceContext
* context
) {
1578 // http://crbug.com/90971
1580 base::strlcpy(url_buf
, url
.spec().c_str(), arraysize(url_buf
));
1581 base::debug::Alias(url_buf
);
1582 CHECK(ContainsKey(active_resource_contexts_
, context
));
1586 const net::URLRequestContext
* request_context
= context
->GetRequestContext();
1588 request_context
->job_factory()->IsHandledURL(url
);
1590 // Since any URLs which have non-standard scheme have been filtered
1591 // by save manager(see GURL::SchemeIsStandard). This situation
1592 // should not happen.
1597 net::CookieStore
* cookie_store
=
1598 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1600 scoped_ptr
<net::URLRequest
> request(
1601 request_context
->CreateRequest(url
, net::DEFAULT_PRIORITY
, NULL
,
1604 request
->set_method("GET");
1605 SetReferrerForRequest(request
.get(), referrer
);
1607 // So far, for saving page, we need fetch content from cache, in the
1608 // future, maybe we can use a configuration to configure this behavior.
1609 request
->SetLoadFlags(net::LOAD_PREFERRING_CACHE
);
1611 // Since we're just saving some resources we need, disallow downloading.
1612 ResourceRequestInfoImpl
* extra_info
=
1613 CreateRequestInfo(child_id
, route_id
, false, context
);
1614 extra_info
->AssociateWithRequest(request
.get()); // Request takes ownership.
1616 scoped_ptr
<ResourceHandler
> handler(
1617 new SaveFileResourceHandler(request
.get(),
1621 save_file_manager_
.get()));
1623 BeginRequestInternal(request
.Pass(), handler
.Pass());
1626 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1627 const GlobalRequestID
& id
) {
1628 GetLoader(id
)->MarkAsTransferring();
1631 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1632 const GlobalRequestID
& id
) {
1633 // Request should still exist and be in the middle of a transfer.
1634 DCHECK(IsTransferredNavigation(id
));
1635 RemovePendingRequest(id
.child_id
, id
.request_id
);
1638 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1639 const GlobalRequestID
& id
) {
1640 ResourceLoader
* loader
= GetLoader(id
);
1641 // The response we were meant to resume could have already been canceled.
1643 loader
->CompleteTransfer();
1646 // The object died, so cancel and detach all requests associated with it except
1647 // for downloads and detachable resources, which belong to the browser process
1648 // even if initiated via a renderer.
1649 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id
) {
1650 CancelRequestsForRoute(child_id
, -1 /* cancel all */);
1651 registered_temp_files_
.erase(child_id
);
1654 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id
,
1656 // Since pending_requests_ is a map, we first build up a list of all of the
1657 // matching requests to be cancelled, and then we cancel them. Since there
1658 // may be more than one request to cancel, we cannot simply hold onto the map
1659 // iterators found in the first loop.
1661 // Find the global ID of all matching elements.
1662 bool any_requests_transferring
= false;
1663 std::vector
<GlobalRequestID
> matching_requests
;
1664 for (LoaderMap::const_iterator i
= pending_loaders_
.begin();
1665 i
!= pending_loaders_
.end(); ++i
) {
1666 if (i
->first
.child_id
!= child_id
)
1669 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
1671 GlobalRequestID
id(child_id
, i
->first
.request_id
);
1672 DCHECK(id
== i
->first
);
1673 // Don't cancel navigations that are expected to live beyond this process.
1674 if (IsTransferredNavigation(id
))
1675 any_requests_transferring
= true;
1676 if (info
->detachable_handler()) {
1677 info
->detachable_handler()->Detach();
1678 } else if (!info
->IsDownload() && !info
->is_stream() &&
1679 !IsTransferredNavigation(id
) &&
1680 (route_id
== -1 || route_id
== info
->GetRouteID())) {
1681 matching_requests
.push_back(id
);
1686 for (size_t i
= 0; i
< matching_requests
.size(); ++i
) {
1687 LoaderMap::iterator iter
= pending_loaders_
.find(matching_requests
[i
]);
1688 // Although every matching request was in pending_requests_ when we built
1689 // matching_requests, it is normal for a matching request to be not found
1690 // in pending_requests_ after we have removed some matching requests from
1691 // pending_requests_. For example, deleting a net::URLRequest that has
1692 // exclusive (write) access to an HTTP cache entry may unblock another
1693 // net::URLRequest that needs exclusive access to the same cache entry, and
1694 // that net::URLRequest may complete and remove itself from
1695 // pending_requests_. So we need to check that iter is not equal to
1696 // pending_requests_.end().
1697 if (iter
!= pending_loaders_
.end())
1698 RemovePendingLoader(iter
);
1701 // Don't clear the blocked loaders or offline policy maps if any of the
1702 // requests in route_id are being transferred to a new process, since those
1703 // maps will be updated with the new route_id after the transfer. Otherwise
1704 // we will lose track of this info when the old route goes away, before the
1705 // new one is created.
1706 if (any_requests_transferring
)
1709 // Now deal with blocked requests if any.
1710 if (route_id
!= -1) {
1711 if (blocked_loaders_map_
.find(GlobalRoutingID(child_id
, route_id
)) !=
1712 blocked_loaders_map_
.end()) {
1713 CancelBlockedRequestsForRoute(child_id
, route_id
);
1716 // We have to do all render views for the process |child_id|.
1717 // Note that we have to do this in 2 passes as we cannot call
1718 // CancelBlockedRequestsForRoute while iterating over
1719 // blocked_loaders_map_, as it modifies it.
1720 std::set
<int> route_ids
;
1721 for (BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.begin();
1722 iter
!= blocked_loaders_map_
.end(); ++iter
) {
1723 if (iter
->first
.child_id
== child_id
)
1724 route_ids
.insert(iter
->first
.route_id
);
1726 for (std::set
<int>::const_iterator iter
= route_ids
.begin();
1727 iter
!= route_ids
.end(); ++iter
) {
1728 CancelBlockedRequestsForRoute(child_id
, *iter
);
1733 // Cancels the request and removes it from the list.
1734 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id
,
1736 LoaderMap::iterator i
= pending_loaders_
.find(
1737 GlobalRequestID(child_id
, request_id
));
1738 if (i
== pending_loaders_
.end()) {
1739 NOTREACHED() << "Trying to remove a request that's not here";
1742 RemovePendingLoader(i
);
1745 void ResourceDispatcherHostImpl::RemovePendingLoader(
1746 const LoaderMap::iterator
& iter
) {
1747 ResourceRequestInfoImpl
* info
= iter
->second
->GetRequestInfo();
1749 // Remove the memory credit that we added when pushing the request onto
1750 // the pending list.
1751 IncrementOutstandingRequestsMemory(-1, *info
);
1753 pending_loaders_
.erase(iter
);
1755 // If we have no more pending requests, then stop the load state monitor
1756 if (pending_loaders_
.empty() && update_load_states_timer_
)
1757 update_load_states_timer_
->Stop();
1760 void ResourceDispatcherHostImpl::CancelRequest(int child_id
,
1762 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1764 // We probably want to remove this warning eventually, but I wanted to be
1765 // able to notice when this happens during initial development since it
1766 // should be rare and may indicate a bug.
1767 DVLOG(1) << "Canceling a request that wasn't found";
1771 RemovePendingRequest(child_id
, request_id
);
1774 ResourceDispatcherHostImpl::OustandingRequestsStats
1775 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1776 const ResourceRequestInfoImpl
& info
) {
1777 OutstandingRequestsStatsMap::iterator entry
=
1778 outstanding_requests_stats_map_
.find(info
.GetChildID());
1779 OustandingRequestsStats stats
= { 0, 0 };
1780 if (entry
!= outstanding_requests_stats_map_
.end())
1781 stats
= entry
->second
;
1785 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1786 const ResourceRequestInfoImpl
& info
,
1787 const OustandingRequestsStats
& stats
) {
1788 if (stats
.memory_cost
== 0 && stats
.num_requests
== 0)
1789 outstanding_requests_stats_map_
.erase(info
.GetChildID());
1791 outstanding_requests_stats_map_
[info
.GetChildID()] = stats
;
1794 ResourceDispatcherHostImpl::OustandingRequestsStats
1795 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1797 const ResourceRequestInfoImpl
& info
) {
1798 DCHECK_EQ(1, abs(count
));
1800 // Retrieve the previous value (defaulting to 0 if not found).
1801 OustandingRequestsStats stats
= GetOutstandingRequestsStats(info
);
1803 // Insert/update the total; delete entries when their count reaches 0.
1804 stats
.memory_cost
+= count
* info
.memory_cost();
1805 DCHECK_GE(stats
.memory_cost
, 0);
1806 UpdateOutstandingRequestsStats(info
, stats
);
1811 ResourceDispatcherHostImpl::OustandingRequestsStats
1812 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1814 ResourceRequestInfoImpl
* info
) {
1815 DCHECK_EQ(1, abs(count
));
1816 num_in_flight_requests_
+= count
;
1818 // Keep track of whether this request is counting toward the number of
1819 // in-flight requests for this process, in case we need to transfer it to
1820 // another process. This should be a toggle.
1821 DCHECK_NE(info
->counted_as_in_flight_request(), count
> 0);
1822 info
->set_counted_as_in_flight_request(count
> 0);
1824 OustandingRequestsStats stats
= GetOutstandingRequestsStats(*info
);
1825 stats
.num_requests
+= count
;
1826 DCHECK_GE(stats
.num_requests
, 0);
1827 UpdateOutstandingRequestsStats(*info
, stats
);
1832 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1833 net::URLRequest
* request
) {
1834 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1835 OustandingRequestsStats stats
= IncrementOutstandingRequestsCount(1, info
);
1837 if (stats
.num_requests
> max_num_in_flight_requests_per_process_
)
1839 if (num_in_flight_requests_
> max_num_in_flight_requests_
)
1845 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1846 net::URLRequest
* request
) {
1847 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1848 IncrementOutstandingRequestsCount(-1, info
);
1851 void ResourceDispatcherHostImpl::BeginNavigationRequest(
1852 ResourceContext
* resource_context
,
1853 int64 frame_tree_node_id
,
1854 const NavigationRequestInfo
& info
,
1855 NavigationURLLoaderImplCore
* loader
) {
1856 // PlzNavigate: BeginNavigationRequest currently should only be used for the
1857 // browser-side navigations project.
1858 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1859 switches::kEnableBrowserSideNavigation
));
1861 ResourceType resource_type
= info
.is_main_frame
?
1862 RESOURCE_TYPE_MAIN_FRAME
: RESOURCE_TYPE_SUB_FRAME
;
1865 // TODO(davidben): Check ShouldServiceRequest here. This is important; it
1866 // needs to be checked relative to the child that /requested/ the
1867 // navigation. It's where file upload checks, etc., come in.
1868 (delegate_
&& !delegate_
->ShouldBeginRequest(
1869 info
.begin_params
.method
,
1870 info
.common_params
.url
,
1872 resource_context
))) {
1873 loader
->NotifyRequestFailed(net::ERR_ABORTED
);
1877 // Save the URL on the stack to help catch URLRequests which outlive their
1878 // URLRequestContexts. See https://crbug.com/90971
1881 url_buf
, info
.common_params
.url
.spec().c_str(), arraysize(url_buf
));
1882 base::debug::Alias(url_buf
);
1883 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1885 const net::URLRequestContext
* request_context
=
1886 resource_context
->GetRequestContext();
1888 int load_flags
= info
.begin_params
.load_flags
;
1889 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
1890 if (info
.is_main_frame
) {
1891 load_flags
|= net::LOAD_MAIN_FRAME
;
1893 load_flags
|= net::LOAD_SUB_FRAME
;
1895 // Add a flag to selectively bypass the data reduction proxy if the resource
1896 // type is not an image.
1897 load_flags
|= net::LOAD_BYPASS_DATA_REDUCTION_PROXY
;
1899 // TODO(davidben): BuildLoadFlagsForRequest includes logic for
1900 // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here?
1902 // Sync loads should have maximum priority and should be the only
1903 // requests that have the ignore limits flag set.
1904 DCHECK(!(load_flags
& net::LOAD_IGNORE_LIMITS
));
1906 // TODO(davidben): OverrideCookieStoreForRenderProcess handling for
1907 // prerender. There may not be a renderer process yet, so we need to use the
1908 // ResourceContext or something.
1909 scoped_ptr
<net::URLRequest
> new_request
;
1910 new_request
= request_context
->CreateRequest(
1911 info
.common_params
.url
, net::HIGHEST
, nullptr, nullptr);
1913 new_request
->set_method(info
.begin_params
.method
);
1914 new_request
->set_first_party_for_cookies(
1915 info
.first_party_for_cookies
);
1916 if (info
.is_main_frame
) {
1917 new_request
->set_first_party_url_policy(
1918 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1921 SetReferrerForRequest(new_request
.get(), info
.common_params
.referrer
);
1923 net::HttpRequestHeaders headers
;
1924 headers
.AddHeadersFromString(info
.begin_params
.headers
);
1925 new_request
->SetExtraRequestHeaders(headers
);
1927 new_request
->SetLoadFlags(load_flags
);
1929 // Resolve elements from request_body and prepare upload data.
1930 if (info
.request_body
.get()) {
1931 storage::BlobStorageContext
* blob_context
= GetBlobStorageContext(
1932 GetChromeBlobStorageContextForResourceContext(resource_context
));
1933 AttachRequestBodyBlobDataHandles(
1934 info
.request_body
.get(),
1936 // TODO(davidben): The FileSystemContext is null here. In the case where
1937 // another renderer requested this navigation, this should be the same
1938 // FileSystemContext passed into ShouldServiceRequest.
1939 new_request
->set_upload(UploadDataStreamBuilder::Build(
1940 info
.request_body
.get(),
1942 nullptr, // file_system_context
1943 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1949 // Make extra info and read footer (contains request ID).
1951 // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so
1952 // that IO thread -> UI thread hops will work.
1953 ResourceRequestInfoImpl
* extra_info
=
1954 new ResourceRequestInfoImpl(
1955 PROCESS_TYPE_BROWSER
,
1958 -1, // request_data.origin_pid,
1960 -1, // request_data.render_frame_id,
1962 info
.parent_is_main_frame
,
1963 -1, // request_data.parent_render_frame_id,
1965 info
.common_params
.transition
,
1966 // should_replace_current_entry. This was only maintained at layer for
1967 // request transfers and isn't needed for browser-side navigations.
1969 false, // is download
1971 info
.common_params
.allow_download
,
1972 info
.begin_params
.has_user_gesture
,
1973 true, // enable_load_timing
1974 false, // enable_upload_progress
1975 false, // do_not_prompt_for_login
1976 info
.common_params
.referrer
.policy
,
1977 // TODO(davidben): This is only used for prerenders. Replace
1978 // is_showing with something for that. Or maybe it just comes from the
1979 // same mechanism as the cookie one.
1980 blink::WebPageVisibilityStateVisible
,
1982 base::WeakPtr
<ResourceMessageFilter
>(), // filter
1984 // Request takes ownership.
1985 extra_info
->AssociateWithRequest(new_request
.get());
1987 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
1988 // Hang on to a reference to ensure the blob is not released prior
1989 // to the job being started.
1990 ChromeBlobStorageContext
* blob_context
=
1991 GetChromeBlobStorageContextForResourceContext(resource_context
);
1992 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1994 blob_context
->context()->GetBlobDataFromPublicURL(new_request
->url()));
1997 // TODO(davidben): Attach ServiceWorkerRequestHandler.
1998 // TODO(michaeln): Help out with this and that.
1999 // TODO(davidben): Attach AppCacheInterceptor.
2001 scoped_ptr
<ResourceHandler
> handler(new NavigationResourceHandler(
2002 new_request
.get(), loader
));
2004 // TODO(davidben): Pass in the appropriate appcache_service. Also fix the
2005 // dependency on child_id/route_id. Those are used by the ResourceScheduler;
2006 // currently it's a no-op.
2007 handler
= AddStandardHandlers(new_request
.get(), resource_type
,
2009 nullptr, // appcache_service
2014 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
2018 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
2019 net::URLRequest
* request
) {
2020 // The following fields should be a minor size contribution (experimentally
2021 // on the order of 100). However since they are variable length, it could
2022 // in theory be a sizeable contribution.
2023 int strings_cost
= request
->extra_request_headers().ToString().size() +
2024 request
->original_url().spec().size() +
2025 request
->referrer().size() +
2026 request
->method().size();
2028 // Note that this expression will typically be dominated by:
2029 // |kAvgBytesPerOutstandingRequest|.
2030 return kAvgBytesPerOutstandingRequest
+ strings_cost
;
2033 void ResourceDispatcherHostImpl::BeginRequestInternal(
2034 scoped_ptr
<net::URLRequest
> request
,
2035 scoped_ptr
<ResourceHandler
> handler
) {
2036 DCHECK(!request
->is_pending());
2037 ResourceRequestInfoImpl
* info
=
2038 ResourceRequestInfoImpl::ForRequest(request
.get());
2040 if ((TimeTicks::Now() - last_user_gesture_time_
) <
2041 TimeDelta::FromMilliseconds(kUserGestureWindowMs
)) {
2042 request
->SetLoadFlags(
2043 request
->load_flags() | net::LOAD_MAYBE_USER_GESTURE
);
2046 // Add the memory estimate that starting this request will consume.
2047 info
->set_memory_cost(CalculateApproximateMemoryCost(request
.get()));
2049 // If enqueing/starting this request will exceed our per-process memory
2050 // bound, abort it right away.
2051 OustandingRequestsStats stats
= IncrementOutstandingRequestsMemory(1, *info
);
2052 if (stats
.memory_cost
> max_outstanding_requests_cost_per_process_
) {
2053 // We call "CancelWithError()" as a way of setting the net::URLRequest's
2054 // status -- it has no effect beyond this, since the request hasn't started.
2055 request
->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES
);
2058 handler
->OnResponseCompleted(request
->status(), std::string(), &defer
);
2060 // TODO(darin): The handler is not ready for us to kill the request. Oops!
2064 IncrementOutstandingRequestsMemory(-1, *info
);
2066 // A ResourceHandler must not outlive its associated URLRequest.
2071 linked_ptr
<ResourceLoader
> loader(
2072 new ResourceLoader(request
.Pass(), handler
.Pass(), this));
2074 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2075 BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.find(id
);
2076 if (iter
!= blocked_loaders_map_
.end()) {
2077 // The request should be blocked.
2078 iter
->second
->push_back(loader
);
2082 StartLoading(info
, loader
);
2085 void ResourceDispatcherHostImpl::StartLoading(
2086 ResourceRequestInfoImpl
* info
,
2087 const linked_ptr
<ResourceLoader
>& loader
) {
2088 // TODO(pkasting): Remove ScopedTracker below once crbug.com/456331 is fixed.
2089 tracked_objects::ScopedTracker
tracking_profile(
2090 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2091 "456331 ResourceDispatcherHostImpl::StartLoading"));
2092 pending_loaders_
[info
->GetGlobalRequestID()] = loader
;
2094 loader
->StartRequest();
2097 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl
* contents
) {
2098 last_user_gesture_time_
= TimeTicks::Now();
2101 net::URLRequest
* ResourceDispatcherHostImpl::GetURLRequest(
2102 const GlobalRequestID
& id
) {
2103 ResourceLoader
* loader
= GetLoader(id
);
2107 return loader
->request();
2111 bool ResourceDispatcherHostImpl::LoadInfoIsMoreInteresting(const LoadInfo
& a
,
2112 const LoadInfo
& b
) {
2113 // Set |*_uploading_size| to be the size of the corresponding upload body if
2114 // it's currently being uploaded.
2116 uint64 a_uploading_size
= 0;
2117 if (a
.load_state
.state
== net::LOAD_STATE_SENDING_REQUEST
)
2118 a_uploading_size
= a
.upload_size
;
2120 uint64 b_uploading_size
= 0;
2121 if (b
.load_state
.state
== net::LOAD_STATE_SENDING_REQUEST
)
2122 b_uploading_size
= b
.upload_size
;
2124 if (a_uploading_size
!= b_uploading_size
)
2125 return a_uploading_size
> b_uploading_size
;
2127 return a
.load_state
.state
> b
.load_state
.state
;
2131 void ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread(
2132 scoped_ptr
<LoadInfoMap
> info_map
) {
2133 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
2134 for (const auto& load_info
: *info_map
) {
2135 RenderViewHostImpl
* view
= RenderViewHostImpl::FromID(
2136 load_info
.first
.child_id
, load_info
.first
.route_id
);
2137 // The view could be gone at this point.
2139 view
->LoadStateChanged(load_info
.second
.url
, load_info
.second
.load_state
,
2140 load_info
.second
.upload_position
,
2141 load_info
.second
.upload_size
);
2146 scoped_ptr
<ResourceDispatcherHostImpl::LoadInfoMap
>
2147 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes() {
2148 // Populate this map with load state changes, and then send them on to the UI
2149 // thread where they can be passed along to the respective RVHs.
2150 scoped_ptr
<LoadInfoMap
> info_map(new LoadInfoMap());
2152 for (const auto& loader
: pending_loaders_
) {
2153 // Also poll for upload progress on this timer and send upload progress ipc
2154 // messages to the plugin process.
2156 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is
2158 tracked_objects::ScopedTracker
tracking_profile1(
2159 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2160 "455952 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes1"));
2161 loader
.second
->ReportUploadProgress();
2164 net::URLRequest
* request
= loader
.second
->request();
2165 net::UploadProgress upload_progress
;
2167 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is
2169 tracked_objects::ScopedTracker
tracking_profile2(
2170 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2171 "455952 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes2"));
2172 upload_progress
= request
->GetUploadProgress();
2175 tracked_objects::ScopedTracker
tracking_profile4(
2176 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2177 "455952 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes4"));
2180 load_info
.url
= request
->url();
2182 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is
2184 tracked_objects::ScopedTracker
tracking_profile3(
2185 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2186 "455952 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes3"));
2187 load_info
.load_state
= request
->GetLoadState();
2189 load_info
.upload_size
= upload_progress
.size();
2190 load_info
.upload_position
= upload_progress
.position();
2192 tracked_objects::ScopedTracker
tracking_profile5(
2193 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2194 "455952 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes5"));
2196 GlobalRoutingID
id(loader
.second
->GetRequestInfo()->GetGlobalRoutingID());
2197 LoadInfoMap::iterator existing
= info_map
->find(id
);
2199 tracked_objects::ScopedTracker
tracking_profile6(
2200 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2201 "455952 ResourceDispatcherHostImpl::GetLoadInfoForAllRoutes6"));
2203 if (existing
== info_map
->end() ||
2204 LoadInfoIsMoreInteresting(load_info
, existing
->second
)) {
2205 (*info_map
)[id
] = load_info
;
2208 return info_map
.Pass();
2211 void ResourceDispatcherHostImpl::UpdateLoadInfo() {
2212 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is
2214 tracked_objects::ScopedTracker
tracking_profile(
2215 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2216 "455952 ResourceDispatcherHostImpl::UpdateLoadInfo"));
2218 scoped_ptr
<LoadInfoMap
> info_map(GetLoadInfoForAllRoutes());
2220 if (info_map
->empty())
2223 BrowserThread::PostTask(
2224 BrowserThread::UI
, FROM_HERE
,
2225 base::Bind(&ResourceDispatcherHostImpl::UpdateLoadInfoOnUIThread
,
2226 base::Passed(&info_map
)));
2229 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id
,
2231 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
2232 GlobalRoutingID
key(child_id
, route_id
);
2233 DCHECK(blocked_loaders_map_
.find(key
) == blocked_loaders_map_
.end()) <<
2234 "BlockRequestsForRoute called multiple time for the same RVH";
2235 blocked_loaders_map_
[key
] = new BlockedLoadersList();
2238 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id
,
2240 ProcessBlockedRequestsForRoute(child_id
, route_id
, false);
2243 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id
,
2245 ProcessBlockedRequestsForRoute(child_id
, route_id
, true);
2248 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
2251 bool cancel_requests
) {
2252 BlockedLoadersMap::iterator iter
= blocked_loaders_map_
.find(
2253 GlobalRoutingID(child_id
, route_id
));
2254 if (iter
== blocked_loaders_map_
.end()) {
2255 // It's possible to reach here if the renderer crashed while an interstitial
2256 // page was showing.
2260 BlockedLoadersList
* loaders
= iter
->second
;
2262 // Removing the vector from the map unblocks any subsequent requests.
2263 blocked_loaders_map_
.erase(iter
);
2265 for (BlockedLoadersList::iterator loaders_iter
= loaders
->begin();
2266 loaders_iter
!= loaders
->end(); ++loaders_iter
) {
2267 linked_ptr
<ResourceLoader
> loader
= *loaders_iter
;
2268 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
2269 if (cancel_requests
) {
2270 IncrementOutstandingRequestsMemory(-1, *info
);
2272 StartLoading(info
, loader
);
2279 ResourceDispatcherHostImpl::HttpAuthRelationType
2280 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
2281 const GURL
& request_url
,
2282 const GURL
& first_party
) {
2283 if (!first_party
.is_valid())
2284 return HTTP_AUTH_RELATION_TOP
;
2286 if (net::registry_controlled_domains::SameDomainOrHost(
2287 first_party
, request_url
,
2288 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
))
2289 return HTTP_AUTH_RELATION_SAME_DOMAIN
;
2291 if (allow_cross_origin_auth_prompt())
2292 return HTTP_AUTH_RELATION_ALLOWED_CROSS
;
2294 return HTTP_AUTH_RELATION_BLOCKED_CROSS
;
2297 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
2298 return allow_cross_origin_auth_prompt_
;
2301 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
2302 const GlobalRequestID
& id
) const {
2303 ResourceLoader
* loader
= GetLoader(id
);
2304 return loader
? loader
->is_transferring() : false;
2307 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(
2308 const GlobalRequestID
& id
) const {
2309 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
2311 LoaderMap::const_iterator i
= pending_loaders_
.find(id
);
2312 if (i
== pending_loaders_
.end())
2315 return i
->second
.get();
2318 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(int child_id
,
2319 int request_id
) const {
2320 return GetLoader(GlobalRequestID(child_id
, request_id
));
2323 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
2324 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2325 DelegateMap::iterator it
= delegate_map_
.find(id
);
2326 if (it
== delegate_map_
.end()) {
2327 it
= delegate_map_
.insert(
2328 std::make_pair(id
, new ObserverList
<ResourceMessageDelegate
>)).first
;
2330 it
->second
->AddObserver(delegate
);
2333 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
2334 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2335 DCHECK(ContainsKey(delegate_map_
, id
));
2336 DelegateMap::iterator it
= delegate_map_
.find(id
);
2337 DCHECK(it
->second
->HasObserver(delegate
));
2338 it
->second
->RemoveObserver(delegate
);
2339 if (!it
->second
->might_have_observers()) {
2341 delegate_map_
.erase(it
);
2345 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
2346 const ResourceHostMsg_Request
& request_data
,
2348 bool is_sync_load
) {
2349 int load_flags
= request_data
.load_flags
;
2351 // Although EV status is irrelevant to sub-frames and sub-resources, we have
2352 // to perform EV certificate verification on all resources because an HTTP
2353 // keep-alive connection created to load a sub-frame or a sub-resource could
2354 // be reused to load a main frame.
2355 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
2356 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
2357 load_flags
|= net::LOAD_MAIN_FRAME
;
2358 } else if (request_data
.resource_type
== RESOURCE_TYPE_SUB_FRAME
) {
2359 load_flags
|= net::LOAD_SUB_FRAME
;
2360 } else if (request_data
.resource_type
== RESOURCE_TYPE_PREFETCH
) {
2361 load_flags
|= net::LOAD_PREFETCH
;
2365 load_flags
|= net::LOAD_IGNORE_LIMITS
;
2367 ChildProcessSecurityPolicyImpl
* policy
=
2368 ChildProcessSecurityPolicyImpl::GetInstance();
2369 if (!policy
->CanSendCookiesForOrigin(child_id
, request_data
.url
)) {
2370 load_flags
|= (net::LOAD_DO_NOT_SEND_COOKIES
|
2371 net::LOAD_DO_NOT_SEND_AUTH_DATA
|
2372 net::LOAD_DO_NOT_SAVE_COOKIES
);
2375 // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only
2376 // allow requesting them if requester has ReadRawCookies permission.
2377 if ((load_flags
& net::LOAD_REPORT_RAW_HEADERS
)
2378 && !policy
->CanReadRawCookies(child_id
)) {
2379 VLOG(1) << "Denied unauthorized request for raw headers";
2380 load_flags
&= ~net::LOAD_REPORT_RAW_HEADERS
;
2383 // Add a flag to selectively bypass the data reduction proxy if the resource
2384 // type is not an image.
2385 if (request_data
.resource_type
!= RESOURCE_TYPE_IMAGE
)
2386 load_flags
|= net::LOAD_BYPASS_DATA_REDUCTION_PROXY
;
2391 } // namespace content