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/stl_util.h"
25 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
26 #include "content/browser/appcache/appcache_interceptor.h"
27 #include "content/browser/appcache/chrome_appcache_service.h"
28 #include "content/browser/cert_store_impl.h"
29 #include "content/browser/child_process_security_policy_impl.h"
30 #include "content/browser/download/download_resource_handler.h"
31 #include "content/browser/download/save_file_manager.h"
32 #include "content/browser/download/save_file_resource_handler.h"
33 #include "content/browser/fileapi/chrome_blob_storage_context.h"
34 #include "content/browser/frame_host/navigation_request_info.h"
35 #include "content/browser/frame_host/navigator.h"
36 #include "content/browser/loader/async_resource_handler.h"
37 #include "content/browser/loader/buffered_resource_handler.h"
38 #include "content/browser/loader/cross_site_resource_handler.h"
39 #include "content/browser/loader/detachable_resource_handler.h"
40 #include "content/browser/loader/navigation_resource_handler.h"
41 #include "content/browser/loader/navigation_url_loader_impl_core.h"
42 #include "content/browser/loader/power_save_block_resource_throttle.h"
43 #include "content/browser/loader/redirect_to_file_resource_handler.h"
44 #include "content/browser/loader/resource_message_filter.h"
45 #include "content/browser/loader/resource_request_info_impl.h"
46 #include "content/browser/loader/stream_resource_handler.h"
47 #include "content/browser/loader/sync_resource_handler.h"
48 #include "content/browser/loader/throttling_resource_handler.h"
49 #include "content/browser/loader/upload_data_stream_builder.h"
50 #include "content/browser/renderer_host/render_view_host_delegate.h"
51 #include "content/browser/renderer_host/render_view_host_impl.h"
52 #include "content/browser/resource_context_impl.h"
53 #include "content/browser/service_worker/service_worker_request_handler.h"
54 #include "content/browser/streams/stream.h"
55 #include "content/browser/streams/stream_context.h"
56 #include "content/browser/streams/stream_registry.h"
57 #include "content/browser/web_contents/web_contents_impl.h"
58 #include "content/common/appcache_interfaces.h"
59 #include "content/common/navigation_params.h"
60 #include "content/common/resource_messages.h"
61 #include "content/common/ssl_status_serialization.h"
62 #include "content/common/view_messages.h"
63 #include "content/public/browser/browser_thread.h"
64 #include "content/public/browser/content_browser_client.h"
65 #include "content/public/browser/download_manager.h"
66 #include "content/public/browser/download_url_parameters.h"
67 #include "content/public/browser/global_request_id.h"
68 #include "content/public/browser/resource_dispatcher_host_delegate.h"
69 #include "content/public/browser/resource_request_details.h"
70 #include "content/public/browser/resource_throttle.h"
71 #include "content/public/browser/stream_handle.h"
72 #include "content/public/browser/stream_info.h"
73 #include "content/public/browser/user_metrics.h"
74 #include "content/public/common/content_switches.h"
75 #include "content/public/common/process_type.h"
76 #include "ipc/ipc_message_macros.h"
77 #include "ipc/ipc_message_start.h"
78 #include "net/base/auth.h"
79 #include "net/base/load_flags.h"
80 #include "net/base/mime_util.h"
81 #include "net/base/net_errors.h"
82 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
83 #include "net/base/request_priority.h"
84 #include "net/base/upload_data_stream.h"
85 #include "net/cert/cert_status_flags.h"
86 #include "net/cookies/cookie_monster.h"
87 #include "net/http/http_response_headers.h"
88 #include "net/http/http_response_info.h"
89 #include "net/ssl/ssl_cert_request_info.h"
90 #include "net/url_request/url_request.h"
91 #include "net/url_request/url_request_context.h"
92 #include "net/url_request/url_request_job_factory.h"
93 #include "storage/browser/blob/blob_data_handle.h"
94 #include "storage/browser/blob/blob_storage_context.h"
95 #include "storage/browser/blob/blob_url_request_job_factory.h"
96 #include "storage/browser/fileapi/file_permission_policy.h"
97 #include "storage/browser/fileapi/file_system_context.h"
98 #include "storage/common/blob/blob_data.h"
99 #include "storage/common/blob/shareable_file_reference.h"
100 #include "url/url_constants.h"
102 #if defined(ENABLE_PLUGINS)
103 #include "content/browser/plugin_service_impl.h"
107 using base::TimeDelta
;
108 using base::TimeTicks
;
109 using storage::ShareableFileReference
;
111 // ----------------------------------------------------------------------------
117 static ResourceDispatcherHostImpl
* g_resource_dispatcher_host
;
119 // The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates
120 const int kUpdateLoadStatesIntervalMsec
= 100;
122 // Maximum byte "cost" of all the outstanding requests for a renderer.
123 // See delcaration of |max_outstanding_requests_cost_per_process_| for details.
124 // This bound is 25MB, which allows for around 6000 outstanding requests.
125 const int kMaxOutstandingRequestsCostPerProcess
= 26214400;
127 // The number of milliseconds after noting a user gesture that we will
128 // tag newly-created URLRequest objects with the
129 // net::LOAD_MAYBE_USER_GESTURE load flag. This is a fairly arbitrary
130 // guess at how long to expect direct impact from a user gesture, but
131 // this should be OK as the load flag is a best-effort thing only,
132 // rather than being intended as fully accurate.
133 const int kUserGestureWindowMs
= 3500;
135 // Ratio of |max_num_in_flight_requests_| that any one renderer is allowed to
136 // use. Arbitrarily chosen.
137 const double kMaxRequestsPerProcessRatio
= 0.45;
139 // TODO(jkarlin): The value is high to reduce the chance of the detachable
140 // request timing out, forcing a blocked second request to open a new connection
141 // and start over. Reduce this value once we have a better idea of what it
142 // should be and once we stop blocking multiple simultaneous requests for the
143 // same resource (see bugs 46104 and 31014).
144 const int kDefaultDetachableCancelDelayMs
= 30000;
146 enum SHA1HistogramTypes
{
147 // SHA-1 is not present in the certificate chain.
148 SHA1_NOT_PRESENT
= 0,
149 // SHA-1 is present in the certificate chain, and the leaf expires on or
150 // after January 1, 2017.
151 SHA1_EXPIRES_AFTER_JANUARY_2017
= 1,
152 // SHA-1 is present in the certificate chain, and the leaf expires on or
153 // after June 1, 2016.
154 SHA1_EXPIRES_AFTER_JUNE_2016
= 2,
155 // SHA-1 is present in the certificate chain, and the leaf expires on or
156 // after January 1, 2016.
157 SHA1_EXPIRES_AFTER_JANUARY_2016
= 3,
158 // SHA-1 is present in the certificate chain, but the leaf expires before
161 // Always keep this at the end.
162 SHA1_HISTOGRAM_TYPES_MAX
,
165 void RecordCertificateHistograms(const net::SSLInfo
& ssl_info
,
166 ResourceType resource_type
) {
167 // The internal representation of the dates for UI treatment of SHA-1.
168 // See http://crbug.com/401365 for details
169 static const int64_t kJanuary2017
= INT64_C(13127702400000000);
170 static const int64_t kJune2016
= INT64_C(13109213000000000);
171 static const int64_t kJanuary2016
= INT64_C(13096080000000000);
173 SHA1HistogramTypes sha1_histogram
= SHA1_NOT_PRESENT
;
174 if (ssl_info
.cert_status
& net::CERT_STATUS_SHA1_SIGNATURE_PRESENT
) {
175 DCHECK(ssl_info
.cert
.get());
176 if (ssl_info
.cert
->valid_expiry() >=
177 base::Time::FromInternalValue(kJanuary2017
)) {
178 sha1_histogram
= SHA1_EXPIRES_AFTER_JANUARY_2017
;
179 } else if (ssl_info
.cert
->valid_expiry() >=
180 base::Time::FromInternalValue(kJune2016
)) {
181 sha1_histogram
= SHA1_EXPIRES_AFTER_JUNE_2016
;
182 } else if (ssl_info
.cert
->valid_expiry() >=
183 base::Time::FromInternalValue(kJanuary2016
)) {
184 sha1_histogram
= SHA1_EXPIRES_AFTER_JANUARY_2016
;
186 sha1_histogram
= SHA1_PRESENT
;
189 if (resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
190 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.MainFrame",
192 SHA1_HISTOGRAM_TYPES_MAX
);
194 UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.Subresource",
196 SHA1_HISTOGRAM_TYPES_MAX
);
200 bool IsDetachableResourceType(ResourceType type
) {
202 case RESOURCE_TYPE_PREFETCH
:
203 case RESOURCE_TYPE_PING
:
210 // Aborts a request before an URLRequest has actually been created.
211 void AbortRequestBeforeItStarts(ResourceMessageFilter
* filter
,
212 IPC::Message
* sync_result
,
215 SyncLoadResult result
;
216 result
.error_code
= net::ERR_ABORTED
;
217 ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result
, result
);
218 filter
->Send(sync_result
);
220 // Tell the renderer that this request was disallowed.
221 ResourceMsg_RequestCompleteData request_complete_data
;
222 request_complete_data
.error_code
= net::ERR_ABORTED
;
223 request_complete_data
.was_ignored_by_handler
= false;
224 request_complete_data
.exists_in_cache
= false;
225 // No security info needed, connection not established.
226 request_complete_data
.completion_time
= base::TimeTicks();
227 request_complete_data
.encoded_data_length
= 0;
228 filter
->Send(new ResourceMsg_RequestComplete(
229 request_id
, request_complete_data
));
233 void SetReferrerForRequest(net::URLRequest
* request
, const Referrer
& referrer
) {
234 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
235 if (!referrer
.url
.is_valid() ||
236 command_line
->HasSwitch(switches::kNoReferrers
)) {
237 request
->SetReferrer(std::string());
239 request
->SetReferrer(referrer
.url
.spec());
242 net::URLRequest::ReferrerPolicy net_referrer_policy
=
243 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
244 switch (referrer
.policy
) {
245 case blink::WebReferrerPolicyAlways
:
246 case blink::WebReferrerPolicyNever
:
247 case blink::WebReferrerPolicyOrigin
:
248 net_referrer_policy
= net::URLRequest::NEVER_CLEAR_REFERRER
;
250 case blink::WebReferrerPolicyNoReferrerWhenDowngrade
:
251 net_referrer_policy
=
252 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
254 case blink::WebReferrerPolicyDefault
:
256 net_referrer_policy
=
257 command_line
->HasSwitch(switches::kReducedReferrerGranularity
)
259 REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
261 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
;
264 request
->set_referrer_policy(net_referrer_policy
);
267 // Consults the RendererSecurity policy to determine whether the
268 // ResourceDispatcherHostImpl should service this request. A request might be
269 // disallowed if the renderer is not authorized to retrieve the request URL or
270 // if the renderer is attempting to upload an unauthorized file.
271 bool ShouldServiceRequest(int process_type
,
273 const ResourceHostMsg_Request
& request_data
,
274 storage::FileSystemContext
* file_system_context
) {
275 if (process_type
== PROCESS_TYPE_PLUGIN
)
278 ChildProcessSecurityPolicyImpl
* policy
=
279 ChildProcessSecurityPolicyImpl::GetInstance();
281 // Check if the renderer is permitted to request the requested URL.
282 if (!policy
->CanRequestURL(child_id
, request_data
.url
)) {
283 VLOG(1) << "Denied unauthorized request for "
284 << request_data
.url
.possibly_invalid_spec();
288 // Check if the renderer is permitted to upload the requested files.
289 if (request_data
.request_body
.get()) {
290 const std::vector
<ResourceRequestBody::Element
>* uploads
=
291 request_data
.request_body
->elements();
292 std::vector
<ResourceRequestBody::Element
>::const_iterator iter
;
293 for (iter
= uploads
->begin(); iter
!= uploads
->end(); ++iter
) {
294 if (iter
->type() == ResourceRequestBody::Element::TYPE_FILE
&&
295 !policy
->CanReadFile(child_id
, iter
->path())) {
296 NOTREACHED() << "Denied unauthorized upload of "
297 << iter
->path().value();
300 if (iter
->type() == ResourceRequestBody::Element::TYPE_FILE_FILESYSTEM
) {
301 storage::FileSystemURL url
=
302 file_system_context
->CrackURL(iter
->filesystem_url());
303 if (!policy
->CanReadFileSystemFile(child_id
, url
)) {
304 NOTREACHED() << "Denied unauthorized upload of "
305 << iter
->filesystem_url().spec();
315 void RemoveDownloadFileFromChildSecurityPolicy(int child_id
,
316 const base::FilePath
& path
) {
317 ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile(
321 DownloadInterruptReason
CallbackAndReturn(
322 const DownloadUrlParameters::OnStartedCallback
& started_cb
,
323 DownloadInterruptReason interrupt_reason
) {
324 if (started_cb
.is_null())
325 return interrupt_reason
;
326 BrowserThread::PostTask(
330 started_cb
, static_cast<DownloadItem
*>(NULL
), interrupt_reason
));
332 return interrupt_reason
;
335 int GetCertID(net::URLRequest
* request
, int child_id
) {
336 if (request
->ssl_info().cert
.get()) {
337 return CertStore::GetInstance()->StoreCert(request
->ssl_info().cert
.get(),
343 void NotifyRedirectOnUI(int render_process_id
,
344 int render_frame_host
,
345 scoped_ptr
<ResourceRedirectDetails
> details
) {
346 RenderFrameHostImpl
* host
=
347 RenderFrameHostImpl::FromID(render_process_id
, render_frame_host
);
348 WebContentsImpl
* web_contents
=
349 static_cast<WebContentsImpl
*>(WebContents::FromRenderFrameHost(host
));
352 web_contents
->DidGetRedirectForResourceRequest(host
, *details
.get());
355 void NotifyResponseOnUI(int render_process_id
,
356 int render_frame_host
,
357 scoped_ptr
<ResourceRequestDetails
> details
) {
358 RenderFrameHostImpl
* host
=
359 RenderFrameHostImpl::FromID(render_process_id
, render_frame_host
);
360 WebContentsImpl
* web_contents
=
361 static_cast<WebContentsImpl
*>(WebContents::FromRenderFrameHost(host
));
364 web_contents
->DidGetResourceResponseStart(*details
.get());
368 const net::SignedCertificateTimestampAndStatus
& sct_status
) {
369 return sct_status
.status
== net::ct::SCT_STATUS_OK
;
372 storage::BlobStorageContext
* GetBlobStorageContext(
373 ChromeBlobStorageContext
* blob_storage_context
) {
374 if (!blob_storage_context
)
376 return blob_storage_context
->context();
379 void AttachRequestBodyBlobDataHandles(
380 ResourceRequestBody
* body
,
381 storage::BlobStorageContext
* blob_context
) {
382 DCHECK(blob_context
);
383 for (size_t i
= 0; i
< body
->elements()->size(); ++i
) {
384 const ResourceRequestBody::Element
& element
= (*body
->elements())[i
];
385 if (element
.type() != ResourceRequestBody::Element::TYPE_BLOB
)
387 scoped_ptr
<storage::BlobDataHandle
> handle
=
388 blob_context
->GetBlobDataFromUUID(element
.blob_uuid());
392 // Ensure the blob and any attached shareable files survive until
393 // upload completion. The |body| takes ownership of |handle|.
394 const void* key
= handle
.get();
395 body
->SetUserData(key
, handle
.release());
400 // This method is called in the UI thread to send the timestamp of a resource
401 // request to the respective Navigator (for an UMA histogram).
402 void LogResourceRequestTimeOnUI(
403 base::TimeTicks timestamp
,
404 int render_process_id
,
407 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
408 RenderFrameHostImpl
* host
=
409 RenderFrameHostImpl::FromID(render_process_id
, render_frame_id
);
411 DCHECK(host
->frame_tree_node()->IsMainFrame());
412 host
->frame_tree_node()->navigator()->LogResourceRequestTime(
420 ResourceDispatcherHost
* ResourceDispatcherHost::Get() {
421 return g_resource_dispatcher_host
;
424 ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
425 : save_file_manager_(new SaveFileManager()),
428 num_in_flight_requests_(0),
429 max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()),
430 max_num_in_flight_requests_per_process_(
432 max_num_in_flight_requests_
* kMaxRequestsPerProcessRatio
)),
433 max_outstanding_requests_cost_per_process_(
434 kMaxOutstandingRequestsCostPerProcess
),
437 allow_cross_origin_auth_prompt_(false) {
438 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
439 DCHECK(!g_resource_dispatcher_host
);
440 g_resource_dispatcher_host
= this;
442 GetContentClient()->browser()->ResourceDispatcherHostCreated();
444 ANNOTATE_BENIGN_RACE(
445 &last_user_gesture_time_
,
446 "We don't care about the precise value, see http://crbug.com/92889");
448 BrowserThread::PostTask(BrowserThread::IO
,
450 base::Bind(&ResourceDispatcherHostImpl::OnInit
,
451 base::Unretained(this)));
453 update_load_states_timer_
.reset(
454 new base::RepeatingTimer
<ResourceDispatcherHostImpl
>());
457 ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() {
458 DCHECK(outstanding_requests_stats_map_
.empty());
459 DCHECK(g_resource_dispatcher_host
);
460 g_resource_dispatcher_host
= NULL
;
464 ResourceDispatcherHostImpl
* ResourceDispatcherHostImpl::Get() {
465 return g_resource_dispatcher_host
;
468 void ResourceDispatcherHostImpl::SetDelegate(
469 ResourceDispatcherHostDelegate
* delegate
) {
470 delegate_
= delegate
;
473 void ResourceDispatcherHostImpl::SetAllowCrossOriginAuthPrompt(bool value
) {
474 allow_cross_origin_auth_prompt_
= value
;
477 void ResourceDispatcherHostImpl::AddResourceContext(ResourceContext
* context
) {
478 active_resource_contexts_
.insert(context
);
481 void ResourceDispatcherHostImpl::RemoveResourceContext(
482 ResourceContext
* context
) {
483 CHECK(ContainsKey(active_resource_contexts_
, context
));
484 active_resource_contexts_
.erase(context
);
487 void ResourceDispatcherHostImpl::ResumeResponseDeferredAtStart(
488 const GlobalRequestID
& id
) {
489 ResourceLoader
* loader
= GetLoader(id
);
491 // The response we were meant to resume could have already been canceled.
492 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
493 if (info
->cross_site_handler())
494 info
->cross_site_handler()->ResumeResponseDeferredAtStart(id
.request_id
);
498 void ResourceDispatcherHostImpl::CancelRequestsForContext(
499 ResourceContext
* context
) {
500 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
503 CHECK(ContainsKey(active_resource_contexts_
, context
));
505 // Note that request cancellation has side effects. Therefore, we gather all
506 // the requests to cancel first, and then we start cancelling. We assert at
507 // the end that there are no more to cancel since the context is about to go
509 typedef std::vector
<linked_ptr
<ResourceLoader
>> LoaderList
;
510 LoaderList loaders_to_cancel
;
512 for (LoaderMap::iterator i
= pending_loaders_
.begin();
513 i
!= pending_loaders_
.end();) {
514 if (i
->second
->GetRequestInfo()->GetContext() == context
) {
515 loaders_to_cancel
.push_back(i
->second
);
516 IncrementOutstandingRequestsMemory(-1, *i
->second
->GetRequestInfo());
517 pending_loaders_
.erase(i
++);
523 for (BlockedLoadersMap::iterator i
= blocked_loaders_map_
.begin();
524 i
!= blocked_loaders_map_
.end();) {
525 BlockedLoadersList
* loaders
= i
->second
;
526 if (loaders
->empty()) {
527 // This can happen if BlockRequestsForRoute() has been called for a route,
528 // but we haven't blocked any matching requests yet.
532 ResourceRequestInfoImpl
* info
= loaders
->front()->GetRequestInfo();
533 if (info
->GetContext() == context
) {
534 blocked_loaders_map_
.erase(i
++);
535 for (BlockedLoadersList::const_iterator it
= loaders
->begin();
536 it
!= loaders
->end(); ++it
) {
537 linked_ptr
<ResourceLoader
> loader
= *it
;
538 info
= loader
->GetRequestInfo();
539 // We make the assumption that all requests on the list have the same
541 DCHECK_EQ(context
, info
->GetContext());
542 IncrementOutstandingRequestsMemory(-1, *info
);
543 loaders_to_cancel
.push_back(loader
);
552 for (LoaderList::iterator i
= loaders_to_cancel
.begin();
553 i
!= loaders_to_cancel
.end(); ++i
) {
554 // There is no strict requirement that this be the case, but currently
555 // downloads, streams, detachable requests, transferred requests, and
556 // browser-owned requests are the only requests that aren't cancelled when
557 // the associated processes go away. It may be OK for this invariant to
558 // change in the future, but if this assertion fires without the invariant
559 // changing, then it's indicative of a leak.
560 DCHECK((*i
)->GetRequestInfo()->IsDownload() ||
561 (*i
)->GetRequestInfo()->is_stream() ||
562 ((*i
)->GetRequestInfo()->detachable_handler() &&
563 (*i
)->GetRequestInfo()->detachable_handler()->is_detached()) ||
564 (*i
)->GetRequestInfo()->GetProcessType() == PROCESS_TYPE_BROWSER
||
565 (*i
)->is_transferring());
569 loaders_to_cancel
.clear();
571 // Validate that no more requests for this context were added.
572 for (LoaderMap::const_iterator i
= pending_loaders_
.begin();
573 i
!= pending_loaders_
.end(); ++i
) {
574 // http://crbug.com/90971
575 CHECK_NE(i
->second
->GetRequestInfo()->GetContext(), context
);
578 for (BlockedLoadersMap::const_iterator i
= blocked_loaders_map_
.begin();
579 i
!= blocked_loaders_map_
.end(); ++i
) {
580 BlockedLoadersList
* loaders
= i
->second
;
581 if (!loaders
->empty()) {
582 ResourceRequestInfoImpl
* info
= loaders
->front()->GetRequestInfo();
583 // http://crbug.com/90971
584 CHECK_NE(info
->GetContext(), context
);
589 DownloadInterruptReason
ResourceDispatcherHostImpl::BeginDownload(
590 scoped_ptr
<net::URLRequest
> request
,
591 const Referrer
& referrer
,
592 bool is_content_initiated
,
593 ResourceContext
* context
,
597 scoped_ptr
<DownloadSaveInfo
> save_info
,
599 const DownloadStartedCallback
& started_callback
) {
601 return CallbackAndReturn(started_callback
,
602 DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN
);
604 const GURL
& url
= request
->original_url();
606 // http://crbug.com/90971
608 base::strlcpy(url_buf
, url
.spec().c_str(), arraysize(url_buf
));
609 base::debug::Alias(url_buf
);
610 CHECK(ContainsKey(active_resource_contexts_
, context
));
612 SetReferrerForRequest(request
.get(), referrer
);
614 int extra_load_flags
= net::LOAD_IS_DOWNLOAD
;
616 // If there is upload data attached, only retrieve from cache because there
617 // is no current mechanism to prompt the user for their consent for a
618 // re-post. For GETs, try to retrieve data from the cache and skip
619 // validating the entry if present.
620 if (request
->get_upload() != NULL
)
621 extra_load_flags
|= net::LOAD_ONLY_FROM_CACHE
;
623 extra_load_flags
|= net::LOAD_PREFERRING_CACHE
;
625 extra_load_flags
|= net::LOAD_DISABLE_CACHE
;
627 request
->SetLoadFlags(request
->load_flags() | extra_load_flags
);
629 // We treat a download as a main frame load, and thus update the policy URL on
632 // TODO(davidben): Is this correct? If this came from a
633 // ViewHostMsg_DownloadUrl in a frame, should it have first-party URL set
635 request
->set_first_party_url_policy(
636 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
638 // Check if the renderer is permitted to request the requested URL.
639 if (!ChildProcessSecurityPolicyImpl::GetInstance()->
640 CanRequestURL(child_id
, url
)) {
641 VLOG(1) << "Denied unauthorized download request for "
642 << url
.possibly_invalid_spec();
643 return CallbackAndReturn(started_callback
,
644 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST
);
649 const net::URLRequestContext
* request_context
= context
->GetRequestContext();
650 if (!request_context
->job_factory()->IsHandledURL(url
)) {
651 VLOG(1) << "Download request for unsupported protocol: "
652 << url
.possibly_invalid_spec();
653 return CallbackAndReturn(started_callback
,
654 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST
);
657 ResourceRequestInfoImpl
* extra_info
=
658 CreateRequestInfo(child_id
, route_id
, true, context
);
659 extra_info
->AssociateWithRequest(request
.get()); // Request takes ownership.
661 if (request
->url().SchemeIs(url::kBlobScheme
)) {
662 ChromeBlobStorageContext
* blob_context
=
663 GetChromeBlobStorageContextForResourceContext(context
);
664 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
666 blob_context
->context()->GetBlobDataFromPublicURL(request
->url()));
669 // From this point forward, the |DownloadResourceHandler| is responsible for
670 // |started_callback|.
671 scoped_ptr
<ResourceHandler
> handler(
672 CreateResourceHandlerForDownload(request
.get(), is_content_initiated
,
673 true, download_id
, save_info
.Pass(),
676 BeginRequestInternal(request
.Pass(), handler
.Pass());
678 return DOWNLOAD_INTERRUPT_REASON_NONE
;
681 void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest(
682 net::URLRequest
* request
) {
683 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
685 ResourceLoader
* loader
= GetLoader(info
->GetGlobalRequestID());
687 loader
->ClearLoginDelegate();
691 void ResourceDispatcherHostImpl::Shutdown() {
692 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
693 BrowserThread::PostTask(BrowserThread::IO
,
695 base::Bind(&ResourceDispatcherHostImpl::OnShutdown
,
696 base::Unretained(this)));
699 scoped_ptr
<ResourceHandler
>
700 ResourceDispatcherHostImpl::CreateResourceHandlerForDownload(
701 net::URLRequest
* request
,
702 bool is_content_initiated
,
705 scoped_ptr
<DownloadSaveInfo
> save_info
,
706 const DownloadUrlParameters::OnStartedCallback
& started_cb
) {
707 scoped_ptr
<ResourceHandler
> handler(
708 new DownloadResourceHandler(id
, request
, started_cb
, save_info
.Pass()));
710 const ResourceRequestInfo
* request_info(
711 ResourceRequestInfo::ForRequest(request
));
713 ScopedVector
<ResourceThrottle
> throttles
;
714 delegate_
->DownloadStarting(
715 request
, request_info
->GetContext(), request_info
->GetChildID(),
716 request_info
->GetRouteID(), request_info
->GetRequestID(),
717 is_content_initiated
, must_download
, &throttles
);
718 if (!throttles
.empty()) {
720 new ThrottlingResourceHandler(
721 handler
.Pass(), request
, throttles
.Pass()));
724 return handler
.Pass();
727 scoped_ptr
<ResourceHandler
>
728 ResourceDispatcherHostImpl::MaybeInterceptAsStream(net::URLRequest
* request
,
729 ResourceResponse
* response
,
730 std::string
* payload
) {
731 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
732 const std::string
& mime_type
= response
->head
.mime_type
;
736 !delegate_
->ShouldInterceptResourceAsStream(request
,
740 return scoped_ptr
<ResourceHandler
>();
743 StreamContext
* stream_context
=
744 GetStreamContextForResourceContext(info
->GetContext());
746 scoped_ptr
<StreamResourceHandler
> handler(
747 new StreamResourceHandler(request
,
748 stream_context
->registry(),
751 info
->set_is_stream(true);
752 scoped_ptr
<StreamInfo
> stream_info(new StreamInfo
);
753 stream_info
->handle
= handler
->stream()->CreateHandle();
754 stream_info
->original_url
= request
->url();
755 stream_info
->mime_type
= mime_type
;
756 // Make a copy of the response headers so it is safe to pass across threads;
757 // the old handler (AsyncResourceHandler) may modify it in parallel via the
758 // ResourceDispatcherHostDelegate.
759 if (response
->head
.headers
.get()) {
760 stream_info
->response_headers
=
761 new net::HttpResponseHeaders(response
->head
.headers
->raw_headers());
763 delegate_
->OnStreamCreated(request
, stream_info
.Pass());
764 return handler
.Pass();
767 ResourceDispatcherHostLoginDelegate
*
768 ResourceDispatcherHostImpl::CreateLoginDelegate(
769 ResourceLoader
* loader
,
770 net::AuthChallengeInfo
* auth_info
) {
774 return delegate_
->CreateLoginDelegate(auth_info
, loader
->request());
777 bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader
* loader
,
782 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
784 if (!IsResourceTypeFrame(info
->GetResourceType()))
787 const net::URLRequestJobFactory
* job_factory
=
788 info
->GetContext()->GetRequestContext()->job_factory();
789 if (job_factory
->IsHandledURL(url
))
792 return delegate_
->HandleExternalProtocol(
793 url
, info
->GetChildID(), info
->GetRouteID());
796 void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader
* loader
) {
797 // Make sure we have the load state monitor running
798 if (!update_load_states_timer_
->IsRunning()) {
799 update_load_states_timer_
->Start(FROM_HERE
,
800 TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec
),
801 this, &ResourceDispatcherHostImpl::UpdateLoadStates
);
805 void ResourceDispatcherHostImpl::DidReceiveRedirect(ResourceLoader
* loader
,
806 const GURL
& new_url
) {
807 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
809 int render_process_id
, render_frame_host
;
810 if (!info
->GetAssociatedRenderFrame(&render_process_id
, &render_frame_host
))
813 // Notify the observers on the UI thread.
814 scoped_ptr
<ResourceRedirectDetails
> detail(new ResourceRedirectDetails(
816 GetCertID(loader
->request(), info
->GetChildID()),
818 BrowserThread::PostTask(
819 BrowserThread::UI
, FROM_HERE
,
822 render_process_id
, render_frame_host
, base::Passed(&detail
)));
825 void ResourceDispatcherHostImpl::DidReceiveResponse(ResourceLoader
* loader
) {
826 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
828 if (loader
->request()->was_fetched_via_proxy() &&
829 loader
->request()->was_fetched_via_spdy() &&
830 loader
->request()->url().SchemeIs(url::kHttpScheme
)) {
831 scheduler_
->OnReceivedSpdyProxiedHttpResponse(
832 info
->GetChildID(), info
->GetRouteID());
835 int render_process_id
, render_frame_host
;
836 if (!info
->GetAssociatedRenderFrame(&render_process_id
, &render_frame_host
))
839 // Notify the observers on the UI thread.
840 scoped_ptr
<ResourceRequestDetails
> detail(new ResourceRequestDetails(
842 GetCertID(loader
->request(), info
->GetChildID())));
843 BrowserThread::PostTask(
844 BrowserThread::UI
, FROM_HERE
,
847 render_process_id
, render_frame_host
, base::Passed(&detail
)));
850 void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader
* loader
) {
851 ResourceRequestInfo
* info
= loader
->GetRequestInfo();
853 // Record final result of all resource loads.
854 if (info
->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME
) {
855 // This enumeration has "3" appended to its name to distinguish it from
857 UMA_HISTOGRAM_SPARSE_SLOWLY(
858 "Net.ErrorCodesForMainFrame3",
859 -loader
->request()->status().error());
861 if (loader
->request()->url().SchemeIsSecure()) {
862 if (loader
->request()->url().host() == "www.google.com") {
863 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2",
864 -loader
->request()->status().error());
867 int num_valid_scts
= std::count_if(
868 loader
->request()->ssl_info().signed_certificate_timestamps
.begin(),
869 loader
->request()->ssl_info().signed_certificate_timestamps
.end(),
871 UMA_HISTOGRAM_COUNTS_100(
872 "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts
);
875 if (info
->GetResourceType() == RESOURCE_TYPE_IMAGE
) {
876 UMA_HISTOGRAM_SPARSE_SLOWLY(
877 "Net.ErrorCodesForImages",
878 -loader
->request()->status().error());
880 // This enumeration has "2" appended to distinguish it from older versions.
881 UMA_HISTOGRAM_SPARSE_SLOWLY(
882 "Net.ErrorCodesForSubresources2",
883 -loader
->request()->status().error());
886 if (loader
->request()->url().SchemeIsSecure()) {
887 RecordCertificateHistograms(loader
->request()->ssl_info(),
888 info
->GetResourceType());
892 delegate_
->RequestComplete(loader
->request());
894 // Destroy the ResourceLoader.
895 RemovePendingRequest(info
->GetChildID(), info
->GetRequestID());
898 void ResourceDispatcherHostImpl::OnInit() {
899 scheduler_
.reset(new ResourceScheduler
);
902 void ResourceDispatcherHostImpl::OnShutdown() {
903 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
906 pending_loaders_
.clear();
908 // Make sure we shutdown the timer now, otherwise by the time our destructor
909 // runs if the timer is still running the Task is deleted twice (once by
910 // the MessageLoop and the second time by RepeatingTimer).
911 update_load_states_timer_
.reset();
913 // Clear blocked requests if any left.
914 // Note that we have to do this in 2 passes as we cannot call
915 // CancelBlockedRequestsForRoute while iterating over
916 // blocked_loaders_map_, as it modifies it.
917 std::set
<GlobalRoutingID
> ids
;
918 for (BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.begin();
919 iter
!= blocked_loaders_map_
.end(); ++iter
) {
920 std::pair
<std::set
<GlobalRoutingID
>::iterator
, bool> result
=
921 ids
.insert(iter
->first
);
922 // We should not have duplicates.
923 DCHECK(result
.second
);
925 for (std::set
<GlobalRoutingID
>::const_iterator iter
= ids
.begin();
926 iter
!= ids
.end(); ++iter
) {
927 CancelBlockedRequestsForRoute(iter
->child_id
, iter
->route_id
);
933 bool ResourceDispatcherHostImpl::OnMessageReceived(
934 const IPC::Message
& message
,
935 ResourceMessageFilter
* filter
) {
938 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcherHostImpl
, message
)
939 IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource
, OnRequestResource
)
940 IPC_MESSAGE_HANDLER_DELAY_REPLY(ResourceHostMsg_SyncLoad
, OnSyncLoad
)
941 IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile
,
942 OnReleaseDownloadedFile
)
943 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataDownloaded_ACK
, OnDataDownloadedACK
)
944 IPC_MESSAGE_HANDLER(ResourceHostMsg_UploadProgress_ACK
, OnUploadProgressACK
)
945 IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest
, OnCancelRequest
)
946 IPC_MESSAGE_UNHANDLED(handled
= false)
947 IPC_END_MESSAGE_MAP()
949 if (!handled
&& IPC_MESSAGE_ID_CLASS(message
.type()) == ResourceMsgStart
) {
950 PickleIterator
iter(message
);
952 bool ok
= iter
.ReadInt(&request_id
);
954 GlobalRequestID
id(filter_
->child_id(), request_id
);
955 DelegateMap::iterator it
= delegate_map_
.find(id
);
956 if (it
!= delegate_map_
.end()) {
957 ObserverList
<ResourceMessageDelegate
>::Iterator
del_it(*it
->second
);
958 ResourceMessageDelegate
* delegate
;
959 while (!handled
&& (delegate
= del_it
.GetNext()) != NULL
) {
960 handled
= delegate
->OnMessageReceived(message
);
964 // As the unhandled resource message effectively has no consumer, mark it as
965 // handled to prevent needless propagation through the filter pipeline.
973 void ResourceDispatcherHostImpl::OnRequestResource(
976 const ResourceHostMsg_Request
& request_data
) {
977 // When logging time-to-network only care about main frame and non-transfer
979 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
&&
980 request_data
.transferred_request_request_id
== -1) {
981 BrowserThread::PostTask(
984 base::Bind(&LogResourceRequestTimeOnUI
,
987 request_data
.render_frame_id
,
990 BeginRequest(request_id
, request_data
, NULL
, routing_id
);
993 // Begins a resource request with the given params on behalf of the specified
994 // child process. Responses will be dispatched through the given receiver. The
995 // process ID is used to lookup WebContentsImpl from routing_id's in the case of
996 // a request from a renderer. request_context is the cookie/cache context to be
997 // used for this request.
999 // If sync_result is non-null, then a SyncLoad reply will be generated, else
1000 // a normal asynchronous set of response messages will be generated.
1001 void ResourceDispatcherHostImpl::OnSyncLoad(
1003 const ResourceHostMsg_Request
& request_data
,
1004 IPC::Message
* sync_result
) {
1005 BeginRequest(request_id
, request_data
, sync_result
,
1006 sync_result
->routing_id());
1009 void ResourceDispatcherHostImpl::UpdateRequestForTransfer(
1013 const ResourceHostMsg_Request
& request_data
,
1014 const linked_ptr
<ResourceLoader
>& loader
) {
1015 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
1016 GlobalRoutingID
old_routing_id(
1017 request_data
.transferred_request_child_id
, info
->GetRouteID());
1018 GlobalRequestID
old_request_id(request_data
.transferred_request_child_id
,
1019 request_data
.transferred_request_request_id
);
1020 GlobalRoutingID
new_routing_id(child_id
, route_id
);
1021 GlobalRequestID
new_request_id(child_id
, request_id
);
1023 // Clear out data that depends on |info| before updating it.
1024 // We always need to move the memory stats to the new process. In contrast,
1025 // stats.num_requests is only tracked for some requests (those that require
1026 // file descriptors for their shared memory buffer).
1027 IncrementOutstandingRequestsMemory(-1, *info
);
1028 bool should_update_count
= info
->counted_as_in_flight_request();
1029 if (should_update_count
)
1030 IncrementOutstandingRequestsCount(-1, info
);
1031 pending_loaders_
.erase(old_request_id
);
1033 // ResourceHandlers should always get state related to the request from the
1034 // ResourceRequestInfo rather than caching it locally. This lets us update
1035 // the info object when a transfer occurs.
1036 info
->UpdateForTransfer(child_id
, route_id
, request_data
.origin_pid
,
1037 request_id
, request_data
.parent_render_frame_id
,
1038 filter_
->GetWeakPtr());
1040 // Update maps that used the old IDs, if necessary. Some transfers in tests
1041 // do not actually use a different ID, so not all maps need to be updated.
1042 pending_loaders_
[new_request_id
] = loader
;
1043 IncrementOutstandingRequestsMemory(1, *info
);
1044 if (should_update_count
)
1045 IncrementOutstandingRequestsCount(1, info
);
1046 if (old_routing_id
!= new_routing_id
) {
1047 if (blocked_loaders_map_
.find(old_routing_id
) !=
1048 blocked_loaders_map_
.end()) {
1049 blocked_loaders_map_
[new_routing_id
] =
1050 blocked_loaders_map_
[old_routing_id
];
1051 blocked_loaders_map_
.erase(old_routing_id
);
1054 if (old_request_id
!= new_request_id
) {
1055 DelegateMap::iterator it
= delegate_map_
.find(old_request_id
);
1056 if (it
!= delegate_map_
.end()) {
1057 // Tell each delegate that the request ID has changed.
1058 ObserverList
<ResourceMessageDelegate
>::Iterator
del_it(*it
->second
);
1059 ResourceMessageDelegate
* delegate
;
1060 while ((delegate
= del_it
.GetNext()) != NULL
) {
1061 delegate
->set_request_id(new_request_id
);
1063 // Now store the observer list under the new request ID.
1064 delegate_map_
[new_request_id
] = delegate_map_
[old_request_id
];
1065 delegate_map_
.erase(old_request_id
);
1069 AppCacheInterceptor::CompleteCrossSiteTransfer(
1072 request_data
.appcache_host_id
);
1074 // We should have a CrossSiteResourceHandler to finish the transfer.
1075 DCHECK(info
->cross_site_handler());
1078 void ResourceDispatcherHostImpl::BeginRequest(
1080 const ResourceHostMsg_Request
& request_data
,
1081 IPC::Message
* sync_result
, // only valid for sync
1083 int process_type
= filter_
->process_type();
1084 int child_id
= filter_
->child_id();
1086 // Reject invalid priority.
1087 if (request_data
.priority
< net::MINIMUM_PRIORITY
||
1088 request_data
.priority
> net::MAXIMUM_PRIORITY
) {
1089 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1090 filter_
->BadMessageReceived();
1094 // If we crash here, figure out what URL the renderer was requesting.
1095 // http://crbug.com/91398
1097 base::strlcpy(url_buf
, request_data
.url
.spec().c_str(), arraysize(url_buf
));
1098 base::debug::Alias(url_buf
);
1100 // If the request that's coming in is being transferred from another process,
1101 // we want to reuse and resume the old loader rather than start a new one.
1103 LoaderMap::iterator it
= pending_loaders_
.find(
1104 GlobalRequestID(request_data
.transferred_request_child_id
,
1105 request_data
.transferred_request_request_id
));
1106 if (it
!= pending_loaders_
.end()) {
1107 // If the request is transferring to a new process, we can update our
1108 // state and let it resume with its existing ResourceHandlers.
1109 if (it
->second
->is_transferring()) {
1110 linked_ptr
<ResourceLoader
> deferred_loader
= it
->second
;
1111 UpdateRequestForTransfer(child_id
, route_id
, request_id
,
1112 request_data
, deferred_loader
);
1114 deferred_loader
->CompleteTransfer();
1116 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1117 filter_
->BadMessageReceived();
1123 ResourceContext
* resource_context
= NULL
;
1124 net::URLRequestContext
* request_context
= NULL
;
1125 filter_
->GetContexts(request_data
, &resource_context
, &request_context
);
1126 // http://crbug.com/90971
1127 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1130 !ShouldServiceRequest(process_type
, child_id
, request_data
,
1131 filter_
->file_system_context())) {
1132 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1136 // Allow the observer to block/handle the request.
1137 if (delegate_
&& !delegate_
->ShouldBeginRequest(request_data
.method
,
1139 request_data
.resource_type
,
1140 resource_context
)) {
1141 AbortRequestBeforeItStarts(filter_
, sync_result
, request_id
);
1145 bool is_sync_load
= sync_result
!= NULL
;
1147 BuildLoadFlagsForRequest(request_data
, child_id
, is_sync_load
);
1149 // Sync loads should have maximum priority and should be the only
1150 // requets that have the ignore limits flag set.
1152 DCHECK_EQ(request_data
.priority
, net::MAXIMUM_PRIORITY
);
1153 DCHECK_NE(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1155 DCHECK_EQ(load_flags
& net::LOAD_IGNORE_LIMITS
, 0);
1158 // Construct the request.
1159 net::CookieStore
* cookie_store
=
1160 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1162 scoped_ptr
<net::URLRequest
> new_request
;
1163 new_request
= request_context
->CreateRequest(
1164 request_data
.url
, request_data
.priority
, NULL
, cookie_store
);
1166 new_request
->set_method(request_data
.method
);
1167 new_request
->set_first_party_for_cookies(
1168 request_data
.first_party_for_cookies
);
1170 // If the request is a MAIN_FRAME request, the first-party URL gets updated on
1172 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
1173 new_request
->set_first_party_url_policy(
1174 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1177 const Referrer
referrer(request_data
.referrer
, request_data
.referrer_policy
);
1178 SetReferrerForRequest(new_request
.get(), referrer
);
1180 net::HttpRequestHeaders headers
;
1181 headers
.AddHeadersFromString(request_data
.headers
);
1182 new_request
->SetExtraRequestHeaders(headers
);
1184 new_request
->SetLoadFlags(load_flags
);
1186 storage::BlobStorageContext
* blob_context
=
1187 GetBlobStorageContext(filter_
->blob_storage_context());
1188 // Resolve elements from request_body and prepare upload data.
1189 if (request_data
.request_body
.get()) {
1190 // |blob_context| could be null when the request is from the plugins because
1191 // ResourceMessageFilters created in PluginProcessHost don't have the blob
1194 // Attaches the BlobDataHandles to request_body not to free the blobs and
1195 // any attached shareable files until upload completion. These data will
1196 // be used in UploadDataStream and ServiceWorkerURLRequestJob.
1197 AttachRequestBodyBlobDataHandles(
1198 request_data
.request_body
.get(),
1201 new_request
->set_upload(UploadDataStreamBuilder::Build(
1202 request_data
.request_body
.get(),
1204 filter_
->file_system_context(),
1205 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1209 bool allow_download
= request_data
.allow_download
&&
1210 IsResourceTypeFrame(request_data
.resource_type
);
1212 // Make extra info and read footer (contains request ID).
1213 ResourceRequestInfoImpl
* extra_info
=
1214 new ResourceRequestInfoImpl(
1218 request_data
.origin_pid
,
1220 request_data
.render_frame_id
,
1221 request_data
.is_main_frame
,
1222 request_data
.parent_is_main_frame
,
1223 request_data
.parent_render_frame_id
,
1224 request_data
.resource_type
,
1225 request_data
.transition_type
,
1226 request_data
.should_replace_current_entry
,
1227 false, // is download
1230 request_data
.has_user_gesture
,
1231 request_data
.enable_load_timing
,
1232 request_data
.enable_upload_progress
,
1233 request_data
.referrer_policy
,
1234 request_data
.visiblity_state
,
1236 filter_
->GetWeakPtr(),
1238 // Request takes ownership.
1239 extra_info
->AssociateWithRequest(new_request
.get());
1241 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
1242 // Hang on to a reference to ensure the blob is not released prior
1243 // to the job being started.
1244 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1246 filter_
->blob_storage_context()->context()->GetBlobDataFromPublicURL(
1247 new_request
->url()));
1250 // Initialize the service worker handler for the request. We don't use
1251 // ServiceWorker for synchronous loads to avoid renderer deadlocks. We
1252 // don't use ServiceWorker for favicons to avoid cache tainting.
1253 bool is_favicon_load
= request_data
.resource_type
== RESOURCE_TYPE_FAVICON
;
1254 ServiceWorkerRequestHandler::InitializeHandler(
1256 filter_
->service_worker_context(),
1259 request_data
.service_worker_provider_id
,
1260 request_data
.skip_service_worker
|| is_sync_load
|| is_favicon_load
,
1261 request_data
.fetch_request_mode
,
1262 request_data
.fetch_credentials_mode
,
1263 request_data
.resource_type
,
1264 request_data
.fetch_request_context_type
,
1265 request_data
.fetch_frame_type
,
1266 request_data
.request_body
);
1268 // Have the appcache associate its extra info with the request.
1269 AppCacheInterceptor::SetExtraRequestInfo(
1270 new_request
.get(), filter_
->appcache_service(), child_id
,
1271 request_data
.appcache_host_id
, request_data
.resource_type
);
1273 scoped_ptr
<ResourceHandler
> handler(
1274 CreateResourceHandler(
1276 request_data
, sync_result
, route_id
, process_type
, child_id
,
1280 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
1283 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::CreateResourceHandler(
1284 net::URLRequest
* request
,
1285 const ResourceHostMsg_Request
& request_data
,
1286 IPC::Message
* sync_result
,
1290 ResourceContext
* resource_context
) {
1291 // Construct the IPC resource handler.
1292 scoped_ptr
<ResourceHandler
> handler
;
1294 // download_to_file is not supported for synchronous requests.
1295 if (request_data
.download_to_file
) {
1296 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1297 filter_
->BadMessageReceived();
1298 return scoped_ptr
<ResourceHandler
>();
1301 handler
.reset(new SyncResourceHandler(request
, sync_result
, this));
1303 handler
.reset(new AsyncResourceHandler(request
, this));
1305 // The RedirectToFileResourceHandler depends on being next in the chain.
1306 if (request_data
.download_to_file
) {
1308 new RedirectToFileResourceHandler(handler
.Pass(), request
));
1312 // Prefetches and <a ping> requests outlive their child process.
1313 if (!sync_result
&& IsDetachableResourceType(request_data
.resource_type
)) {
1314 handler
.reset(new DetachableResourceHandler(
1316 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs
),
1320 // PlzNavigate: If using --enable-browser-side-navigation, the
1321 // CrossSiteResourceHandler is not needed. This codepath is not used for the
1322 // actual navigation request, but only the subsequent blob URL load. This does
1323 // not require request transfers.
1324 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1325 switches::kEnableBrowserSideNavigation
)) {
1326 // Install a CrossSiteResourceHandler for all main frame requests. This will
1327 // check whether a transfer is required and, if so, pause for the UI thread
1328 // to drive the transfer.
1329 bool is_swappable_navigation
=
1330 request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
;
1331 // If we are using --site-per-process, install it for subframes as well.
1332 if (!is_swappable_navigation
&&
1333 base::CommandLine::ForCurrentProcess()->HasSwitch(
1334 switches::kSitePerProcess
)) {
1335 is_swappable_navigation
=
1336 request_data
.resource_type
== RESOURCE_TYPE_SUB_FRAME
;
1338 if (is_swappable_navigation
&& process_type
== PROCESS_TYPE_RENDERER
)
1339 handler
.reset(new CrossSiteResourceHandler(handler
.Pass(), request
));
1342 return AddStandardHandlers(request
, request_data
.resource_type
,
1343 resource_context
, filter_
->appcache_service(),
1344 child_id
, route_id
, handler
.Pass());
1347 scoped_ptr
<ResourceHandler
> ResourceDispatcherHostImpl::AddStandardHandlers(
1348 net::URLRequest
* request
,
1349 ResourceType resource_type
,
1350 ResourceContext
* resource_context
,
1351 AppCacheService
* appcache_service
,
1354 scoped_ptr
<ResourceHandler
> handler
) {
1355 // Insert a buffered event handler before the actual one.
1357 new BufferedResourceHandler(handler
.Pass(), this, request
));
1359 ScopedVector
<ResourceThrottle
> throttles
;
1361 delegate_
->RequestBeginning(request
,
1368 if (request
->has_upload()) {
1369 // Block power save while uploading data.
1370 throttles
.push_back(new PowerSaveBlockResourceThrottle());
1373 throttles
.push_back(
1374 scheduler_
->ScheduleRequest(child_id
, route_id
, request
).release());
1377 new ThrottlingResourceHandler(handler
.Pass(), request
, throttles
.Pass()));
1379 return handler
.Pass();
1382 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id
) {
1383 UnregisterDownloadedTempFile(filter_
->child_id(), request_id
);
1386 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id
) {
1387 // TODO(michaeln): maybe throttle DataDownloaded messages
1390 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1391 int child_id
, int request_id
, const base::FilePath
& file_path
) {
1392 scoped_refptr
<ShareableFileReference
> reference
=
1393 ShareableFileReference::Get(file_path
);
1394 DCHECK(reference
.get());
1396 registered_temp_files_
[child_id
][request_id
] = reference
;
1397 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1398 child_id
, reference
->path());
1400 // When the temp file is deleted, revoke permissions that the renderer has
1401 // to that file. This covers an edge case where the file is deleted and then
1402 // the same name is re-used for some other purpose, we don't want the old
1403 // renderer to still have access to it.
1405 // We do this when the file is deleted because the renderer can take a blob
1406 // reference to the temp file that outlives the url loaded that it was
1407 // loaded with to keep the file (and permissions) alive.
1408 reference
->AddFinalReleaseCallback(
1409 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy
,
1413 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1414 int child_id
, int request_id
) {
1415 DeletableFilesMap
& map
= registered_temp_files_
[child_id
];
1416 DeletableFilesMap::iterator found
= map
.find(request_id
);
1417 if (found
== map
.end())
1422 // Note that we don't remove the security bits here. This will be done
1423 // when all file refs are deleted (see RegisterDownloadedTempFile).
1426 bool ResourceDispatcherHostImpl::Send(IPC::Message
* message
) {
1431 void ResourceDispatcherHostImpl::OnUploadProgressACK(int request_id
) {
1432 ResourceLoader
* loader
= GetLoader(filter_
->child_id(), request_id
);
1434 loader
->OnUploadProgressACK();
1437 // Note that this cancel is subtly different from the other
1438 // CancelRequest methods in this file, which also tear down the loader.
1439 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id
) {
1440 int child_id
= filter_
->child_id();
1442 // When the old renderer dies, it sends a message to us to cancel its
1444 if (IsTransferredNavigation(GlobalRequestID(child_id
, request_id
)))
1447 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1449 // We probably want to remove this warning eventually, but I wanted to be
1450 // able to notice when this happens during initial development since it
1451 // should be rare and may indicate a bug.
1452 DVLOG(1) << "Canceling a request that wasn't found";
1456 loader
->CancelRequest(true);
1459 ResourceRequestInfoImpl
* ResourceDispatcherHostImpl::CreateRequestInfo(
1463 ResourceContext
* context
) {
1464 return new ResourceRequestInfoImpl(
1465 PROCESS_TYPE_RENDERER
,
1470 MSG_ROUTING_NONE
, // render_frame_id
1471 false, // is_main_frame
1472 false, // parent_is_main_frame
1473 -1, // parent_render_frame_id
1474 RESOURCE_TYPE_SUB_RESOURCE
,
1475 ui::PAGE_TRANSITION_LINK
,
1476 false, // should_replace_current_entry
1477 download
, // is_download
1479 download
, // allow_download
1480 false, // has_user_gesture
1481 false, // enable_load_timing
1482 false, // enable_upload_progress
1483 blink::WebReferrerPolicyDefault
,
1484 blink::WebPageVisibilityStateVisible
,
1486 base::WeakPtr
<ResourceMessageFilter
>(), // filter
1490 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(int child_id
,
1494 scheduler_
->OnClientCreated(child_id
, route_id
, is_visible
, is_audible
);
1497 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1500 scheduler_
->OnClientDeleted(child_id
, route_id
);
1501 CancelRequestsForRoute(child_id
, route_id
);
1504 void ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading(int child_id
,
1507 scheduler_
->OnLoadingStateChanged(child_id
, route_id
, !is_loading
);
1510 void ResourceDispatcherHostImpl::OnRenderViewHostWasHidden(
1513 scheduler_
->OnVisibilityChanged(child_id
, route_id
, false);
1516 void ResourceDispatcherHostImpl::OnRenderViewHostWasShown(
1519 scheduler_
->OnVisibilityChanged(child_id
, route_id
, true);
1522 void ResourceDispatcherHostImpl::OnAudioRenderHostStreamStateChanged(
1526 scheduler_
->OnAudibilityChanged(child_id
, route_id
, is_playing
);
1529 // This function is only used for saving feature.
1530 void ResourceDispatcherHostImpl::BeginSaveFile(
1532 const Referrer
& referrer
,
1535 ResourceContext
* context
) {
1539 // http://crbug.com/90971
1541 base::strlcpy(url_buf
, url
.spec().c_str(), arraysize(url_buf
));
1542 base::debug::Alias(url_buf
);
1543 CHECK(ContainsKey(active_resource_contexts_
, context
));
1547 const net::URLRequestContext
* request_context
= context
->GetRequestContext();
1549 request_context
->job_factory()->IsHandledURL(url
);
1551 // Since any URLs which have non-standard scheme have been filtered
1552 // by save manager(see GURL::SchemeIsStandard). This situation
1553 // should not happen.
1558 net::CookieStore
* cookie_store
=
1559 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1561 scoped_ptr
<net::URLRequest
> request(
1562 request_context
->CreateRequest(url
, net::DEFAULT_PRIORITY
, NULL
,
1565 request
->set_method("GET");
1566 SetReferrerForRequest(request
.get(), referrer
);
1568 // So far, for saving page, we need fetch content from cache, in the
1569 // future, maybe we can use a configuration to configure this behavior.
1570 request
->SetLoadFlags(net::LOAD_PREFERRING_CACHE
);
1572 // Since we're just saving some resources we need, disallow downloading.
1573 ResourceRequestInfoImpl
* extra_info
=
1574 CreateRequestInfo(child_id
, route_id
, false, context
);
1575 extra_info
->AssociateWithRequest(request
.get()); // Request takes ownership.
1577 scoped_ptr
<ResourceHandler
> handler(
1578 new SaveFileResourceHandler(request
.get(),
1582 save_file_manager_
.get()));
1584 BeginRequestInternal(request
.Pass(), handler
.Pass());
1587 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1588 const GlobalRequestID
& id
) {
1589 GetLoader(id
)->MarkAsTransferring();
1592 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1593 const GlobalRequestID
& id
) {
1594 // Request should still exist and be in the middle of a transfer.
1595 DCHECK(IsTransferredNavigation(id
));
1596 RemovePendingRequest(id
.child_id
, id
.request_id
);
1599 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1600 const GlobalRequestID
& id
) {
1601 ResourceLoader
* loader
= GetLoader(id
);
1602 // The response we were meant to resume could have already been canceled.
1604 loader
->CompleteTransfer();
1607 // The object died, so cancel and detach all requests associated with it except
1608 // for downloads and detachable resources, which belong to the browser process
1609 // even if initiated via a renderer.
1610 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id
) {
1611 CancelRequestsForRoute(child_id
, -1 /* cancel all */);
1612 registered_temp_files_
.erase(child_id
);
1615 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id
,
1617 // Since pending_requests_ is a map, we first build up a list of all of the
1618 // matching requests to be cancelled, and then we cancel them. Since there
1619 // may be more than one request to cancel, we cannot simply hold onto the map
1620 // iterators found in the first loop.
1622 // Find the global ID of all matching elements.
1623 bool any_requests_transferring
= false;
1624 std::vector
<GlobalRequestID
> matching_requests
;
1625 for (LoaderMap::const_iterator i
= pending_loaders_
.begin();
1626 i
!= pending_loaders_
.end(); ++i
) {
1627 if (i
->first
.child_id
!= child_id
)
1630 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
1632 GlobalRequestID
id(child_id
, i
->first
.request_id
);
1633 DCHECK(id
== i
->first
);
1634 // Don't cancel navigations that are expected to live beyond this process.
1635 if (IsTransferredNavigation(id
))
1636 any_requests_transferring
= true;
1637 if (info
->detachable_handler()) {
1638 info
->detachable_handler()->Detach();
1639 } else if (!info
->IsDownload() && !info
->is_stream() &&
1640 !IsTransferredNavigation(id
) &&
1641 (route_id
== -1 || route_id
== info
->GetRouteID())) {
1642 matching_requests
.push_back(id
);
1647 for (size_t i
= 0; i
< matching_requests
.size(); ++i
) {
1648 LoaderMap::iterator iter
= pending_loaders_
.find(matching_requests
[i
]);
1649 // Although every matching request was in pending_requests_ when we built
1650 // matching_requests, it is normal for a matching request to be not found
1651 // in pending_requests_ after we have removed some matching requests from
1652 // pending_requests_. For example, deleting a net::URLRequest that has
1653 // exclusive (write) access to an HTTP cache entry may unblock another
1654 // net::URLRequest that needs exclusive access to the same cache entry, and
1655 // that net::URLRequest may complete and remove itself from
1656 // pending_requests_. So we need to check that iter is not equal to
1657 // pending_requests_.end().
1658 if (iter
!= pending_loaders_
.end())
1659 RemovePendingLoader(iter
);
1662 // Don't clear the blocked loaders or offline policy maps if any of the
1663 // requests in route_id are being transferred to a new process, since those
1664 // maps will be updated with the new route_id after the transfer. Otherwise
1665 // we will lose track of this info when the old route goes away, before the
1666 // new one is created.
1667 if (any_requests_transferring
)
1670 // Now deal with blocked requests if any.
1671 if (route_id
!= -1) {
1672 if (blocked_loaders_map_
.find(GlobalRoutingID(child_id
, route_id
)) !=
1673 blocked_loaders_map_
.end()) {
1674 CancelBlockedRequestsForRoute(child_id
, route_id
);
1677 // We have to do all render views for the process |child_id|.
1678 // Note that we have to do this in 2 passes as we cannot call
1679 // CancelBlockedRequestsForRoute while iterating over
1680 // blocked_loaders_map_, as it modifies it.
1681 std::set
<int> route_ids
;
1682 for (BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.begin();
1683 iter
!= blocked_loaders_map_
.end(); ++iter
) {
1684 if (iter
->first
.child_id
== child_id
)
1685 route_ids
.insert(iter
->first
.route_id
);
1687 for (std::set
<int>::const_iterator iter
= route_ids
.begin();
1688 iter
!= route_ids
.end(); ++iter
) {
1689 CancelBlockedRequestsForRoute(child_id
, *iter
);
1694 // Cancels the request and removes it from the list.
1695 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id
,
1697 LoaderMap::iterator i
= pending_loaders_
.find(
1698 GlobalRequestID(child_id
, request_id
));
1699 if (i
== pending_loaders_
.end()) {
1700 NOTREACHED() << "Trying to remove a request that's not here";
1703 RemovePendingLoader(i
);
1706 void ResourceDispatcherHostImpl::RemovePendingLoader(
1707 const LoaderMap::iterator
& iter
) {
1708 ResourceRequestInfoImpl
* info
= iter
->second
->GetRequestInfo();
1710 // Remove the memory credit that we added when pushing the request onto
1711 // the pending list.
1712 IncrementOutstandingRequestsMemory(-1, *info
);
1714 pending_loaders_
.erase(iter
);
1716 // If we have no more pending requests, then stop the load state monitor
1717 if (pending_loaders_
.empty() && update_load_states_timer_
)
1718 update_load_states_timer_
->Stop();
1721 void ResourceDispatcherHostImpl::CancelRequest(int child_id
,
1723 ResourceLoader
* loader
= GetLoader(child_id
, request_id
);
1725 // We probably want to remove this warning eventually, but I wanted to be
1726 // able to notice when this happens during initial development since it
1727 // should be rare and may indicate a bug.
1728 DVLOG(1) << "Canceling a request that wasn't found";
1732 RemovePendingRequest(child_id
, request_id
);
1735 ResourceDispatcherHostImpl::OustandingRequestsStats
1736 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1737 const ResourceRequestInfoImpl
& info
) {
1738 OutstandingRequestsStatsMap::iterator entry
=
1739 outstanding_requests_stats_map_
.find(info
.GetChildID());
1740 OustandingRequestsStats stats
= { 0, 0 };
1741 if (entry
!= outstanding_requests_stats_map_
.end())
1742 stats
= entry
->second
;
1746 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1747 const ResourceRequestInfoImpl
& info
,
1748 const OustandingRequestsStats
& stats
) {
1749 if (stats
.memory_cost
== 0 && stats
.num_requests
== 0)
1750 outstanding_requests_stats_map_
.erase(info
.GetChildID());
1752 outstanding_requests_stats_map_
[info
.GetChildID()] = stats
;
1755 ResourceDispatcherHostImpl::OustandingRequestsStats
1756 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1758 const ResourceRequestInfoImpl
& info
) {
1759 DCHECK_EQ(1, abs(count
));
1761 // Retrieve the previous value (defaulting to 0 if not found).
1762 OustandingRequestsStats stats
= GetOutstandingRequestsStats(info
);
1764 // Insert/update the total; delete entries when their count reaches 0.
1765 stats
.memory_cost
+= count
* info
.memory_cost();
1766 DCHECK_GE(stats
.memory_cost
, 0);
1767 UpdateOutstandingRequestsStats(info
, stats
);
1772 ResourceDispatcherHostImpl::OustandingRequestsStats
1773 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1775 ResourceRequestInfoImpl
* info
) {
1776 DCHECK_EQ(1, abs(count
));
1777 num_in_flight_requests_
+= count
;
1779 // Keep track of whether this request is counting toward the number of
1780 // in-flight requests for this process, in case we need to transfer it to
1781 // another process. This should be a toggle.
1782 DCHECK_NE(info
->counted_as_in_flight_request(), count
> 0);
1783 info
->set_counted_as_in_flight_request(count
> 0);
1785 OustandingRequestsStats stats
= GetOutstandingRequestsStats(*info
);
1786 stats
.num_requests
+= count
;
1787 DCHECK_GE(stats
.num_requests
, 0);
1788 UpdateOutstandingRequestsStats(*info
, stats
);
1793 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1794 net::URLRequest
* request
) {
1795 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1796 OustandingRequestsStats stats
= IncrementOutstandingRequestsCount(1, info
);
1798 if (stats
.num_requests
> max_num_in_flight_requests_per_process_
)
1800 if (num_in_flight_requests_
> max_num_in_flight_requests_
)
1806 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1807 net::URLRequest
* request
) {
1808 ResourceRequestInfoImpl
* info
= ResourceRequestInfoImpl::ForRequest(request
);
1809 IncrementOutstandingRequestsCount(-1, info
);
1812 void ResourceDispatcherHostImpl::BeginNavigationRequest(
1813 ResourceContext
* resource_context
,
1814 int64 frame_tree_node_id
,
1815 const CommonNavigationParams
& params
,
1816 const NavigationRequestInfo
& info
,
1817 scoped_refptr
<ResourceRequestBody
> request_body
,
1818 NavigationURLLoaderImplCore
* loader
) {
1819 // PlzNavigate: BeginNavigationRequest currently should only be used for the
1820 // browser-side navigations project.
1821 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1822 switches::kEnableBrowserSideNavigation
));
1824 ResourceType resource_type
= info
.is_main_frame
?
1825 RESOURCE_TYPE_MAIN_FRAME
: RESOURCE_TYPE_SUB_FRAME
;
1828 // TODO(davidben): Check ShouldServiceRequest here. This is important; it
1829 // needs to be checked relative to the child that /requested/ the
1830 // navigation. It's where file upload checks, etc., come in.
1831 (delegate_
&& !delegate_
->ShouldBeginRequest(
1832 info
.navigation_params
.method
,
1835 resource_context
))) {
1836 loader
->NotifyRequestFailed(net::ERR_ABORTED
);
1840 // Save the URL on the stack to help catch URLRequests which outlive their
1841 // URLRequestContexts. See https://crbug.com/90971
1843 base::strlcpy(url_buf
, params
.url
.spec().c_str(), arraysize(url_buf
));
1844 base::debug::Alias(url_buf
);
1845 CHECK(ContainsKey(active_resource_contexts_
, resource_context
));
1847 const net::URLRequestContext
* request_context
=
1848 resource_context
->GetRequestContext();
1850 int load_flags
= info
.navigation_params
.load_flags
;
1851 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
1852 if (info
.is_main_frame
) {
1853 load_flags
|= net::LOAD_MAIN_FRAME
;
1855 load_flags
|= net::LOAD_SUB_FRAME
;
1857 // Add a flag to selectively bypass the data reduction proxy if the resource
1858 // type is not an image.
1859 load_flags
|= net::LOAD_BYPASS_DATA_REDUCTION_PROXY
;
1861 // TODO(davidben): BuildLoadFlagsForRequest includes logic for
1862 // CanSendCookiesForOrigin and CanReadRawCookies. Is this needed here?
1864 // Sync loads should have maximum priority and should be the only
1865 // requests that have the ignore limits flag set.
1866 DCHECK(!(load_flags
& net::LOAD_IGNORE_LIMITS
));
1868 // TODO(davidben): OverrideCookieStoreForRenderProcess handling for
1869 // prerender. There may not be a renderer process yet, so we need to use the
1870 // ResourceContext or something.
1871 scoped_ptr
<net::URLRequest
> new_request
;
1872 new_request
= request_context
->CreateRequest(params
.url
, net::HIGHEST
,
1875 new_request
->set_method(info
.navigation_params
.method
);
1876 new_request
->set_first_party_for_cookies(
1877 info
.first_party_for_cookies
);
1878 if (info
.is_main_frame
) {
1879 new_request
->set_first_party_url_policy(
1880 net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
1883 SetReferrerForRequest(new_request
.get(), params
.referrer
);
1885 net::HttpRequestHeaders headers
;
1886 headers
.AddHeadersFromString(info
.navigation_params
.headers
);
1887 new_request
->SetExtraRequestHeaders(headers
);
1889 new_request
->SetLoadFlags(load_flags
);
1891 // Resolve elements from request_body and prepare upload data.
1892 if (info
.navigation_params
.request_body
.get()) {
1893 storage::BlobStorageContext
* blob_context
= GetBlobStorageContext(
1894 GetChromeBlobStorageContextForResourceContext(resource_context
));
1895 AttachRequestBodyBlobDataHandles(
1896 info
.navigation_params
.request_body
.get(),
1898 // TODO(davidben): The FileSystemContext is null here. In the case where
1899 // another renderer requested this navigation, this should be the same
1900 // FileSystemContext passed into ShouldServiceRequest.
1901 new_request
->set_upload(UploadDataStreamBuilder::Build(
1902 info
.navigation_params
.request_body
.get(),
1904 nullptr, // file_system_context
1905 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1911 // Make extra info and read footer (contains request ID).
1913 // TODO(davidben): Associate the request with the FrameTreeNode and/or tab so
1914 // that IO thread -> UI thread hops will work.
1915 ResourceRequestInfoImpl
* extra_info
=
1916 new ResourceRequestInfoImpl(
1917 PROCESS_TYPE_BROWSER
,
1920 -1, // request_data.origin_pid,
1922 -1, // request_data.render_frame_id,
1924 info
.parent_is_main_frame
,
1925 -1, // request_data.parent_render_frame_id,
1928 // should_replace_current_entry. This was only maintained at layer for
1929 // request transfers and isn't needed for browser-side navigations.
1931 false, // is download
1933 params
.allow_download
,
1934 info
.navigation_params
.has_user_gesture
,
1935 true, // enable_load_timing
1936 false, // enable_upload_progress
1937 params
.referrer
.policy
,
1938 // TODO(davidben): This is only used for prerenders. Replace
1939 // is_showing with something for that. Or maybe it just comes from the
1940 // same mechanism as the cookie one.
1941 blink::WebPageVisibilityStateVisible
,
1943 base::WeakPtr
<ResourceMessageFilter
>(), // filter
1945 // Request takes ownership.
1946 extra_info
->AssociateWithRequest(new_request
.get());
1948 if (new_request
->url().SchemeIs(url::kBlobScheme
)) {
1949 // Hang on to a reference to ensure the blob is not released prior
1950 // to the job being started.
1951 ChromeBlobStorageContext
* blob_context
=
1952 GetChromeBlobStorageContextForResourceContext(resource_context
);
1953 storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
1955 blob_context
->context()->GetBlobDataFromPublicURL(new_request
->url()));
1958 // TODO(davidben): Attach ServiceWorkerRequestHandler.
1960 // TODO(davidben): Attach AppCacheInterceptor.
1962 scoped_ptr
<ResourceHandler
> handler(new NavigationResourceHandler(
1963 new_request
.get(), loader
));
1965 // TODO(davidben): Pass in the appropriate appcache_service. Also fix the
1966 // dependency on child_id/route_id. Those are used by the ResourceScheduler;
1967 // currently it's a no-op.
1968 handler
= AddStandardHandlers(new_request
.get(), resource_type
,
1970 nullptr, // appcache_service
1975 BeginRequestInternal(new_request
.Pass(), handler
.Pass());
1979 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
1980 net::URLRequest
* request
) {
1981 // The following fields should be a minor size contribution (experimentally
1982 // on the order of 100). However since they are variable length, it could
1983 // in theory be a sizeable contribution.
1984 int strings_cost
= request
->extra_request_headers().ToString().size() +
1985 request
->original_url().spec().size() +
1986 request
->referrer().size() +
1987 request
->method().size();
1989 // Note that this expression will typically be dominated by:
1990 // |kAvgBytesPerOutstandingRequest|.
1991 return kAvgBytesPerOutstandingRequest
+ strings_cost
;
1994 void ResourceDispatcherHostImpl::BeginRequestInternal(
1995 scoped_ptr
<net::URLRequest
> request
,
1996 scoped_ptr
<ResourceHandler
> handler
) {
1997 DCHECK(!request
->is_pending());
1998 ResourceRequestInfoImpl
* info
=
1999 ResourceRequestInfoImpl::ForRequest(request
.get());
2001 if ((TimeTicks::Now() - last_user_gesture_time_
) <
2002 TimeDelta::FromMilliseconds(kUserGestureWindowMs
)) {
2003 request
->SetLoadFlags(
2004 request
->load_flags() | net::LOAD_MAYBE_USER_GESTURE
);
2007 // Add the memory estimate that starting this request will consume.
2008 info
->set_memory_cost(CalculateApproximateMemoryCost(request
.get()));
2010 // If enqueing/starting this request will exceed our per-process memory
2011 // bound, abort it right away.
2012 OustandingRequestsStats stats
= IncrementOutstandingRequestsMemory(1, *info
);
2013 if (stats
.memory_cost
> max_outstanding_requests_cost_per_process_
) {
2014 // We call "CancelWithError()" as a way of setting the net::URLRequest's
2015 // status -- it has no effect beyond this, since the request hasn't started.
2016 request
->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES
);
2019 handler
->OnResponseCompleted(request
->status(), std::string(), &defer
);
2021 // TODO(darin): The handler is not ready for us to kill the request. Oops!
2025 IncrementOutstandingRequestsMemory(-1, *info
);
2027 // A ResourceHandler must not outlive its associated URLRequest.
2032 linked_ptr
<ResourceLoader
> loader(
2033 new ResourceLoader(request
.Pass(), handler
.Pass(), this));
2035 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2036 BlockedLoadersMap::const_iterator iter
= blocked_loaders_map_
.find(id
);
2037 if (iter
!= blocked_loaders_map_
.end()) {
2038 // The request should be blocked.
2039 iter
->second
->push_back(loader
);
2043 StartLoading(info
, loader
);
2046 void ResourceDispatcherHostImpl::StartLoading(
2047 ResourceRequestInfoImpl
* info
,
2048 const linked_ptr
<ResourceLoader
>& loader
) {
2049 pending_loaders_
[info
->GetGlobalRequestID()] = loader
;
2051 loader
->StartRequest();
2054 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl
* contents
) {
2055 last_user_gesture_time_
= TimeTicks::Now();
2058 net::URLRequest
* ResourceDispatcherHostImpl::GetURLRequest(
2059 const GlobalRequestID
& id
) {
2060 ResourceLoader
* loader
= GetLoader(id
);
2064 return loader
->request();
2069 // This function attempts to return the "more interesting" load state of |a|
2070 // and |b|. We don't have temporal information about these load states
2071 // (meaning we don't know when we transitioned into these states), so we just
2072 // rank them according to how "interesting" the states are.
2074 // We take advantage of the fact that the load states are an enumeration listed
2075 // in the order in which they occur during the lifetime of a request, so we can
2076 // regard states with larger numeric values as being further along toward
2077 // completion. We regard those states as more interesting to report since they
2078 // represent progress.
2080 // For example, by this measure "tranferring data" is a more interesting state
2081 // than "resolving host" because when we are transferring data we are actually
2082 // doing something that corresponds to changes that the user might observe,
2083 // whereas waiting for a host name to resolve implies being stuck.
2085 const net::LoadStateWithParam
& MoreInterestingLoadState(
2086 const net::LoadStateWithParam
& a
, const net::LoadStateWithParam
& b
) {
2087 return (a
.state
< b
.state
) ? b
: a
;
2090 // Carries information about a load state change.
2093 net::LoadStateWithParam load_state
;
2094 uint64 upload_position
;
2098 // Map from ProcessID+RouteID pair to LoadState
2099 typedef std::map
<GlobalRoutingID
, LoadInfo
> LoadInfoMap
;
2101 // Used to marshal calls to LoadStateChanged from the IO to UI threads. We do
2102 // them all as a single callback to avoid spamming the UI thread.
2103 void LoadInfoUpdateCallback(const LoadInfoMap
& info_map
) {
2104 LoadInfoMap::const_iterator i
;
2105 for (i
= info_map
.begin(); i
!= info_map
.end(); ++i
) {
2106 RenderViewHostImpl
* view
=
2107 RenderViewHostImpl::FromID(i
->first
.child_id
, i
->first
.route_id
);
2108 if (view
) // The view could be gone at this point.
2109 view
->LoadStateChanged(i
->second
.url
, i
->second
.load_state
,
2110 i
->second
.upload_position
,
2111 i
->second
.upload_size
);
2117 void ResourceDispatcherHostImpl::UpdateLoadStates() {
2118 // Populate this map with load state changes, and then send them on to the UI
2119 // thread where they can be passed along to the respective RVHs.
2120 LoadInfoMap info_map
;
2122 LoaderMap::const_iterator i
;
2124 // Determine the largest upload size of all requests
2125 // in each View (good chance it's zero).
2126 std::map
<GlobalRoutingID
, uint64
> largest_upload_size
;
2127 for (i
= pending_loaders_
.begin(); i
!= pending_loaders_
.end(); ++i
) {
2128 net::URLRequest
* request
= i
->second
->request();
2129 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
2130 uint64 upload_size
= request
->GetUploadProgress().size();
2131 if (request
->GetLoadState().state
!= net::LOAD_STATE_SENDING_REQUEST
)
2133 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2134 if (upload_size
&& largest_upload_size
[id
] < upload_size
)
2135 largest_upload_size
[id
] = upload_size
;
2138 for (i
= pending_loaders_
.begin(); i
!= pending_loaders_
.end(); ++i
) {
2139 net::URLRequest
* request
= i
->second
->request();
2140 ResourceRequestInfoImpl
* info
= i
->second
->GetRequestInfo();
2141 net::LoadStateWithParam load_state
= request
->GetLoadState();
2142 net::UploadProgress progress
= request
->GetUploadProgress();
2144 // We also poll for upload progress on this timer and send upload
2145 // progress ipc messages to the plugin process.
2146 i
->second
->ReportUploadProgress();
2148 GlobalRoutingID
id(info
->GetGlobalRoutingID());
2150 // If a request is uploading data, ignore all other requests so that the
2151 // upload progress takes priority for being shown in the status bar.
2152 if (largest_upload_size
.find(id
) != largest_upload_size
.end() &&
2153 progress
.size() < largest_upload_size
[id
])
2156 net::LoadStateWithParam to_insert
= load_state
;
2157 LoadInfoMap::iterator existing
= info_map
.find(id
);
2158 if (existing
!= info_map
.end()) {
2160 MoreInterestingLoadState(existing
->second
.load_state
, load_state
);
2161 if (to_insert
.state
== existing
->second
.load_state
.state
)
2164 LoadInfo
& load_info
= info_map
[id
];
2165 load_info
.url
= request
->url();
2166 load_info
.load_state
= to_insert
;
2167 load_info
.upload_size
= progress
.size();
2168 load_info
.upload_position
= progress
.position();
2171 if (info_map
.empty())
2174 BrowserThread::PostTask(
2175 BrowserThread::UI
, FROM_HERE
,
2176 base::Bind(&LoadInfoUpdateCallback
, info_map
));
2179 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id
,
2181 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
2182 GlobalRoutingID
key(child_id
, route_id
);
2183 DCHECK(blocked_loaders_map_
.find(key
) == blocked_loaders_map_
.end()) <<
2184 "BlockRequestsForRoute called multiple time for the same RVH";
2185 blocked_loaders_map_
[key
] = new BlockedLoadersList();
2188 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id
,
2190 ProcessBlockedRequestsForRoute(child_id
, route_id
, false);
2193 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id
,
2195 ProcessBlockedRequestsForRoute(child_id
, route_id
, true);
2198 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
2201 bool cancel_requests
) {
2202 BlockedLoadersMap::iterator iter
= blocked_loaders_map_
.find(
2203 GlobalRoutingID(child_id
, route_id
));
2204 if (iter
== blocked_loaders_map_
.end()) {
2205 // It's possible to reach here if the renderer crashed while an interstitial
2206 // page was showing.
2210 BlockedLoadersList
* loaders
= iter
->second
;
2212 // Removing the vector from the map unblocks any subsequent requests.
2213 blocked_loaders_map_
.erase(iter
);
2215 for (BlockedLoadersList::iterator loaders_iter
= loaders
->begin();
2216 loaders_iter
!= loaders
->end(); ++loaders_iter
) {
2217 linked_ptr
<ResourceLoader
> loader
= *loaders_iter
;
2218 ResourceRequestInfoImpl
* info
= loader
->GetRequestInfo();
2219 if (cancel_requests
) {
2220 IncrementOutstandingRequestsMemory(-1, *info
);
2222 StartLoading(info
, loader
);
2229 ResourceDispatcherHostImpl::HttpAuthRelationType
2230 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
2231 const GURL
& request_url
,
2232 const GURL
& first_party
) {
2233 if (!first_party
.is_valid())
2234 return HTTP_AUTH_RELATION_TOP
;
2236 if (net::registry_controlled_domains::SameDomainOrHost(
2237 first_party
, request_url
,
2238 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
))
2239 return HTTP_AUTH_RELATION_SAME_DOMAIN
;
2241 if (allow_cross_origin_auth_prompt())
2242 return HTTP_AUTH_RELATION_ALLOWED_CROSS
;
2244 return HTTP_AUTH_RELATION_BLOCKED_CROSS
;
2247 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
2248 return allow_cross_origin_auth_prompt_
;
2251 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
2252 const GlobalRequestID
& id
) const {
2253 ResourceLoader
* loader
= GetLoader(id
);
2254 return loader
? loader
->is_transferring() : false;
2257 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(
2258 const GlobalRequestID
& id
) const {
2259 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
2261 LoaderMap::const_iterator i
= pending_loaders_
.find(id
);
2262 if (i
== pending_loaders_
.end())
2265 return i
->second
.get();
2268 ResourceLoader
* ResourceDispatcherHostImpl::GetLoader(int child_id
,
2269 int request_id
) const {
2270 return GetLoader(GlobalRequestID(child_id
, request_id
));
2273 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
2274 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2275 DelegateMap::iterator it
= delegate_map_
.find(id
);
2276 if (it
== delegate_map_
.end()) {
2277 it
= delegate_map_
.insert(
2278 std::make_pair(id
, new ObserverList
<ResourceMessageDelegate
>)).first
;
2280 it
->second
->AddObserver(delegate
);
2283 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
2284 const GlobalRequestID
& id
, ResourceMessageDelegate
* delegate
) {
2285 DCHECK(ContainsKey(delegate_map_
, id
));
2286 DelegateMap::iterator it
= delegate_map_
.find(id
);
2287 DCHECK(it
->second
->HasObserver(delegate
));
2288 it
->second
->RemoveObserver(delegate
);
2289 if (!it
->second
->might_have_observers()) {
2291 delegate_map_
.erase(it
);
2295 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
2296 const ResourceHostMsg_Request
& request_data
,
2298 bool is_sync_load
) {
2299 int load_flags
= request_data
.load_flags
;
2301 // Although EV status is irrelevant to sub-frames and sub-resources, we have
2302 // to perform EV certificate verification on all resources because an HTTP
2303 // keep-alive connection created to load a sub-frame or a sub-resource could
2304 // be reused to load a main frame.
2305 load_flags
|= net::LOAD_VERIFY_EV_CERT
;
2306 if (request_data
.resource_type
== RESOURCE_TYPE_MAIN_FRAME
) {
2307 load_flags
|= net::LOAD_MAIN_FRAME
;
2308 } else if (request_data
.resource_type
== RESOURCE_TYPE_SUB_FRAME
) {
2309 load_flags
|= net::LOAD_SUB_FRAME
;
2310 } else if (request_data
.resource_type
== RESOURCE_TYPE_PREFETCH
) {
2311 load_flags
|= (net::LOAD_PREFETCH
| net::LOAD_DO_NOT_PROMPT_FOR_LOGIN
);
2312 } else if (request_data
.resource_type
== RESOURCE_TYPE_FAVICON
) {
2313 load_flags
|= net::LOAD_DO_NOT_PROMPT_FOR_LOGIN
;
2314 } else if (request_data
.resource_type
== RESOURCE_TYPE_IMAGE
) {
2315 // Prevent third-party image content from prompting for login, as this
2316 // is often a scam to extract credentials for another domain from the user.
2317 // Only block image loads, as the attack applies largely to the "src"
2318 // property of the <img> tag. It is common for web properties to allow
2319 // untrusted values for <img src>; this is considered a fair thing for an
2320 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
2321 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
2322 // would be considered vulnerable in and of itself.
2323 HttpAuthRelationType relation_type
= HttpAuthRelationTypeOf(
2324 request_data
.url
, request_data
.first_party_for_cookies
);
2325 if (relation_type
== HTTP_AUTH_RELATION_BLOCKED_CROSS
) {
2326 load_flags
|= (net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY
|
2327 net::LOAD_DO_NOT_PROMPT_FOR_LOGIN
);
2332 load_flags
|= net::LOAD_IGNORE_LIMITS
;
2334 ChildProcessSecurityPolicyImpl
* policy
=
2335 ChildProcessSecurityPolicyImpl::GetInstance();
2336 if (!policy
->CanSendCookiesForOrigin(child_id
, request_data
.url
)) {
2337 load_flags
|= (net::LOAD_DO_NOT_SEND_COOKIES
|
2338 net::LOAD_DO_NOT_SEND_AUTH_DATA
|
2339 net::LOAD_DO_NOT_SAVE_COOKIES
);
2342 // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only
2343 // allow requesting them if requester has ReadRawCookies permission.
2344 if ((load_flags
& net::LOAD_REPORT_RAW_HEADERS
)
2345 && !policy
->CanReadRawCookies(child_id
)) {
2346 VLOG(1) << "Denied unauthorized request for raw headers";
2347 load_flags
&= ~net::LOAD_REPORT_RAW_HEADERS
;
2350 // Add a flag to selectively bypass the data reduction proxy if the resource
2351 // type is not an image.
2352 if (request_data
.resource_type
!= RESOURCE_TYPE_IMAGE
)
2353 load_flags
|= net::LOAD_BYPASS_DATA_REDUCTION_PROXY
;
2358 } // namespace content