Add a FrameHostMsg_BeginNavigation IPC
[chromium-blink-merge.git] / content / browser / loader / resource_dispatcher_host_impl.cc
blob2957728545e30adee24c804af29e71a7cf2d45a8
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading
7 #include "content/browser/loader/resource_dispatcher_host_impl.h"
9 #include <algorithm>
10 #include <set>
11 #include <vector>
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/debug/alias.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/memory/shared_memory.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/metrics/histogram.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/cross_site_request_manager.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/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/power_save_block_resource_throttle.h"
41 #include "content/browser/loader/redirect_to_file_resource_handler.h"
42 #include "content/browser/loader/resource_message_filter.h"
43 #include "content/browser/loader/resource_request_info_impl.h"
44 #include "content/browser/loader/stream_resource_handler.h"
45 #include "content/browser/loader/sync_resource_handler.h"
46 #include "content/browser/loader/throttling_resource_handler.h"
47 #include "content/browser/loader/upload_data_stream_builder.h"
48 #include "content/browser/plugin_service_impl.h"
49 #include "content/browser/renderer_host/render_view_host_delegate.h"
50 #include "content/browser/renderer_host/render_view_host_impl.h"
51 #include "content/browser/resource_context_impl.h"
52 #include "content/browser/service_worker/service_worker_request_handler.h"
53 #include "content/browser/streams/stream.h"
54 #include "content/browser/streams/stream_context.h"
55 #include "content/browser/streams/stream_registry.h"
56 #include "content/browser/worker_host/worker_service_impl.h"
57 #include "content/browser/web_contents/web_contents_impl.h"
58 #include "content/common/appcache_interfaces.h"
59 #include "content/common/resource_messages.h"
60 #include "content/common/ssl_status_serialization.h"
61 #include "content/common/view_messages.h"
62 #include "content/public/browser/browser_thread.h"
63 #include "content/public/browser/content_browser_client.h"
64 #include "content/public/browser/download_manager.h"
65 #include "content/public/browser/download_url_parameters.h"
66 #include "content/public/browser/global_request_id.h"
67 #include "content/public/browser/resource_dispatcher_host_delegate.h"
68 #include "content/public/browser/resource_request_details.h"
69 #include "content/public/browser/resource_throttle.h"
70 #include "content/public/browser/stream_handle.h"
71 #include "content/public/browser/user_metrics.h"
72 #include "content/public/common/content_switches.h"
73 #include "content/public/common/process_type.h"
74 #include "ipc/ipc_message_macros.h"
75 #include "ipc/ipc_message_start.h"
76 #include "net/base/auth.h"
77 #include "net/base/load_flags.h"
78 #include "net/base/mime_util.h"
79 #include "net/base/net_errors.h"
80 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
81 #include "net/base/request_priority.h"
82 #include "net/base/upload_data_stream.h"
83 #include "net/cert/cert_status_flags.h"
84 #include "net/cookies/cookie_monster.h"
85 #include "net/http/http_response_headers.h"
86 #include "net/http/http_response_info.h"
87 #include "net/ssl/ssl_cert_request_info.h"
88 #include "net/url_request/url_request.h"
89 #include "net/url_request/url_request_context.h"
90 #include "net/url_request/url_request_job_factory.h"
91 #include "url/url_constants.h"
92 #include "webkit/common/blob/blob_data.h"
93 #include "webkit/browser/blob/blob_data_handle.h"
94 #include "webkit/browser/blob/blob_storage_context.h"
95 #include "webkit/browser/blob/blob_url_request_job_factory.h"
96 #include "webkit/browser/fileapi/file_permission_policy.h"
97 #include "webkit/browser/fileapi/file_system_context.h"
98 #include "webkit/common/blob/shareable_file_reference.h"
100 using base::Time;
101 using base::TimeDelta;
102 using base::TimeTicks;
103 using webkit_blob::ShareableFileReference;
105 // ----------------------------------------------------------------------------
107 namespace content {
109 namespace {
111 static ResourceDispatcherHostImpl* g_resource_dispatcher_host;
113 // The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates
114 const int kUpdateLoadStatesIntervalMsec = 100;
116 // Maximum byte "cost" of all the outstanding requests for a renderer.
117 // See delcaration of |max_outstanding_requests_cost_per_process_| for details.
118 // This bound is 25MB, which allows for around 6000 outstanding requests.
119 const int kMaxOutstandingRequestsCostPerProcess = 26214400;
121 // The number of milliseconds after noting a user gesture that we will
122 // tag newly-created URLRequest objects with the
123 // net::LOAD_MAYBE_USER_GESTURE load flag. This is a fairly arbitrary
124 // guess at how long to expect direct impact from a user gesture, but
125 // this should be OK as the load flag is a best-effort thing only,
126 // rather than being intended as fully accurate.
127 const int kUserGestureWindowMs = 3500;
129 // Ratio of |max_num_in_flight_requests_| that any one renderer is allowed to
130 // use. Arbitrarily chosen.
131 const double kMaxRequestsPerProcessRatio = 0.45;
133 // TODO(jkarlin): The value is high to reduce the chance of the detachable
134 // request timing out, forcing a blocked second request to open a new connection
135 // and start over. Reduce this value once we have a better idea of what it
136 // should be and once we stop blocking multiple simultaneous requests for the
137 // same resource (see bugs 46104 and 31014).
138 const int kDefaultDetachableCancelDelayMs = 30000;
140 bool IsDetachableResourceType(ResourceType::Type type) {
141 switch (type) {
142 case ResourceType::PREFETCH:
143 case ResourceType::PING:
144 return true;
145 default:
146 return false;
150 // Aborts a request before an URLRequest has actually been created.
151 void AbortRequestBeforeItStarts(ResourceMessageFilter* filter,
152 IPC::Message* sync_result,
153 int request_id) {
154 if (sync_result) {
155 SyncLoadResult result;
156 result.error_code = net::ERR_ABORTED;
157 ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result, result);
158 filter->Send(sync_result);
159 } else {
160 // Tell the renderer that this request was disallowed.
161 ResourceMsg_RequestCompleteData request_complete_data;
162 request_complete_data.error_code = net::ERR_ABORTED;
163 request_complete_data.was_ignored_by_handler = false;
164 request_complete_data.exists_in_cache = false;
165 // No security info needed, connection not established.
166 request_complete_data.completion_time = base::TimeTicks();
167 request_complete_data.encoded_data_length = 0;
168 filter->Send(new ResourceMsg_RequestComplete(
169 request_id, request_complete_data));
173 void SetReferrerForRequest(net::URLRequest* request, const Referrer& referrer) {
174 if (!referrer.url.is_valid() ||
175 CommandLine::ForCurrentProcess()->HasSwitch(switches::kNoReferrers)) {
176 request->SetReferrer(std::string());
177 } else {
178 request->SetReferrer(referrer.url.spec());
181 net::URLRequest::ReferrerPolicy net_referrer_policy =
182 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
183 switch (referrer.policy) {
184 case blink::WebReferrerPolicyDefault:
185 net_referrer_policy =
186 net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
187 break;
188 case blink::WebReferrerPolicyAlways:
189 case blink::WebReferrerPolicyNever:
190 case blink::WebReferrerPolicyOrigin:
191 net_referrer_policy = net::URLRequest::NEVER_CLEAR_REFERRER;
192 break;
194 request->set_referrer_policy(net_referrer_policy);
197 // Consults the RendererSecurity policy to determine whether the
198 // ResourceDispatcherHostImpl should service this request. A request might be
199 // disallowed if the renderer is not authorized to retrieve the request URL or
200 // if the renderer is attempting to upload an unauthorized file.
201 bool ShouldServiceRequest(int process_type,
202 int child_id,
203 const ResourceHostMsg_Request& request_data,
204 fileapi::FileSystemContext* file_system_context) {
205 if (process_type == PROCESS_TYPE_PLUGIN)
206 return true;
208 ChildProcessSecurityPolicyImpl* policy =
209 ChildProcessSecurityPolicyImpl::GetInstance();
211 // Check if the renderer is permitted to request the requested URL.
212 if (!policy->CanRequestURL(child_id, request_data.url)) {
213 VLOG(1) << "Denied unauthorized request for "
214 << request_data.url.possibly_invalid_spec();
215 return false;
218 // Check if the renderer is permitted to upload the requested files.
219 if (request_data.request_body.get()) {
220 const std::vector<ResourceRequestBody::Element>* uploads =
221 request_data.request_body->elements();
222 std::vector<ResourceRequestBody::Element>::const_iterator iter;
223 for (iter = uploads->begin(); iter != uploads->end(); ++iter) {
224 if (iter->type() == ResourceRequestBody::Element::TYPE_FILE &&
225 !policy->CanReadFile(child_id, iter->path())) {
226 NOTREACHED() << "Denied unauthorized upload of "
227 << iter->path().value();
228 return false;
230 if (iter->type() == ResourceRequestBody::Element::TYPE_FILE_FILESYSTEM) {
231 fileapi::FileSystemURL url =
232 file_system_context->CrackURL(iter->filesystem_url());
233 if (!policy->CanReadFileSystemFile(child_id, url)) {
234 NOTREACHED() << "Denied unauthorized upload of "
235 << iter->filesystem_url().spec();
236 return false;
242 return true;
245 void RemoveDownloadFileFromChildSecurityPolicy(int child_id,
246 const base::FilePath& path) {
247 ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile(
248 child_id, path);
251 #if defined(OS_WIN)
252 #pragma warning(disable: 4748)
253 #pragma optimize("", off)
254 #endif
256 #if defined(OS_WIN)
257 #pragma optimize("", on)
258 #pragma warning(default: 4748)
259 #endif
261 DownloadInterruptReason CallbackAndReturn(
262 const DownloadUrlParameters::OnStartedCallback& started_cb,
263 DownloadInterruptReason interrupt_reason) {
264 if (started_cb.is_null())
265 return interrupt_reason;
266 BrowserThread::PostTask(
267 BrowserThread::UI,
268 FROM_HERE,
269 base::Bind(
270 started_cb, static_cast<DownloadItem*>(NULL), interrupt_reason));
272 return interrupt_reason;
275 int GetCertID(net::URLRequest* request, int child_id) {
276 if (request->ssl_info().cert.get()) {
277 return CertStore::GetInstance()->StoreCert(request->ssl_info().cert.get(),
278 child_id);
280 return 0;
283 void NotifyRedirectOnUI(int render_process_id,
284 int render_frame_host,
285 scoped_ptr<ResourceRedirectDetails> details) {
286 RenderFrameHostImpl* host =
287 RenderFrameHostImpl::FromID(render_process_id, render_frame_host);
288 WebContentsImpl* web_contents =
289 static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(host));
290 if (!web_contents)
291 return;
292 web_contents->DidGetRedirectForResourceRequest(
293 host->render_view_host(), *details.get());
296 void NotifyResponseOnUI(int render_process_id,
297 int render_frame_host,
298 scoped_ptr<ResourceRequestDetails> details) {
299 RenderFrameHostImpl* host =
300 RenderFrameHostImpl::FromID(render_process_id, render_frame_host);
301 WebContentsImpl* web_contents =
302 static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(host));
303 if (!web_contents)
304 return;
305 web_contents->DidGetResourceResponseStart(*details.get());
308 bool IsValidatedSCT(
309 const net::SignedCertificateTimestampAndStatus& sct_status) {
310 return sct_status.status == net::ct::SCT_STATUS_OK;
313 webkit_blob::BlobStorageContext* GetBlobStorageContext(
314 ResourceMessageFilter* filter) {
315 if (!filter->blob_storage_context())
316 return NULL;
317 return filter->blob_storage_context()->context();
320 } // namespace
322 // static
323 ResourceDispatcherHost* ResourceDispatcherHost::Get() {
324 return g_resource_dispatcher_host;
327 ResourceDispatcherHostImpl::ResourceDispatcherHostImpl()
328 : save_file_manager_(new SaveFileManager()),
329 request_id_(-1),
330 is_shutdown_(false),
331 num_in_flight_requests_(0),
332 max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()),
333 max_num_in_flight_requests_per_process_(
334 static_cast<int>(
335 max_num_in_flight_requests_ * kMaxRequestsPerProcessRatio)),
336 max_outstanding_requests_cost_per_process_(
337 kMaxOutstandingRequestsCostPerProcess),
338 filter_(NULL),
339 delegate_(NULL),
340 allow_cross_origin_auth_prompt_(false) {
341 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
342 DCHECK(!g_resource_dispatcher_host);
343 g_resource_dispatcher_host = this;
345 GetContentClient()->browser()->ResourceDispatcherHostCreated();
347 ANNOTATE_BENIGN_RACE(
348 &last_user_gesture_time_,
349 "We don't care about the precise value, see http://crbug.com/92889");
351 BrowserThread::PostTask(BrowserThread::IO,
352 FROM_HERE,
353 base::Bind(&ResourceDispatcherHostImpl::OnInit,
354 base::Unretained(this)));
356 update_load_states_timer_.reset(
357 new base::RepeatingTimer<ResourceDispatcherHostImpl>());
360 ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() {
361 DCHECK(outstanding_requests_stats_map_.empty());
362 DCHECK(g_resource_dispatcher_host);
363 g_resource_dispatcher_host = NULL;
366 // static
367 ResourceDispatcherHostImpl* ResourceDispatcherHostImpl::Get() {
368 return g_resource_dispatcher_host;
371 void ResourceDispatcherHostImpl::SetDelegate(
372 ResourceDispatcherHostDelegate* delegate) {
373 delegate_ = delegate;
376 void ResourceDispatcherHostImpl::SetAllowCrossOriginAuthPrompt(bool value) {
377 allow_cross_origin_auth_prompt_ = value;
380 void ResourceDispatcherHostImpl::AddResourceContext(ResourceContext* context) {
381 active_resource_contexts_.insert(context);
384 void ResourceDispatcherHostImpl::RemoveResourceContext(
385 ResourceContext* context) {
386 CHECK(ContainsKey(active_resource_contexts_, context));
387 active_resource_contexts_.erase(context);
390 void ResourceDispatcherHostImpl::ResumeResponseDeferredAtStart(
391 const GlobalRequestID& id) {
392 ResourceLoader* loader = GetLoader(id);
393 if (loader) {
394 // The response we were meant to resume could have already been canceled.
395 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
396 if (info->cross_site_handler())
397 info->cross_site_handler()->ResumeResponseDeferredAtStart(id.request_id);
401 void ResourceDispatcherHostImpl::CancelRequestsForContext(
402 ResourceContext* context) {
403 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
404 DCHECK(context);
406 CHECK(ContainsKey(active_resource_contexts_, context));
408 // Note that request cancellation has side effects. Therefore, we gather all
409 // the requests to cancel first, and then we start cancelling. We assert at
410 // the end that there are no more to cancel since the context is about to go
411 // away.
412 typedef std::vector<linked_ptr<ResourceLoader> > LoaderList;
413 LoaderList loaders_to_cancel;
415 for (LoaderMap::iterator i = pending_loaders_.begin();
416 i != pending_loaders_.end();) {
417 if (i->second->GetRequestInfo()->GetContext() == context) {
418 loaders_to_cancel.push_back(i->second);
419 IncrementOutstandingRequestsMemory(-1, *i->second->GetRequestInfo());
420 pending_loaders_.erase(i++);
421 } else {
422 ++i;
426 for (BlockedLoadersMap::iterator i = blocked_loaders_map_.begin();
427 i != blocked_loaders_map_.end();) {
428 BlockedLoadersList* loaders = i->second;
429 if (loaders->empty()) {
430 // This can happen if BlockRequestsForRoute() has been called for a route,
431 // but we haven't blocked any matching requests yet.
432 ++i;
433 continue;
435 ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo();
436 if (info->GetContext() == context) {
437 blocked_loaders_map_.erase(i++);
438 for (BlockedLoadersList::const_iterator it = loaders->begin();
439 it != loaders->end(); ++it) {
440 linked_ptr<ResourceLoader> loader = *it;
441 info = loader->GetRequestInfo();
442 // We make the assumption that all requests on the list have the same
443 // ResourceContext.
444 DCHECK_EQ(context, info->GetContext());
445 IncrementOutstandingRequestsMemory(-1, *info);
446 loaders_to_cancel.push_back(loader);
448 delete loaders;
449 } else {
450 ++i;
454 #ifndef NDEBUG
455 for (LoaderList::iterator i = loaders_to_cancel.begin();
456 i != loaders_to_cancel.end(); ++i) {
457 // There is no strict requirement that this be the case, but currently
458 // downloads, streams, detachable requests, and transferred requests are the
459 // only requests that aren't cancelled when the associated processes go
460 // away. It may be OK for this invariant to change in the future, but if
461 // this assertion fires without the invariant changing, then it's indicative
462 // of a leak.
463 DCHECK((*i)->GetRequestInfo()->IsDownload() ||
464 (*i)->GetRequestInfo()->is_stream() ||
465 ((*i)->GetRequestInfo()->detachable_handler() &&
466 (*i)->GetRequestInfo()->detachable_handler()->is_detached()) ||
467 (*i)->is_transferring());
469 #endif
471 loaders_to_cancel.clear();
473 // Validate that no more requests for this context were added.
474 for (LoaderMap::const_iterator i = pending_loaders_.begin();
475 i != pending_loaders_.end(); ++i) {
476 // http://crbug.com/90971
477 CHECK_NE(i->second->GetRequestInfo()->GetContext(), context);
480 for (BlockedLoadersMap::const_iterator i = blocked_loaders_map_.begin();
481 i != blocked_loaders_map_.end(); ++i) {
482 BlockedLoadersList* loaders = i->second;
483 if (!loaders->empty()) {
484 ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo();
485 // http://crbug.com/90971
486 CHECK_NE(info->GetContext(), context);
491 DownloadInterruptReason ResourceDispatcherHostImpl::BeginDownload(
492 scoped_ptr<net::URLRequest> request,
493 const Referrer& referrer,
494 bool is_content_initiated,
495 ResourceContext* context,
496 int child_id,
497 int route_id,
498 bool prefer_cache,
499 scoped_ptr<DownloadSaveInfo> save_info,
500 uint32 download_id,
501 const DownloadStartedCallback& started_callback) {
502 if (is_shutdown_)
503 return CallbackAndReturn(started_callback,
504 DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN);
506 const GURL& url = request->original_url();
508 // http://crbug.com/90971
509 char url_buf[128];
510 base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
511 base::debug::Alias(url_buf);
512 CHECK(ContainsKey(active_resource_contexts_, context));
514 SetReferrerForRequest(request.get(), referrer);
516 int extra_load_flags = net::LOAD_IS_DOWNLOAD;
517 if (prefer_cache) {
518 // If there is upload data attached, only retrieve from cache because there
519 // is no current mechanism to prompt the user for their consent for a
520 // re-post. For GETs, try to retrieve data from the cache and skip
521 // validating the entry if present.
522 if (request->get_upload() != NULL)
523 extra_load_flags |= net::LOAD_ONLY_FROM_CACHE;
524 else
525 extra_load_flags |= net::LOAD_PREFERRING_CACHE;
526 } else {
527 extra_load_flags |= net::LOAD_DISABLE_CACHE;
529 request->SetLoadFlags(request->load_flags() | extra_load_flags);
531 // Check if the renderer is permitted to request the requested URL.
532 if (!ChildProcessSecurityPolicyImpl::GetInstance()->
533 CanRequestURL(child_id, url)) {
534 VLOG(1) << "Denied unauthorized download request for "
535 << url.possibly_invalid_spec();
536 return CallbackAndReturn(started_callback,
537 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST);
540 request_id_--;
542 const net::URLRequestContext* request_context = context->GetRequestContext();
543 if (!request_context->job_factory()->IsHandledURL(url)) {
544 VLOG(1) << "Download request for unsupported protocol: "
545 << url.possibly_invalid_spec();
546 return CallbackAndReturn(started_callback,
547 DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST);
550 ResourceRequestInfoImpl* extra_info =
551 CreateRequestInfo(child_id, route_id, true, context);
552 extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
554 if (request->url().SchemeIs(url::kBlobScheme)) {
555 ChromeBlobStorageContext* blob_context =
556 GetChromeBlobStorageContextForResourceContext(context);
557 webkit_blob::BlobProtocolHandler::SetRequestedBlobDataHandle(
558 request.get(),
559 blob_context->context()->GetBlobDataFromPublicURL(request->url()));
562 // From this point forward, the |DownloadResourceHandler| is responsible for
563 // |started_callback|.
564 scoped_ptr<ResourceHandler> handler(
565 CreateResourceHandlerForDownload(request.get(), is_content_initiated,
566 true, download_id, save_info.Pass(),
567 started_callback));
569 BeginRequestInternal(request.Pass(), handler.Pass());
571 return DOWNLOAD_INTERRUPT_REASON_NONE;
574 void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest(
575 net::URLRequest* request) {
576 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
577 if (info) {
578 ResourceLoader* loader = GetLoader(info->GetGlobalRequestID());
579 if (loader)
580 loader->ClearLoginDelegate();
584 void ResourceDispatcherHostImpl::Shutdown() {
585 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
586 BrowserThread::PostTask(BrowserThread::IO,
587 FROM_HERE,
588 base::Bind(&ResourceDispatcherHostImpl::OnShutdown,
589 base::Unretained(this)));
592 scoped_ptr<ResourceHandler>
593 ResourceDispatcherHostImpl::CreateResourceHandlerForDownload(
594 net::URLRequest* request,
595 bool is_content_initiated,
596 bool must_download,
597 uint32 id,
598 scoped_ptr<DownloadSaveInfo> save_info,
599 const DownloadUrlParameters::OnStartedCallback& started_cb) {
600 scoped_ptr<ResourceHandler> handler(
601 new DownloadResourceHandler(id, request, started_cb, save_info.Pass()));
602 if (delegate_) {
603 const ResourceRequestInfo* request_info(
604 ResourceRequestInfo::ForRequest(request));
606 ScopedVector<ResourceThrottle> throttles;
607 delegate_->DownloadStarting(
608 request, request_info->GetContext(), request_info->GetChildID(),
609 request_info->GetRouteID(), request_info->GetRequestID(),
610 is_content_initiated, must_download, &throttles);
611 if (!throttles.empty()) {
612 handler.reset(
613 new ThrottlingResourceHandler(
614 handler.Pass(), request, throttles.Pass()));
617 return handler.Pass();
620 scoped_ptr<ResourceHandler>
621 ResourceDispatcherHostImpl::MaybeInterceptAsStream(net::URLRequest* request,
622 ResourceResponse* response,
623 std::string* payload) {
624 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
625 const std::string& mime_type = response->head.mime_type;
627 GURL origin;
628 if (!delegate_ ||
629 !delegate_->ShouldInterceptResourceAsStream(request,
630 mime_type,
631 &origin,
632 payload)) {
633 return scoped_ptr<ResourceHandler>();
636 StreamContext* stream_context =
637 GetStreamContextForResourceContext(info->GetContext());
639 scoped_ptr<StreamResourceHandler> handler(
640 new StreamResourceHandler(request,
641 stream_context->registry(),
642 origin));
644 info->set_is_stream(true);
645 delegate_->OnStreamCreated(
646 request,
647 handler->stream()->CreateHandle(
648 request->url(),
649 mime_type,
650 response->head.headers));
651 return handler.PassAs<ResourceHandler>();
654 void ResourceDispatcherHostImpl::ClearSSLClientAuthHandlerForRequest(
655 net::URLRequest* request) {
656 ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request);
657 if (info) {
658 ResourceLoader* loader = GetLoader(info->GetGlobalRequestID());
659 if (loader)
660 loader->ClearSSLClientAuthHandler();
664 ResourceDispatcherHostLoginDelegate*
665 ResourceDispatcherHostImpl::CreateLoginDelegate(
666 ResourceLoader* loader,
667 net::AuthChallengeInfo* auth_info) {
668 if (!delegate_)
669 return NULL;
671 return delegate_->CreateLoginDelegate(auth_info, loader->request());
674 bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader* loader,
675 const GURL& url) {
676 if (!delegate_)
677 return false;
679 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
681 if (!ResourceType::IsFrame(info->GetResourceType()))
682 return false;
684 const net::URLRequestJobFactory* job_factory =
685 info->GetContext()->GetRequestContext()->job_factory();
686 if (job_factory->IsHandledURL(url))
687 return false;
689 bool initiated_by_user_gesture =
690 (loader->request()->load_flags() & net::LOAD_MAYBE_USER_GESTURE) != 0;
691 bool handled = delegate_->HandleExternalProtocol(url, info->GetChildID(),
692 info->GetRouteID(),
693 initiated_by_user_gesture);
694 // Consume the user gesture if the external protocol dialog is shown.
695 if (handled)
696 last_user_gesture_time_ = base::TimeTicks();
697 return handled;
700 void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader* loader) {
701 // Make sure we have the load state monitor running
702 if (!update_load_states_timer_->IsRunning()) {
703 update_load_states_timer_->Start(FROM_HERE,
704 TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec),
705 this, &ResourceDispatcherHostImpl::UpdateLoadStates);
709 void ResourceDispatcherHostImpl::DidReceiveRedirect(ResourceLoader* loader,
710 const GURL& new_url) {
711 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
713 int render_process_id, render_frame_host;
714 if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host))
715 return;
717 // Notify the observers on the UI thread.
718 scoped_ptr<ResourceRedirectDetails> detail(new ResourceRedirectDetails(
719 loader->request(),
720 GetCertID(loader->request(), info->GetChildID()),
721 new_url));
722 BrowserThread::PostTask(
723 BrowserThread::UI, FROM_HERE,
724 base::Bind(
725 &NotifyRedirectOnUI,
726 render_process_id, render_frame_host, base::Passed(&detail)));
729 void ResourceDispatcherHostImpl::DidReceiveResponse(ResourceLoader* loader) {
730 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
732 if (loader->request()->was_fetched_via_proxy() &&
733 loader->request()->was_fetched_via_spdy() &&
734 loader->request()->url().SchemeIs("http")) {
735 scheduler_->OnReceivedSpdyProxiedHttpResponse(
736 info->GetChildID(), info->GetRouteID());
739 int render_process_id, render_frame_host;
740 if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host))
741 return;
743 // Notify the observers on the UI thread.
744 scoped_ptr<ResourceRequestDetails> detail(new ResourceRequestDetails(
745 loader->request(),
746 GetCertID(loader->request(), info->GetChildID())));
747 BrowserThread::PostTask(
748 BrowserThread::UI, FROM_HERE,
749 base::Bind(
750 &NotifyResponseOnUI,
751 render_process_id, render_frame_host, base::Passed(&detail)));
754 void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader* loader) {
755 ResourceRequestInfo* info = loader->GetRequestInfo();
757 // Record final result of all resource loads.
758 if (info->GetResourceType() == ResourceType::MAIN_FRAME) {
759 // This enumeration has "3" appended to its name to distinguish it from
760 // older versions.
761 UMA_HISTOGRAM_SPARSE_SLOWLY(
762 "Net.ErrorCodesForMainFrame3",
763 -loader->request()->status().error());
765 if (loader->request()->url().SchemeIsSecure()) {
766 if (loader->request()->url().host() == "www.google.com") {
767 UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2",
768 -loader->request()->status().error());
771 int num_valid_scts = std::count_if(
772 loader->request()->ssl_info().signed_certificate_timestamps.begin(),
773 loader->request()->ssl_info().signed_certificate_timestamps.end(),
774 IsValidatedSCT);
775 UMA_HISTOGRAM_COUNTS_100(
776 "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts);
778 } else {
779 if (info->GetResourceType() == ResourceType::IMAGE) {
780 UMA_HISTOGRAM_SPARSE_SLOWLY(
781 "Net.ErrorCodesForImages",
782 -loader->request()->status().error());
784 // This enumeration has "2" appended to distinguish it from older versions.
785 UMA_HISTOGRAM_SPARSE_SLOWLY(
786 "Net.ErrorCodesForSubresources2",
787 -loader->request()->status().error());
790 if (delegate_)
791 delegate_->RequestComplete(loader->request());
793 // Destroy the ResourceLoader.
794 RemovePendingRequest(info->GetChildID(), info->GetRequestID());
797 void ResourceDispatcherHostImpl::OnInit() {
798 scheduler_.reset(new ResourceScheduler);
799 AppCacheInterceptor::EnsureRegistered();
802 void ResourceDispatcherHostImpl::OnShutdown() {
803 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
805 is_shutdown_ = true;
806 pending_loaders_.clear();
808 // Make sure we shutdown the timer now, otherwise by the time our destructor
809 // runs if the timer is still running the Task is deleted twice (once by
810 // the MessageLoop and the second time by RepeatingTimer).
811 update_load_states_timer_.reset();
813 // Clear blocked requests if any left.
814 // Note that we have to do this in 2 passes as we cannot call
815 // CancelBlockedRequestsForRoute while iterating over
816 // blocked_loaders_map_, as it modifies it.
817 std::set<GlobalRoutingID> ids;
818 for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
819 iter != blocked_loaders_map_.end(); ++iter) {
820 std::pair<std::set<GlobalRoutingID>::iterator, bool> result =
821 ids.insert(iter->first);
822 // We should not have duplicates.
823 DCHECK(result.second);
825 for (std::set<GlobalRoutingID>::const_iterator iter = ids.begin();
826 iter != ids.end(); ++iter) {
827 CancelBlockedRequestsForRoute(iter->child_id, iter->route_id);
830 scheduler_.reset();
833 bool ResourceDispatcherHostImpl::OnMessageReceived(
834 const IPC::Message& message,
835 ResourceMessageFilter* filter) {
836 filter_ = filter;
837 bool handled = true;
838 IPC_BEGIN_MESSAGE_MAP(ResourceDispatcherHostImpl, message)
839 IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource, OnRequestResource)
840 IPC_MESSAGE_HANDLER_DELAY_REPLY(ResourceHostMsg_SyncLoad, OnSyncLoad)
841 IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile,
842 OnReleaseDownloadedFile)
843 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataDownloaded_ACK, OnDataDownloadedACK)
844 IPC_MESSAGE_HANDLER(ResourceHostMsg_UploadProgress_ACK, OnUploadProgressACK)
845 IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest, OnCancelRequest)
846 IPC_MESSAGE_UNHANDLED(handled = false)
847 IPC_END_MESSAGE_MAP()
849 if (!handled && IPC_MESSAGE_ID_CLASS(message.type()) == ResourceMsgStart) {
850 PickleIterator iter(message);
851 int request_id = -1;
852 bool ok = iter.ReadInt(&request_id);
853 DCHECK(ok);
854 GlobalRequestID id(filter_->child_id(), request_id);
855 DelegateMap::iterator it = delegate_map_.find(id);
856 if (it != delegate_map_.end()) {
857 ObserverList<ResourceMessageDelegate>::Iterator del_it(*it->second);
858 ResourceMessageDelegate* delegate;
859 while (!handled && (delegate = del_it.GetNext()) != NULL) {
860 handled = delegate->OnMessageReceived(message);
864 // As the unhandled resource message effectively has no consumer, mark it as
865 // handled to prevent needless propagation through the filter pipeline.
866 handled = true;
869 filter_ = NULL;
870 return handled;
873 void ResourceDispatcherHostImpl::OnRequestResource(
874 int routing_id,
875 int request_id,
876 const ResourceHostMsg_Request& request_data) {
877 BeginRequest(request_id, request_data, NULL, routing_id);
880 // Begins a resource request with the given params on behalf of the specified
881 // child process. Responses will be dispatched through the given receiver. The
882 // process ID is used to lookup WebContentsImpl from routing_id's in the case of
883 // a request from a renderer. request_context is the cookie/cache context to be
884 // used for this request.
886 // If sync_result is non-null, then a SyncLoad reply will be generated, else
887 // a normal asynchronous set of response messages will be generated.
888 void ResourceDispatcherHostImpl::OnSyncLoad(
889 int request_id,
890 const ResourceHostMsg_Request& request_data,
891 IPC::Message* sync_result) {
892 BeginRequest(request_id, request_data, sync_result,
893 sync_result->routing_id());
896 void ResourceDispatcherHostImpl::UpdateRequestForTransfer(
897 int child_id,
898 int route_id,
899 int request_id,
900 const ResourceHostMsg_Request& request_data,
901 const linked_ptr<ResourceLoader>& loader) {
902 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
903 GlobalRoutingID old_routing_id(
904 request_data.transferred_request_child_id, info->GetRouteID());
905 GlobalRequestID old_request_id(request_data.transferred_request_child_id,
906 request_data.transferred_request_request_id);
907 GlobalRoutingID new_routing_id(child_id, route_id);
908 GlobalRequestID new_request_id(child_id, request_id);
910 // Clear out data that depends on |info| before updating it.
911 IncrementOutstandingRequestsMemory(-1, *info);
912 OustandingRequestsStats empty_stats = { 0, 0 };
913 OustandingRequestsStats old_stats = GetOutstandingRequestsStats(*info);
914 UpdateOutstandingRequestsStats(*info, empty_stats);
915 pending_loaders_.erase(old_request_id);
917 // ResourceHandlers should always get state related to the request from the
918 // ResourceRequestInfo rather than caching it locally. This lets us update
919 // the info object when a transfer occurs.
920 info->UpdateForTransfer(child_id, route_id, request_data.origin_pid,
921 request_id, request_data.parent_render_frame_id,
922 filter_->GetWeakPtr());
924 // Update maps that used the old IDs, if necessary. Some transfers in tests
925 // do not actually use a different ID, so not all maps need to be updated.
926 pending_loaders_[new_request_id] = loader;
927 UpdateOutstandingRequestsStats(*info, old_stats);
928 IncrementOutstandingRequestsMemory(1, *info);
929 if (old_routing_id != new_routing_id) {
930 if (blocked_loaders_map_.find(old_routing_id) !=
931 blocked_loaders_map_.end()) {
932 blocked_loaders_map_[new_routing_id] =
933 blocked_loaders_map_[old_routing_id];
934 blocked_loaders_map_.erase(old_routing_id);
937 if (old_request_id != new_request_id) {
938 DelegateMap::iterator it = delegate_map_.find(old_request_id);
939 if (it != delegate_map_.end()) {
940 // Tell each delegate that the request ID has changed.
941 ObserverList<ResourceMessageDelegate>::Iterator del_it(*it->second);
942 ResourceMessageDelegate* delegate;
943 while ((delegate = del_it.GetNext()) != NULL) {
944 delegate->set_request_id(new_request_id);
946 // Now store the observer list under the new request ID.
947 delegate_map_[new_request_id] = delegate_map_[old_request_id];
948 delegate_map_.erase(old_request_id);
952 AppCacheInterceptor::CompleteCrossSiteTransfer(
953 loader->request(),
954 child_id,
955 request_data.appcache_host_id);
957 // We should have a CrossSiteResourceHandler to finish the transfer.
958 DCHECK(info->cross_site_handler());
961 void ResourceDispatcherHostImpl::BeginRequest(
962 int request_id,
963 const ResourceHostMsg_Request& request_data,
964 IPC::Message* sync_result, // only valid for sync
965 int route_id) {
966 int process_type = filter_->process_type();
967 int child_id = filter_->child_id();
969 // Reject invalid priority.
970 if (request_data.priority < net::MINIMUM_PRIORITY ||
971 request_data.priority > net::MAXIMUM_PRIORITY) {
972 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
973 filter_->BadMessageReceived();
974 return;
977 // If we crash here, figure out what URL the renderer was requesting.
978 // http://crbug.com/91398
979 char url_buf[128];
980 base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf));
981 base::debug::Alias(url_buf);
983 // If the request that's coming in is being transferred from another process,
984 // we want to reuse and resume the old loader rather than start a new one.
986 LoaderMap::iterator it = pending_loaders_.find(
987 GlobalRequestID(request_data.transferred_request_child_id,
988 request_data.transferred_request_request_id));
989 if (it != pending_loaders_.end()) {
990 // If the request is transferring to a new process, we can update our
991 // state and let it resume with its existing ResourceHandlers.
992 if (it->second->is_transferring()) {
993 linked_ptr<ResourceLoader> deferred_loader = it->second;
994 UpdateRequestForTransfer(child_id, route_id, request_id,
995 request_data, deferred_loader);
997 deferred_loader->CompleteTransfer();
998 } else {
999 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1000 filter_->BadMessageReceived();
1002 return;
1006 ResourceContext* resource_context = NULL;
1007 net::URLRequestContext* request_context = NULL;
1008 filter_->GetContexts(request_data, &resource_context, &request_context);
1009 // http://crbug.com/90971
1010 CHECK(ContainsKey(active_resource_contexts_, resource_context));
1012 if (is_shutdown_ ||
1013 !ShouldServiceRequest(process_type, child_id, request_data,
1014 filter_->file_system_context())) {
1015 AbortRequestBeforeItStarts(filter_, sync_result, request_id);
1016 return;
1019 // Allow the observer to block/handle the request.
1020 if (delegate_ && !delegate_->ShouldBeginRequest(child_id,
1021 route_id,
1022 request_data.method,
1023 request_data.url,
1024 request_data.resource_type,
1025 resource_context)) {
1026 AbortRequestBeforeItStarts(filter_, sync_result, request_id);
1027 return;
1030 bool is_sync_load = sync_result != NULL;
1031 int load_flags =
1032 BuildLoadFlagsForRequest(request_data, child_id, is_sync_load);
1034 // Sync loads should have maximum priority and should be the only
1035 // requets that have the ignore limits flag set.
1036 if (is_sync_load) {
1037 DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY);
1038 DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1039 } else {
1040 DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0);
1043 // Construct the request.
1044 net::CookieStore* cookie_store =
1045 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1046 child_id);
1047 scoped_ptr<net::URLRequest> new_request;
1048 new_request = request_context->CreateRequest(
1049 request_data.url, request_data.priority, NULL, cookie_store);
1051 new_request->set_method(request_data.method);
1052 new_request->set_first_party_for_cookies(
1053 request_data.first_party_for_cookies);
1055 const Referrer referrer(request_data.referrer, request_data.referrer_policy);
1056 SetReferrerForRequest(new_request.get(), referrer);
1058 net::HttpRequestHeaders headers;
1059 headers.AddHeadersFromString(request_data.headers);
1060 new_request->SetExtraRequestHeaders(headers);
1062 new_request->SetLoadFlags(load_flags);
1064 // Resolve elements from request_body and prepare upload data.
1065 if (request_data.request_body.get()) {
1066 new_request->set_upload(UploadDataStreamBuilder::Build(
1067 request_data.request_body.get(),
1068 GetBlobStorageContext(filter_),
1069 filter_->file_system_context(),
1070 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
1071 .get()));
1074 bool allow_download = request_data.allow_download &&
1075 ResourceType::IsFrame(request_data.resource_type);
1077 // Make extra info and read footer (contains request ID).
1078 ResourceRequestInfoImpl* extra_info =
1079 new ResourceRequestInfoImpl(
1080 process_type,
1081 child_id,
1082 route_id,
1083 request_data.origin_pid,
1084 request_id,
1085 request_data.render_frame_id,
1086 request_data.is_main_frame,
1087 request_data.parent_is_main_frame,
1088 request_data.parent_render_frame_id,
1089 request_data.resource_type,
1090 request_data.transition_type,
1091 request_data.should_replace_current_entry,
1092 false, // is download
1093 false, // is stream
1094 allow_download,
1095 request_data.has_user_gesture,
1096 request_data.referrer_policy,
1097 request_data.visiblity_state,
1098 resource_context,
1099 filter_->GetWeakPtr(),
1100 !is_sync_load);
1101 // Request takes ownership.
1102 extra_info->AssociateWithRequest(new_request.get());
1104 if (new_request->url().SchemeIs(url::kBlobScheme)) {
1105 // Hang on to a reference to ensure the blob is not released prior
1106 // to the job being started.
1107 webkit_blob::BlobProtocolHandler::SetRequestedBlobDataHandle(
1108 new_request.get(),
1109 filter_->blob_storage_context()->context()->
1110 GetBlobDataFromPublicURL(new_request->url()));
1113 // Initialize the service worker handler for the request.
1114 ServiceWorkerRequestHandler::InitializeHandler(
1115 new_request.get(),
1116 filter_->service_worker_context(),
1117 GetBlobStorageContext(filter_),
1118 child_id,
1119 request_data.service_worker_provider_id,
1120 request_data.resource_type);
1122 // Have the appcache associate its extra info with the request.
1123 AppCacheInterceptor::SetExtraRequestInfo(
1124 new_request.get(), filter_->appcache_service(), child_id,
1125 request_data.appcache_host_id, request_data.resource_type);
1127 scoped_ptr<ResourceHandler> handler(
1128 CreateResourceHandler(
1129 new_request.get(),
1130 request_data, sync_result, route_id, process_type, child_id,
1131 resource_context));
1133 if (handler)
1134 BeginRequestInternal(new_request.Pass(), handler.Pass());
1137 scoped_ptr<ResourceHandler> ResourceDispatcherHostImpl::CreateResourceHandler(
1138 net::URLRequest* request,
1139 const ResourceHostMsg_Request& request_data,
1140 IPC::Message* sync_result,
1141 int route_id,
1142 int process_type,
1143 int child_id,
1144 ResourceContext* resource_context) {
1145 // Construct the IPC resource handler.
1146 scoped_ptr<ResourceHandler> handler;
1147 if (sync_result) {
1148 // download_to_file is not supported for synchronous requests.
1149 if (request_data.download_to_file) {
1150 RecordAction(base::UserMetricsAction("BadMessageTerminate_RDH"));
1151 filter_->BadMessageReceived();
1152 return scoped_ptr<ResourceHandler>();
1155 handler.reset(new SyncResourceHandler(request, sync_result, this));
1156 } else {
1157 handler.reset(new AsyncResourceHandler(request, this));
1159 // The RedirectToFileResourceHandler depends on being next in the chain.
1160 if (request_data.download_to_file) {
1161 handler.reset(
1162 new RedirectToFileResourceHandler(handler.Pass(), request));
1166 // Prefetches and <a ping> requests outlive their child process.
1167 if (!sync_result && IsDetachableResourceType(request_data.resource_type)) {
1168 handler.reset(new DetachableResourceHandler(
1169 request,
1170 base::TimeDelta::FromMilliseconds(kDefaultDetachableCancelDelayMs),
1171 handler.Pass()));
1174 // Install a CrossSiteResourceHandler for all main frame requests. This will
1175 // let us check whether a transfer is required and pause for the unload
1176 // handler either if so or if a cross-process navigation is already under way.
1177 bool is_swappable_navigation =
1178 request_data.resource_type == ResourceType::MAIN_FRAME;
1179 // If we are using --site-per-process, install it for subframes as well.
1180 if (!is_swappable_navigation &&
1181 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess)) {
1182 is_swappable_navigation =
1183 request_data.resource_type == ResourceType::SUB_FRAME;
1185 if (is_swappable_navigation && process_type == PROCESS_TYPE_RENDERER)
1186 handler.reset(new CrossSiteResourceHandler(handler.Pass(), request));
1188 // Insert a buffered event handler before the actual one.
1189 handler.reset(
1190 new BufferedResourceHandler(handler.Pass(), this, request));
1192 ScopedVector<ResourceThrottle> throttles;
1193 if (delegate_) {
1194 delegate_->RequestBeginning(request,
1195 resource_context,
1196 filter_->appcache_service(),
1197 request_data.resource_type,
1198 child_id,
1199 route_id,
1200 &throttles);
1203 if (request->has_upload()) {
1204 // Block power save while uploading data.
1205 throttles.push_back(new PowerSaveBlockResourceThrottle());
1208 throttles.push_back(
1209 scheduler_->ScheduleRequest(child_id, route_id, request).release());
1211 handler.reset(
1212 new ThrottlingResourceHandler(handler.Pass(), request, throttles.Pass()));
1214 return handler.Pass();
1217 void ResourceDispatcherHostImpl::OnReleaseDownloadedFile(int request_id) {
1218 UnregisterDownloadedTempFile(filter_->child_id(), request_id);
1221 void ResourceDispatcherHostImpl::OnDataDownloadedACK(int request_id) {
1222 // TODO(michaeln): maybe throttle DataDownloaded messages
1225 void ResourceDispatcherHostImpl::RegisterDownloadedTempFile(
1226 int child_id, int request_id, const base::FilePath& file_path) {
1227 scoped_refptr<ShareableFileReference> reference =
1228 ShareableFileReference::Get(file_path);
1229 DCHECK(reference);
1231 registered_temp_files_[child_id][request_id] = reference;
1232 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1233 child_id, reference->path());
1235 // When the temp file is deleted, revoke permissions that the renderer has
1236 // to that file. This covers an edge case where the file is deleted and then
1237 // the same name is re-used for some other purpose, we don't want the old
1238 // renderer to still have access to it.
1240 // We do this when the file is deleted because the renderer can take a blob
1241 // reference to the temp file that outlives the url loaded that it was
1242 // loaded with to keep the file (and permissions) alive.
1243 reference->AddFinalReleaseCallback(
1244 base::Bind(&RemoveDownloadFileFromChildSecurityPolicy,
1245 child_id));
1248 void ResourceDispatcherHostImpl::UnregisterDownloadedTempFile(
1249 int child_id, int request_id) {
1250 DeletableFilesMap& map = registered_temp_files_[child_id];
1251 DeletableFilesMap::iterator found = map.find(request_id);
1252 if (found == map.end())
1253 return;
1255 map.erase(found);
1257 // Note that we don't remove the security bits here. This will be done
1258 // when all file refs are deleted (see RegisterDownloadedTempFile).
1261 bool ResourceDispatcherHostImpl::Send(IPC::Message* message) {
1262 delete message;
1263 return false;
1266 void ResourceDispatcherHostImpl::OnUploadProgressACK(int request_id) {
1267 ResourceLoader* loader = GetLoader(filter_->child_id(), request_id);
1268 if (loader)
1269 loader->OnUploadProgressACK();
1272 // Note that this cancel is subtly different from the other
1273 // CancelRequest methods in this file, which also tear down the loader.
1274 void ResourceDispatcherHostImpl::OnCancelRequest(int request_id) {
1275 int child_id = filter_->child_id();
1277 // When the old renderer dies, it sends a message to us to cancel its
1278 // requests.
1279 if (IsTransferredNavigation(GlobalRequestID(child_id, request_id)))
1280 return;
1282 ResourceLoader* loader = GetLoader(child_id, request_id);
1283 if (!loader) {
1284 // We probably want to remove this warning eventually, but I wanted to be
1285 // able to notice when this happens during initial development since it
1286 // should be rare and may indicate a bug.
1287 DVLOG(1) << "Canceling a request that wasn't found";
1288 return;
1291 loader->CancelRequest(true);
1294 ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo(
1295 int child_id,
1296 int route_id,
1297 bool download,
1298 ResourceContext* context) {
1299 return new ResourceRequestInfoImpl(
1300 PROCESS_TYPE_RENDERER,
1301 child_id,
1302 route_id,
1304 request_id_,
1305 MSG_ROUTING_NONE, // render_frame_id
1306 false, // is_main_frame
1307 false, // parent_is_main_frame
1308 -1, // parent_render_frame_id
1309 ResourceType::SUB_RESOURCE,
1310 PAGE_TRANSITION_LINK,
1311 false, // should_replace_current_entry
1312 download, // is_download
1313 false, // is_stream
1314 download, // allow_download
1315 false, // has_user_gesture
1316 blink::WebReferrerPolicyDefault,
1317 blink::WebPageVisibilityStateVisible,
1318 context,
1319 base::WeakPtr<ResourceMessageFilter>(), // filter
1320 true); // is_async
1323 void ResourceDispatcherHostImpl::OnRenderViewHostCreated(
1324 int child_id,
1325 int route_id) {
1326 scheduler_->OnClientCreated(child_id, route_id);
1329 void ResourceDispatcherHostImpl::OnRenderViewHostDeleted(
1330 int child_id,
1331 int route_id) {
1332 scheduler_->OnClientDeleted(child_id, route_id);
1333 CancelRequestsForRoute(child_id, route_id);
1336 // This function is only used for saving feature.
1337 void ResourceDispatcherHostImpl::BeginSaveFile(
1338 const GURL& url,
1339 const Referrer& referrer,
1340 int child_id,
1341 int route_id,
1342 ResourceContext* context) {
1343 if (is_shutdown_)
1344 return;
1346 // http://crbug.com/90971
1347 char url_buf[128];
1348 base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
1349 base::debug::Alias(url_buf);
1350 CHECK(ContainsKey(active_resource_contexts_, context));
1352 request_id_--;
1354 const net::URLRequestContext* request_context = context->GetRequestContext();
1355 bool known_proto =
1356 request_context->job_factory()->IsHandledURL(url);
1357 if (!known_proto) {
1358 // Since any URLs which have non-standard scheme have been filtered
1359 // by save manager(see GURL::SchemeIsStandard). This situation
1360 // should not happen.
1361 NOTREACHED();
1362 return;
1365 net::CookieStore* cookie_store =
1366 GetContentClient()->browser()->OverrideCookieStoreForRenderProcess(
1367 child_id);
1368 scoped_ptr<net::URLRequest> request(
1369 request_context->CreateRequest(url, net::DEFAULT_PRIORITY, NULL,
1370 cookie_store));
1372 request->set_method("GET");
1373 SetReferrerForRequest(request.get(), referrer);
1375 // So far, for saving page, we need fetch content from cache, in the
1376 // future, maybe we can use a configuration to configure this behavior.
1377 request->SetLoadFlags(net::LOAD_PREFERRING_CACHE);
1379 // Since we're just saving some resources we need, disallow downloading.
1380 ResourceRequestInfoImpl* extra_info =
1381 CreateRequestInfo(child_id, route_id, false, context);
1382 extra_info->AssociateWithRequest(request.get()); // Request takes ownership.
1384 scoped_ptr<ResourceHandler> handler(
1385 new SaveFileResourceHandler(request.get(),
1386 child_id,
1387 route_id,
1388 url,
1389 save_file_manager_.get()));
1391 BeginRequestInternal(request.Pass(), handler.Pass());
1394 void ResourceDispatcherHostImpl::MarkAsTransferredNavigation(
1395 const GlobalRequestID& id) {
1396 GetLoader(id)->MarkAsTransferring();
1399 void ResourceDispatcherHostImpl::CancelTransferringNavigation(
1400 const GlobalRequestID& id) {
1401 // Request should still exist and be in the middle of a transfer.
1402 DCHECK(IsTransferredNavigation(id));
1403 RemovePendingRequest(id.child_id, id.request_id);
1406 void ResourceDispatcherHostImpl::ResumeDeferredNavigation(
1407 const GlobalRequestID& id) {
1408 ResourceLoader* loader = GetLoader(id);
1409 if (loader) {
1410 // The response we were meant to resume could have already been canceled.
1411 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
1412 if (info->cross_site_handler())
1413 info->cross_site_handler()->ResumeResponse();
1417 // The object died, so cancel and detach all requests associated with it except
1418 // for downloads and detachable resources, which belong to the browser process
1419 // even if initiated via a renderer.
1420 void ResourceDispatcherHostImpl::CancelRequestsForProcess(int child_id) {
1421 CancelRequestsForRoute(child_id, -1 /* cancel all */);
1422 registered_temp_files_.erase(child_id);
1425 void ResourceDispatcherHostImpl::CancelRequestsForRoute(int child_id,
1426 int route_id) {
1427 // Since pending_requests_ is a map, we first build up a list of all of the
1428 // matching requests to be cancelled, and then we cancel them. Since there
1429 // may be more than one request to cancel, we cannot simply hold onto the map
1430 // iterators found in the first loop.
1432 // Find the global ID of all matching elements.
1433 bool any_requests_transferring = false;
1434 std::vector<GlobalRequestID> matching_requests;
1435 for (LoaderMap::const_iterator i = pending_loaders_.begin();
1436 i != pending_loaders_.end(); ++i) {
1437 if (i->first.child_id != child_id)
1438 continue;
1440 ResourceRequestInfoImpl* info = i->second->GetRequestInfo();
1442 GlobalRequestID id(child_id, i->first.request_id);
1443 DCHECK(id == i->first);
1444 // Don't cancel navigations that are expected to live beyond this process.
1445 if (IsTransferredNavigation(id))
1446 any_requests_transferring = true;
1447 if (info->detachable_handler()) {
1448 info->detachable_handler()->Detach();
1449 } else if (!info->IsDownload() && !info->is_stream() &&
1450 !IsTransferredNavigation(id) &&
1451 (route_id == -1 || route_id == info->GetRouteID())) {
1452 matching_requests.push_back(id);
1456 // Remove matches.
1457 for (size_t i = 0; i < matching_requests.size(); ++i) {
1458 LoaderMap::iterator iter = pending_loaders_.find(matching_requests[i]);
1459 // Although every matching request was in pending_requests_ when we built
1460 // matching_requests, it is normal for a matching request to be not found
1461 // in pending_requests_ after we have removed some matching requests from
1462 // pending_requests_. For example, deleting a net::URLRequest that has
1463 // exclusive (write) access to an HTTP cache entry may unblock another
1464 // net::URLRequest that needs exclusive access to the same cache entry, and
1465 // that net::URLRequest may complete and remove itself from
1466 // pending_requests_. So we need to check that iter is not equal to
1467 // pending_requests_.end().
1468 if (iter != pending_loaders_.end())
1469 RemovePendingLoader(iter);
1472 // Don't clear the blocked loaders or offline policy maps if any of the
1473 // requests in route_id are being transferred to a new process, since those
1474 // maps will be updated with the new route_id after the transfer. Otherwise
1475 // we will lose track of this info when the old route goes away, before the
1476 // new one is created.
1477 if (any_requests_transferring)
1478 return;
1480 // Now deal with blocked requests if any.
1481 if (route_id != -1) {
1482 if (blocked_loaders_map_.find(GlobalRoutingID(child_id, route_id)) !=
1483 blocked_loaders_map_.end()) {
1484 CancelBlockedRequestsForRoute(child_id, route_id);
1486 } else {
1487 // We have to do all render views for the process |child_id|.
1488 // Note that we have to do this in 2 passes as we cannot call
1489 // CancelBlockedRequestsForRoute while iterating over
1490 // blocked_loaders_map_, as it modifies it.
1491 std::set<int> route_ids;
1492 for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin();
1493 iter != blocked_loaders_map_.end(); ++iter) {
1494 if (iter->first.child_id == child_id)
1495 route_ids.insert(iter->first.route_id);
1497 for (std::set<int>::const_iterator iter = route_ids.begin();
1498 iter != route_ids.end(); ++iter) {
1499 CancelBlockedRequestsForRoute(child_id, *iter);
1504 // Cancels the request and removes it from the list.
1505 void ResourceDispatcherHostImpl::RemovePendingRequest(int child_id,
1506 int request_id) {
1507 LoaderMap::iterator i = pending_loaders_.find(
1508 GlobalRequestID(child_id, request_id));
1509 if (i == pending_loaders_.end()) {
1510 NOTREACHED() << "Trying to remove a request that's not here";
1511 return;
1513 RemovePendingLoader(i);
1516 void ResourceDispatcherHostImpl::RemovePendingLoader(
1517 const LoaderMap::iterator& iter) {
1518 ResourceRequestInfoImpl* info = iter->second->GetRequestInfo();
1520 // Remove the memory credit that we added when pushing the request onto
1521 // the pending list.
1522 IncrementOutstandingRequestsMemory(-1, *info);
1524 pending_loaders_.erase(iter);
1526 // If we have no more pending requests, then stop the load state monitor
1527 if (pending_loaders_.empty() && update_load_states_timer_)
1528 update_load_states_timer_->Stop();
1531 void ResourceDispatcherHostImpl::CancelRequest(int child_id,
1532 int request_id) {
1533 ResourceLoader* loader = GetLoader(child_id, request_id);
1534 if (!loader) {
1535 // We probably want to remove this warning eventually, but I wanted to be
1536 // able to notice when this happens during initial development since it
1537 // should be rare and may indicate a bug.
1538 DVLOG(1) << "Canceling a request that wasn't found";
1539 return;
1542 RemovePendingRequest(child_id, request_id);
1545 ResourceDispatcherHostImpl::OustandingRequestsStats
1546 ResourceDispatcherHostImpl::GetOutstandingRequestsStats(
1547 const ResourceRequestInfoImpl& info) {
1548 OutstandingRequestsStatsMap::iterator entry =
1549 outstanding_requests_stats_map_.find(info.GetChildID());
1550 OustandingRequestsStats stats = { 0, 0 };
1551 if (entry != outstanding_requests_stats_map_.end())
1552 stats = entry->second;
1553 return stats;
1556 void ResourceDispatcherHostImpl::UpdateOutstandingRequestsStats(
1557 const ResourceRequestInfoImpl& info,
1558 const OustandingRequestsStats& stats) {
1559 if (stats.memory_cost == 0 && stats.num_requests == 0)
1560 outstanding_requests_stats_map_.erase(info.GetChildID());
1561 else
1562 outstanding_requests_stats_map_[info.GetChildID()] = stats;
1565 ResourceDispatcherHostImpl::OustandingRequestsStats
1566 ResourceDispatcherHostImpl::IncrementOutstandingRequestsMemory(
1567 int count,
1568 const ResourceRequestInfoImpl& info) {
1569 DCHECK_EQ(1, abs(count));
1571 // Retrieve the previous value (defaulting to 0 if not found).
1572 OustandingRequestsStats stats = GetOutstandingRequestsStats(info);
1574 // Insert/update the total; delete entries when their count reaches 0.
1575 stats.memory_cost += count * info.memory_cost();
1576 DCHECK_GE(stats.memory_cost, 0);
1577 UpdateOutstandingRequestsStats(info, stats);
1579 return stats;
1582 ResourceDispatcherHostImpl::OustandingRequestsStats
1583 ResourceDispatcherHostImpl::IncrementOutstandingRequestsCount(
1584 int count,
1585 const ResourceRequestInfoImpl& info) {
1586 DCHECK_EQ(1, abs(count));
1587 num_in_flight_requests_ += count;
1589 OustandingRequestsStats stats = GetOutstandingRequestsStats(info);
1590 stats.num_requests += count;
1591 DCHECK_GE(stats.num_requests, 0);
1592 UpdateOutstandingRequestsStats(info, stats);
1594 return stats;
1597 bool ResourceDispatcherHostImpl::HasSufficientResourcesForRequest(
1598 const net::URLRequest* request_) {
1599 const ResourceRequestInfoImpl* info =
1600 ResourceRequestInfoImpl::ForRequest(request_);
1601 OustandingRequestsStats stats = IncrementOutstandingRequestsCount(1, *info);
1603 if (stats.num_requests > max_num_in_flight_requests_per_process_)
1604 return false;
1605 if (num_in_flight_requests_ > max_num_in_flight_requests_)
1606 return false;
1608 return true;
1611 void ResourceDispatcherHostImpl::FinishedWithResourcesForRequest(
1612 const net::URLRequest* request_) {
1613 const ResourceRequestInfoImpl* info =
1614 ResourceRequestInfoImpl::ForRequest(request_);
1615 IncrementOutstandingRequestsCount(-1, *info);
1618 void ResourceDispatcherHostImpl::NavigationRequest(
1619 const NavigationRequestInfo& info,
1620 scoped_refptr<ResourceRequestBody> request_body,
1621 int64 frame_node_id) {
1622 NOTIMPLEMENTED();
1625 // static
1626 int ResourceDispatcherHostImpl::CalculateApproximateMemoryCost(
1627 net::URLRequest* request) {
1628 // The following fields should be a minor size contribution (experimentally
1629 // on the order of 100). However since they are variable length, it could
1630 // in theory be a sizeable contribution.
1631 int strings_cost = request->extra_request_headers().ToString().size() +
1632 request->original_url().spec().size() +
1633 request->referrer().size() +
1634 request->method().size();
1636 // Note that this expression will typically be dominated by:
1637 // |kAvgBytesPerOutstandingRequest|.
1638 return kAvgBytesPerOutstandingRequest + strings_cost;
1641 void ResourceDispatcherHostImpl::BeginRequestInternal(
1642 scoped_ptr<net::URLRequest> request,
1643 scoped_ptr<ResourceHandler> handler) {
1644 DCHECK(!request->is_pending());
1645 ResourceRequestInfoImpl* info =
1646 ResourceRequestInfoImpl::ForRequest(request.get());
1648 if ((TimeTicks::Now() - last_user_gesture_time_) <
1649 TimeDelta::FromMilliseconds(kUserGestureWindowMs)) {
1650 request->SetLoadFlags(
1651 request->load_flags() | net::LOAD_MAYBE_USER_GESTURE);
1654 // Add the memory estimate that starting this request will consume.
1655 info->set_memory_cost(CalculateApproximateMemoryCost(request.get()));
1657 // If enqueing/starting this request will exceed our per-process memory
1658 // bound, abort it right away.
1659 OustandingRequestsStats stats = IncrementOutstandingRequestsMemory(1, *info);
1660 if (stats.memory_cost > max_outstanding_requests_cost_per_process_) {
1661 // We call "CancelWithError()" as a way of setting the net::URLRequest's
1662 // status -- it has no effect beyond this, since the request hasn't started.
1663 request->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
1665 bool defer = false;
1666 handler->OnResponseCompleted(request->status(), std::string(), &defer);
1667 if (defer) {
1668 // TODO(darin): The handler is not ready for us to kill the request. Oops!
1669 NOTREACHED();
1672 IncrementOutstandingRequestsMemory(-1, *info);
1674 // A ResourceHandler must not outlive its associated URLRequest.
1675 handler.reset();
1676 return;
1679 linked_ptr<ResourceLoader> loader(
1680 new ResourceLoader(request.Pass(), handler.Pass(), this));
1682 GlobalRoutingID id(info->GetGlobalRoutingID());
1683 BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.find(id);
1684 if (iter != blocked_loaders_map_.end()) {
1685 // The request should be blocked.
1686 iter->second->push_back(loader);
1687 return;
1690 StartLoading(info, loader);
1693 void ResourceDispatcherHostImpl::StartLoading(
1694 ResourceRequestInfoImpl* info,
1695 const linked_ptr<ResourceLoader>& loader) {
1696 pending_loaders_[info->GetGlobalRequestID()] = loader;
1698 loader->StartRequest();
1701 void ResourceDispatcherHostImpl::OnUserGesture(WebContentsImpl* contents) {
1702 last_user_gesture_time_ = TimeTicks::Now();
1705 net::URLRequest* ResourceDispatcherHostImpl::GetURLRequest(
1706 const GlobalRequestID& id) {
1707 ResourceLoader* loader = GetLoader(id);
1708 if (!loader)
1709 return NULL;
1711 return loader->request();
1714 namespace {
1716 // This function attempts to return the "more interesting" load state of |a|
1717 // and |b|. We don't have temporal information about these load states
1718 // (meaning we don't know when we transitioned into these states), so we just
1719 // rank them according to how "interesting" the states are.
1721 // We take advantage of the fact that the load states are an enumeration listed
1722 // in the order in which they occur during the lifetime of a request, so we can
1723 // regard states with larger numeric values as being further along toward
1724 // completion. We regard those states as more interesting to report since they
1725 // represent progress.
1727 // For example, by this measure "tranferring data" is a more interesting state
1728 // than "resolving host" because when we are transferring data we are actually
1729 // doing something that corresponds to changes that the user might observe,
1730 // whereas waiting for a host name to resolve implies being stuck.
1732 const net::LoadStateWithParam& MoreInterestingLoadState(
1733 const net::LoadStateWithParam& a, const net::LoadStateWithParam& b) {
1734 return (a.state < b.state) ? b : a;
1737 // Carries information about a load state change.
1738 struct LoadInfo {
1739 GURL url;
1740 net::LoadStateWithParam load_state;
1741 uint64 upload_position;
1742 uint64 upload_size;
1745 // Map from ProcessID+RouteID pair to LoadState
1746 typedef std::map<GlobalRoutingID, LoadInfo> LoadInfoMap;
1748 // Used to marshal calls to LoadStateChanged from the IO to UI threads. We do
1749 // them all as a single callback to avoid spamming the UI thread.
1750 void LoadInfoUpdateCallback(const LoadInfoMap& info_map) {
1751 LoadInfoMap::const_iterator i;
1752 for (i = info_map.begin(); i != info_map.end(); ++i) {
1753 RenderViewHostImpl* view =
1754 RenderViewHostImpl::FromID(i->first.child_id, i->first.route_id);
1755 if (view) // The view could be gone at this point.
1756 view->LoadStateChanged(i->second.url, i->second.load_state,
1757 i->second.upload_position,
1758 i->second.upload_size);
1762 } // namespace
1764 void ResourceDispatcherHostImpl::UpdateLoadStates() {
1765 // Populate this map with load state changes, and then send them on to the UI
1766 // thread where they can be passed along to the respective RVHs.
1767 LoadInfoMap info_map;
1769 LoaderMap::const_iterator i;
1771 // Determine the largest upload size of all requests
1772 // in each View (good chance it's zero).
1773 std::map<GlobalRoutingID, uint64> largest_upload_size;
1774 for (i = pending_loaders_.begin(); i != pending_loaders_.end(); ++i) {
1775 net::URLRequest* request = i->second->request();
1776 ResourceRequestInfoImpl* info = i->second->GetRequestInfo();
1777 uint64 upload_size = request->GetUploadProgress().size();
1778 if (request->GetLoadState().state != net::LOAD_STATE_SENDING_REQUEST)
1779 upload_size = 0;
1780 GlobalRoutingID id(info->GetGlobalRoutingID());
1781 if (upload_size && largest_upload_size[id] < upload_size)
1782 largest_upload_size[id] = upload_size;
1785 for (i = pending_loaders_.begin(); i != pending_loaders_.end(); ++i) {
1786 net::URLRequest* request = i->second->request();
1787 ResourceRequestInfoImpl* info = i->second->GetRequestInfo();
1788 net::LoadStateWithParam load_state = request->GetLoadState();
1789 net::UploadProgress progress = request->GetUploadProgress();
1791 // We also poll for upload progress on this timer and send upload
1792 // progress ipc messages to the plugin process.
1793 i->second->ReportUploadProgress();
1795 GlobalRoutingID id(info->GetGlobalRoutingID());
1797 // If a request is uploading data, ignore all other requests so that the
1798 // upload progress takes priority for being shown in the status bar.
1799 if (largest_upload_size.find(id) != largest_upload_size.end() &&
1800 progress.size() < largest_upload_size[id])
1801 continue;
1803 net::LoadStateWithParam to_insert = load_state;
1804 LoadInfoMap::iterator existing = info_map.find(id);
1805 if (existing != info_map.end()) {
1806 to_insert =
1807 MoreInterestingLoadState(existing->second.load_state, load_state);
1808 if (to_insert.state == existing->second.load_state.state)
1809 continue;
1811 LoadInfo& load_info = info_map[id];
1812 load_info.url = request->url();
1813 load_info.load_state = to_insert;
1814 load_info.upload_size = progress.size();
1815 load_info.upload_position = progress.position();
1818 if (info_map.empty())
1819 return;
1821 BrowserThread::PostTask(
1822 BrowserThread::UI, FROM_HERE,
1823 base::Bind(&LoadInfoUpdateCallback, info_map));
1826 void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id,
1827 int route_id) {
1828 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1829 GlobalRoutingID key(child_id, route_id);
1830 DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) <<
1831 "BlockRequestsForRoute called multiple time for the same RVH";
1832 blocked_loaders_map_[key] = new BlockedLoadersList();
1835 void ResourceDispatcherHostImpl::ResumeBlockedRequestsForRoute(int child_id,
1836 int route_id) {
1837 ProcessBlockedRequestsForRoute(child_id, route_id, false);
1840 void ResourceDispatcherHostImpl::CancelBlockedRequestsForRoute(int child_id,
1841 int route_id) {
1842 ProcessBlockedRequestsForRoute(child_id, route_id, true);
1845 void ResourceDispatcherHostImpl::ProcessBlockedRequestsForRoute(
1846 int child_id,
1847 int route_id,
1848 bool cancel_requests) {
1849 BlockedLoadersMap::iterator iter = blocked_loaders_map_.find(
1850 GlobalRoutingID(child_id, route_id));
1851 if (iter == blocked_loaders_map_.end()) {
1852 // It's possible to reach here if the renderer crashed while an interstitial
1853 // page was showing.
1854 return;
1857 BlockedLoadersList* loaders = iter->second;
1859 // Removing the vector from the map unblocks any subsequent requests.
1860 blocked_loaders_map_.erase(iter);
1862 for (BlockedLoadersList::iterator loaders_iter = loaders->begin();
1863 loaders_iter != loaders->end(); ++loaders_iter) {
1864 linked_ptr<ResourceLoader> loader = *loaders_iter;
1865 ResourceRequestInfoImpl* info = loader->GetRequestInfo();
1866 if (cancel_requests) {
1867 IncrementOutstandingRequestsMemory(-1, *info);
1868 } else {
1869 StartLoading(info, loader);
1873 delete loaders;
1876 ResourceDispatcherHostImpl::HttpAuthRelationType
1877 ResourceDispatcherHostImpl::HttpAuthRelationTypeOf(
1878 const GURL& request_url,
1879 const GURL& first_party) {
1880 if (!first_party.is_valid())
1881 return HTTP_AUTH_RELATION_TOP;
1883 if (net::registry_controlled_domains::SameDomainOrHost(
1884 first_party, request_url,
1885 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES))
1886 return HTTP_AUTH_RELATION_SAME_DOMAIN;
1888 if (allow_cross_origin_auth_prompt())
1889 return HTTP_AUTH_RELATION_ALLOWED_CROSS;
1891 return HTTP_AUTH_RELATION_BLOCKED_CROSS;
1894 bool ResourceDispatcherHostImpl::allow_cross_origin_auth_prompt() {
1895 return allow_cross_origin_auth_prompt_;
1898 bool ResourceDispatcherHostImpl::IsTransferredNavigation(
1899 const GlobalRequestID& id) const {
1900 ResourceLoader* loader = GetLoader(id);
1901 return loader ? loader->is_transferring() : false;
1904 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(
1905 const GlobalRequestID& id) const {
1906 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1908 LoaderMap::const_iterator i = pending_loaders_.find(id);
1909 if (i == pending_loaders_.end())
1910 return NULL;
1912 return i->second.get();
1915 ResourceLoader* ResourceDispatcherHostImpl::GetLoader(int child_id,
1916 int request_id) const {
1917 return GetLoader(GlobalRequestID(child_id, request_id));
1920 void ResourceDispatcherHostImpl::RegisterResourceMessageDelegate(
1921 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
1922 DelegateMap::iterator it = delegate_map_.find(id);
1923 if (it == delegate_map_.end()) {
1924 it = delegate_map_.insert(
1925 std::make_pair(id, new ObserverList<ResourceMessageDelegate>)).first;
1927 it->second->AddObserver(delegate);
1930 void ResourceDispatcherHostImpl::UnregisterResourceMessageDelegate(
1931 const GlobalRequestID& id, ResourceMessageDelegate* delegate) {
1932 DCHECK(ContainsKey(delegate_map_, id));
1933 DelegateMap::iterator it = delegate_map_.find(id);
1934 DCHECK(it->second->HasObserver(delegate));
1935 it->second->RemoveObserver(delegate);
1936 if (!it->second->might_have_observers()) {
1937 delete it->second;
1938 delegate_map_.erase(it);
1942 int ResourceDispatcherHostImpl::BuildLoadFlagsForRequest(
1943 const ResourceHostMsg_Request& request_data,
1944 int child_id,
1945 bool is_sync_load) {
1946 int load_flags = request_data.load_flags;
1948 // Although EV status is irrelevant to sub-frames and sub-resources, we have
1949 // to perform EV certificate verification on all resources because an HTTP
1950 // keep-alive connection created to load a sub-frame or a sub-resource could
1951 // be reused to load a main frame.
1952 load_flags |= net::LOAD_VERIFY_EV_CERT;
1953 if (request_data.resource_type == ResourceType::MAIN_FRAME) {
1954 load_flags |= net::LOAD_MAIN_FRAME;
1955 } else if (request_data.resource_type == ResourceType::SUB_FRAME) {
1956 load_flags |= net::LOAD_SUB_FRAME;
1957 } else if (request_data.resource_type == ResourceType::PREFETCH) {
1958 load_flags |= (net::LOAD_PREFETCH | net::LOAD_DO_NOT_PROMPT_FOR_LOGIN);
1959 } else if (request_data.resource_type == ResourceType::FAVICON) {
1960 load_flags |= net::LOAD_DO_NOT_PROMPT_FOR_LOGIN;
1961 } else if (request_data.resource_type == ResourceType::IMAGE) {
1962 // Prevent third-party image content from prompting for login, as this
1963 // is often a scam to extract credentials for another domain from the user.
1964 // Only block image loads, as the attack applies largely to the "src"
1965 // property of the <img> tag. It is common for web properties to allow
1966 // untrusted values for <img src>; this is considered a fair thing for an
1967 // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't
1968 // filter sources for <script>, <link>, <embed>, <object>, <iframe> tags
1969 // would be considered vulnerable in and of itself.
1970 HttpAuthRelationType relation_type = HttpAuthRelationTypeOf(
1971 request_data.url, request_data.first_party_for_cookies);
1972 if (relation_type == HTTP_AUTH_RELATION_BLOCKED_CROSS) {
1973 load_flags |= (net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY |
1974 net::LOAD_DO_NOT_PROMPT_FOR_LOGIN);
1978 if (is_sync_load)
1979 load_flags |= net::LOAD_IGNORE_LIMITS;
1981 ChildProcessSecurityPolicyImpl* policy =
1982 ChildProcessSecurityPolicyImpl::GetInstance();
1983 if (!policy->CanSendCookiesForOrigin(child_id, request_data.url)) {
1984 load_flags |= (net::LOAD_DO_NOT_SEND_COOKIES |
1985 net::LOAD_DO_NOT_SEND_AUTH_DATA |
1986 net::LOAD_DO_NOT_SAVE_COOKIES);
1989 // Raw headers are sensitive, as they include Cookie/Set-Cookie, so only
1990 // allow requesting them if requester has ReadRawCookies permission.
1991 if ((load_flags & net::LOAD_REPORT_RAW_HEADERS)
1992 && !policy->CanReadRawCookies(child_id)) {
1993 VLOG(1) << "Denied unauthorized request for raw headers";
1994 load_flags &= ~net::LOAD_REPORT_RAW_HEADERS;
1997 // Add a flag to selectively bypass the data reduction proxy if the resource
1998 // type is not an image.
1999 if (request_data.resource_type != ResourceType::IMAGE)
2000 load_flags |= net::LOAD_BYPASS_DATA_REDUCTION_PROXY;
2002 return load_flags;
2005 } // namespace content