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 // This is the browser side of the resource dispatcher, it receives requests
6 // from the child process (i.e. [Renderer, Plugin, Worker]ProcessHost), and
7 // dispatches them to URLRequests. It then forwards the messages from the
8 // URLRequests back to the correct process for handling.
10 // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading
12 #ifndef CONTENT_BROWSER_LOADER_RESOURCE_DISPATCHER_HOST_IMPL_H_
13 #define CONTENT_BROWSER_LOADER_RESOURCE_DISPATCHER_HOST_IMPL_H_
20 #include "base/basictypes.h"
21 #include "base/gtest_prod_util.h"
22 #include "base/memory/linked_ptr.h"
23 #include "base/memory/scoped_ptr.h"
24 #include "base/observer_list.h"
25 #include "base/time/time.h"
26 #include "base/timer/timer.h"
27 #include "content/browser/download/download_resource_handler.h"
28 #include "content/browser/loader/global_routing_id.h"
29 #include "content/browser/loader/resource_loader.h"
30 #include "content/browser/loader/resource_loader_delegate.h"
31 #include "content/browser/loader/resource_scheduler.h"
32 #include "content/common/content_export.h"
33 #include "content/common/resource_request_body.h"
34 #include "content/public/browser/child_process_data.h"
35 #include "content/public/browser/download_item.h"
36 #include "content/public/browser/download_url_parameters.h"
37 #include "content/public/browser/global_request_id.h"
38 #include "content/public/browser/notification_types.h"
39 #include "content/public/browser/resource_dispatcher_host.h"
40 #include "content/public/common/resource_type.h"
41 #include "ipc/ipc_message.h"
42 #include "net/cookies/canonical_cookie.h"
43 #include "net/url_request/url_request.h"
45 class ResourceHandler
;
46 struct ResourceHostMsg_Request
;
49 class URLRequestJobFactory
;
53 class ShareableFileReference
;
57 class AppCacheService
;
58 class NavigationURLLoaderImplCore
;
59 class ResourceContext
;
60 class ResourceDispatcherHostDelegate
;
61 class ResourceMessageDelegate
;
62 class ResourceMessageFilter
;
63 class ResourceRequestInfoImpl
;
64 class SaveFileManager
;
65 class WebContentsImpl
;
66 struct CommonNavigationParams
;
67 struct DownloadSaveInfo
;
68 struct NavigationRequestInfo
;
71 class CONTENT_EXPORT ResourceDispatcherHostImpl
72 : public ResourceDispatcherHost
,
73 public ResourceLoaderDelegate
{
75 ResourceDispatcherHostImpl();
76 ~ResourceDispatcherHostImpl() override
;
78 // Returns the current ResourceDispatcherHostImpl. May return NULL if it
79 // hasn't been created yet.
80 static ResourceDispatcherHostImpl
* Get();
82 // ResourceDispatcherHost implementation:
83 void SetDelegate(ResourceDispatcherHostDelegate
* delegate
) override
;
84 void SetAllowCrossOriginAuthPrompt(bool value
) override
;
85 DownloadInterruptReason
BeginDownload(
86 scoped_ptr
<net::URLRequest
> request
,
87 const Referrer
& referrer
,
88 bool is_content_initiated
,
89 ResourceContext
* context
,
93 scoped_ptr
<DownloadSaveInfo
> save_info
,
95 const DownloadStartedCallback
& started_callback
) override
;
96 void ClearLoginDelegateForRequest(net::URLRequest
* request
) override
;
97 void BlockRequestsForRoute(int child_id
, int route_id
) override
;
98 void ResumeBlockedRequestsForRoute(int child_id
, int route_id
) override
;
100 // Puts the resource dispatcher host in an inactive state (unable to begin
101 // new requests). Cancels all pending requests.
104 // Notify the ResourceDispatcherHostImpl of a new resource context.
105 void AddResourceContext(ResourceContext
* context
);
107 // Notify the ResourceDispatcherHostImpl of a resource context destruction.
108 void RemoveResourceContext(ResourceContext
* context
);
110 // Resumes a request that deferred at response start.
111 void ResumeResponseDeferredAtStart(const GlobalRequestID
& id
);
113 // Force cancels any pending requests for the given |context|. This is
114 // necessary to ensure that before |context| goes away, all requests
116 void CancelRequestsForContext(ResourceContext
* context
);
118 // Returns true if the message was a resource message that was processed.
119 bool OnMessageReceived(const IPC::Message
& message
,
120 ResourceMessageFilter
* filter
);
122 // Initiates a save file from the browser process (as opposed to a resource
123 // request from the renderer or another child process).
124 void BeginSaveFile(const GURL
& url
,
125 const Referrer
& referrer
,
128 ResourceContext
* context
);
130 // Cancels the given request if it still exists.
131 void CancelRequest(int child_id
, int request_id
);
133 // Marks the request as "parked". This happens if a request is
134 // redirected cross-site and needs to be resumed by a new render view.
135 void MarkAsTransferredNavigation(const GlobalRequestID
& id
);
137 // Cancels a request previously marked as being transferred, for use when a
138 // navigation was cancelled.
139 void CancelTransferringNavigation(const GlobalRequestID
& id
);
141 // Resumes the request without transferring it to a new render view.
142 void ResumeDeferredNavigation(const GlobalRequestID
& id
);
144 // Returns the number of pending requests. This is designed for the unittests
145 int pending_requests() const {
146 return static_cast<int>(pending_loaders_
.size());
149 // Intended for unit-tests only. Overrides the outstanding requests bound.
150 void set_max_outstanding_requests_cost_per_process(int limit
) {
151 max_outstanding_requests_cost_per_process_
= limit
;
153 void set_max_num_in_flight_requests_per_process(int limit
) {
154 max_num_in_flight_requests_per_process_
= limit
;
156 void set_max_num_in_flight_requests(int limit
) {
157 max_num_in_flight_requests_
= limit
;
160 // The average private bytes increase of the browser for each new pending
161 // request. Experimentally obtained.
162 static const int kAvgBytesPerOutstandingRequest
= 4400;
164 SaveFileManager
* save_file_manager() const {
165 return save_file_manager_
.get();
168 // Called when a RenderViewHost is created.
169 void OnRenderViewHostCreated(int child_id
,
174 // Called when a RenderViewHost is deleted.
175 void OnRenderViewHostDeleted(int child_id
, int route_id
);
177 // Called when a RenderViewHost starts or stops loading.
178 void OnRenderViewHostSetIsLoading(int child_id
,
182 // Called when a RenderViewHost is hidden.
183 void OnRenderViewHostWasHidden(int child_id
, int route_id
);
185 // Called when a RenderViewHost is shown.
186 void OnRenderViewHostWasShown(int child_id
, int route_id
);
188 // Called when an AudioRenderHost starts or stops playing.
189 void OnAudioRenderHostStreamStateChanged(int child_id
,
193 // Force cancels any pending requests for the given process.
194 void CancelRequestsForProcess(int child_id
);
196 void OnUserGesture(WebContentsImpl
* contents
);
198 // Retrieves a net::URLRequest. Must be called from the IO thread.
199 net::URLRequest
* GetURLRequest(const GlobalRequestID
& request_id
);
201 void RemovePendingRequest(int child_id
, int request_id
);
203 // Cancels any blocked request for the specified route id.
204 void CancelBlockedRequestsForRoute(int child_id
, int route_id
);
206 // Maintains a collection of temp files created in support of
207 // the download_to_file capability. Used to grant access to the
208 // child process and to defer deletion of the file until it's
210 void RegisterDownloadedTempFile(
211 int child_id
, int request_id
,
212 const base::FilePath
& file_path
);
213 void UnregisterDownloadedTempFile(int child_id
, int request_id
);
215 // Needed for the sync IPC message dispatcher macros.
216 bool Send(IPC::Message
* message
);
218 // Indicates whether third-party sub-content can pop-up HTTP basic auth
220 bool allow_cross_origin_auth_prompt();
222 ResourceDispatcherHostDelegate
* delegate() {
226 // Must be called after the ResourceRequestInfo has been created
227 // and associated with the request.
228 // |id| should be |content::DownloadItem::kInvalidId| to request automatic
230 scoped_ptr
<ResourceHandler
> CreateResourceHandlerForDownload(
231 net::URLRequest
* request
,
232 bool is_content_initiated
,
235 scoped_ptr
<DownloadSaveInfo
> save_info
,
236 const DownloadUrlParameters::OnStartedCallback
& started_cb
);
238 // Must be called after the ResourceRequestInfo has been created
239 // and associated with the request. If |payload| is set to a non-empty value,
240 // the value will be sent to the old resource handler instead of canceling
241 // it, except on HTTP errors.
242 scoped_ptr
<ResourceHandler
> MaybeInterceptAsStream(
243 net::URLRequest
* request
,
244 ResourceResponse
* response
,
245 std::string
* payload
);
247 ResourceScheduler
* scheduler() { return scheduler_
.get(); }
249 // Called by a ResourceHandler when it's ready to start reading data and
250 // sending it to the renderer. Returns true if there are enough file
251 // descriptors available for the shared memory buffer. If false is returned,
252 // the request should cancel.
253 bool HasSufficientResourcesForRequest(net::URLRequest
* request
);
255 // Called by a ResourceHandler after it has finished its request and is done
256 // using its shared memory buffer. Frees up that file descriptor to be used
258 void FinishedWithResourcesForRequest(net::URLRequest
* request
);
260 // PlzNavigate: Begins a request for NavigationURLLoader. |loader| is the
261 // loader to attach to the leaf resource handler.
262 void BeginNavigationRequest(ResourceContext
* resource_context
,
263 int64 frame_tree_node_id
,
264 const CommonNavigationParams
& common_params
,
265 const NavigationRequestInfo
& info
,
266 scoped_refptr
<ResourceRequestBody
> request_body
,
267 NavigationURLLoaderImplCore
* loader
);
270 friend class ResourceDispatcherHostTest
;
272 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
273 TestBlockedRequestsProcessDies
);
274 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
275 CalculateApproximateMemoryCost
);
276 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
277 DetachableResourceTimesOut
);
278 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
279 TestProcessCancelDetachableTimesOut
);
283 struct OustandingRequestsStats
{
288 friend class ShutdownTask
;
289 friend class ResourceMessageDelegate
;
291 // ResourceLoaderDelegate implementation:
292 ResourceDispatcherHostLoginDelegate
* CreateLoginDelegate(
293 ResourceLoader
* loader
,
294 net::AuthChallengeInfo
* auth_info
) override
;
295 bool HandleExternalProtocol(ResourceLoader
* loader
, const GURL
& url
) override
;
296 void DidStartRequest(ResourceLoader
* loader
) override
;
297 void DidReceiveRedirect(ResourceLoader
* loader
, const GURL
& new_url
) override
;
298 void DidReceiveResponse(ResourceLoader
* loader
) override
;
299 void DidFinishLoading(ResourceLoader
* loader
) override
;
301 // An init helper that runs on the IO thread.
304 // A shutdown helper that runs on the IO thread.
307 // Helper function for regular and download requests.
308 void BeginRequestInternal(scoped_ptr
<net::URLRequest
> request
,
309 scoped_ptr
<ResourceHandler
> handler
);
311 void StartLoading(ResourceRequestInfoImpl
* info
,
312 const linked_ptr
<ResourceLoader
>& loader
);
314 // We keep track of how much memory each request needs and how many requests
315 // are issued by each renderer. These are known as OustandingRequestStats.
316 // Memory limits apply to all requests sent to us by the renderers. There is a
317 // limit for each renderer. File descriptor limits apply to requests that are
318 // receiving their body. These are known as in-flight requests. There is a
319 // global limit that applies for the browser process. Each render is allowed
320 // to use up to a fraction of that.
322 // Returns the OustandingRequestsStats for |info|'s renderer, or an empty
323 // struct if that renderer has no outstanding requests.
324 OustandingRequestsStats
GetOutstandingRequestsStats(
325 const ResourceRequestInfoImpl
& info
);
327 // Updates |outstanding_requests_stats_map_| with the specified |stats| for
328 // the renderer that made the request in |info|.
329 void UpdateOutstandingRequestsStats(const ResourceRequestInfoImpl
& info
,
330 const OustandingRequestsStats
& stats
);
332 // Called every time an outstanding request is created or deleted. |count|
333 // indicates whether the request is new or deleted. |count| must be 1 or -1.
334 OustandingRequestsStats
IncrementOutstandingRequestsMemory(
336 const ResourceRequestInfoImpl
& info
);
338 // Called when an in flight request allocates or releases a shared memory
339 // buffer. |count| indicates whether the request is issuing or finishing.
340 // |count| must be 1 or -1.
341 OustandingRequestsStats
IncrementOutstandingRequestsCount(
343 ResourceRequestInfoImpl
* info
);
345 // Estimate how much heap space |request| will consume to run.
346 static int CalculateApproximateMemoryCost(net::URLRequest
* request
);
348 // Force cancels any pending requests for the given route id. This method
349 // acts like CancelRequestsForProcess when route_id is -1.
350 void CancelRequestsForRoute(int child_id
, int route_id
);
352 // The list of all requests that we have pending. This list is not really
353 // optimized, and assumes that we have relatively few requests pending at once
354 // since some operations require brute-force searching of the list.
356 // It may be enhanced in the future to provide some kind of prioritization
357 // mechanism. We should also consider a hashtable or binary tree if it turns
358 // out we have a lot of things here.
359 typedef std::map
<GlobalRequestID
, linked_ptr
<ResourceLoader
> > LoaderMap
;
361 // Deletes the pending request identified by the iterator passed in.
362 // This function will invalidate the iterator passed in. Callers should
363 // not rely on this iterator being valid on return.
364 void RemovePendingLoader(const LoaderMap::iterator
& iter
);
366 // Checks all pending requests and updates the load states and upload
367 // progress if necessary.
368 void UpdateLoadStates();
370 // Resumes or cancels (if |cancel_requests| is true) any blocked requests.
371 void ProcessBlockedRequestsForRoute(int child_id
,
373 bool cancel_requests
);
375 void OnRequestResource(int routing_id
,
377 const ResourceHostMsg_Request
& request_data
);
378 void OnSyncLoad(int request_id
,
379 const ResourceHostMsg_Request
& request_data
,
380 IPC::Message
* sync_result
);
382 // Update the ResourceRequestInfo and internal maps when a request is
383 // transferred from one process to another.
384 void UpdateRequestForTransfer(int child_id
,
387 const ResourceHostMsg_Request
& request_data
,
388 const linked_ptr
<ResourceLoader
>& loader
);
390 void BeginRequest(int request_id
,
391 const ResourceHostMsg_Request
& request_data
,
392 IPC::Message
* sync_result
, // only valid for sync
393 int route_id
); // only valid for async
395 // Creates a ResourceHandler to be used by BeginRequest() for normal resource
397 scoped_ptr
<ResourceHandler
> CreateResourceHandler(
398 net::URLRequest
* request
,
399 const ResourceHostMsg_Request
& request_data
,
400 IPC::Message
* sync_result
,
404 ResourceContext
* resource_context
);
406 // Wraps |handler| in the standard resource handlers for normal resource
407 // loading and navigation requests. This adds BufferedResourceHandler and
408 // ResourceThrottles.
409 scoped_ptr
<ResourceHandler
> AddStandardHandlers(
410 net::URLRequest
* request
,
411 ResourceType resource_type
,
412 ResourceContext
* resource_context
,
413 AppCacheService
* appcache_service
,
416 scoped_ptr
<ResourceHandler
> handler
);
418 void OnDataDownloadedACK(int request_id
);
419 void OnUploadProgressACK(int request_id
);
420 void OnCancelRequest(int request_id
);
421 void OnReleaseDownloadedFile(int request_id
);
423 // Creates ResourceRequestInfoImpl for a download or page save.
424 // |download| should be true if the request is a file download.
425 ResourceRequestInfoImpl
* CreateRequestInfo(
429 ResourceContext
* context
);
431 // Relationship of resource being authenticated with the top level page.
432 enum HttpAuthRelationType
{
433 HTTP_AUTH_RELATION_TOP
, // Top-level page itself
434 HTTP_AUTH_RELATION_SAME_DOMAIN
, // Sub-content from same domain
435 HTTP_AUTH_RELATION_BLOCKED_CROSS
, // Blocked Sub-content from cross domain
436 HTTP_AUTH_RELATION_ALLOWED_CROSS
, // Allowed Sub-content per command line
437 HTTP_AUTH_RELATION_LAST
440 HttpAuthRelationType
HttpAuthRelationTypeOf(const GURL
& request_url
,
441 const GURL
& first_party
);
443 // Returns whether the URLRequest identified by |transferred_request_id| is
444 // currently in the process of being transferred to a different renderer.
445 // This happens if a request is redirected cross-site and needs to be resumed
446 // by a new render view.
447 bool IsTransferredNavigation(
448 const GlobalRequestID
& transferred_request_id
) const;
450 ResourceLoader
* GetLoader(const GlobalRequestID
& id
) const;
451 ResourceLoader
* GetLoader(int child_id
, int request_id
) const;
453 // Registers |delegate| to receive resource IPC messages targeted to the
455 void RegisterResourceMessageDelegate(const GlobalRequestID
& id
,
456 ResourceMessageDelegate
* delegate
);
457 void UnregisterResourceMessageDelegate(const GlobalRequestID
& id
,
458 ResourceMessageDelegate
* delegate
);
460 int BuildLoadFlagsForRequest(const ResourceHostMsg_Request
& request_data
,
464 LoaderMap pending_loaders_
;
466 // Collection of temp files downloaded for child processes via
467 // the download_to_file mechanism. We avoid deleting them until
468 // the client no longer needs them.
469 typedef std::map
<int, scoped_refptr
<storage::ShareableFileReference
> >
470 DeletableFilesMap
; // key is request id
471 typedef std::map
<int, DeletableFilesMap
>
472 RegisteredTempFiles
; // key is child process id
473 RegisteredTempFiles registered_temp_files_
;
475 // A timer that periodically calls UpdateLoadStates while pending_requests_
477 scoped_ptr
<base::RepeatingTimer
<ResourceDispatcherHostImpl
> >
478 update_load_states_timer_
;
480 // We own the save file manager.
481 scoped_refptr
<SaveFileManager
> save_file_manager_
;
483 // Request ID for browser initiated requests. request_ids generated by
484 // child processes are counted up from 0, while browser created requests
485 // start at -2 and go down from there. (We need to start at -2 because -1 is
486 // used as a special value all over the resource_dispatcher_host for
487 // uninitialized variables.) This way, we no longer have the unlikely (but
488 // observed in the real world!) event where we have two requests with the same
492 // True if the resource dispatcher host has been shut down.
495 typedef std::vector
<linked_ptr
<ResourceLoader
> > BlockedLoadersList
;
496 typedef std::map
<GlobalRoutingID
, BlockedLoadersList
*> BlockedLoadersMap
;
497 BlockedLoadersMap blocked_loaders_map_
;
499 // Maps the child_ids to the approximate number of bytes
500 // being used to service its resource requests. No entry implies 0 cost.
501 typedef std::map
<int, OustandingRequestsStats
> OutstandingRequestsStatsMap
;
502 OutstandingRequestsStatsMap outstanding_requests_stats_map_
;
504 // |num_in_flight_requests_| is the total number of requests currently issued
505 // summed across all renderers.
506 int num_in_flight_requests_
;
508 // |max_num_in_flight_requests_| is the upper bound on how many requests
509 // can be in flight at once. It's based on the maximum number of file
510 // descriptors open per process. We need a global limit for the browser
512 int max_num_in_flight_requests_
;
514 // |max_num_in_flight_requests_| is the upper bound on how many requests
515 // can be issued at once. It's based on the maximum number of file
516 // descriptors open per process. We need a per-renderer limit so that no
517 // single renderer can hog the browser's limit.
518 int max_num_in_flight_requests_per_process_
;
520 // |max_outstanding_requests_cost_per_process_| is the upper bound on how
521 // many outstanding requests can be issued per child process host.
522 // The constraint is expressed in terms of bytes (where the cost of
523 // individual requests is given by CalculateApproximateMemoryCost).
524 // The total number of outstanding requests is roughly:
525 // (max_outstanding_requests_cost_per_process_ /
526 // kAvgBytesPerOutstandingRequest)
527 int max_outstanding_requests_cost_per_process_
;
529 // Time of the last user gesture. Stored so that we can add a load
530 // flag to requests occurring soon after a gesture to indicate they
531 // may be because of explicit user action.
532 base::TimeTicks last_user_gesture_time_
;
534 // Used during IPC message dispatching so that the handlers can get a pointer
535 // to the source of the message.
536 ResourceMessageFilter
* filter_
;
538 ResourceDispatcherHostDelegate
* delegate_
;
540 bool allow_cross_origin_auth_prompt_
;
542 // http://crbug.com/90971 - Assists in tracking down use-after-frees on
544 std::set
<const ResourceContext
*> active_resource_contexts_
;
546 typedef std::map
<GlobalRequestID
,
547 ObserverList
<ResourceMessageDelegate
>*> DelegateMap
;
548 DelegateMap delegate_map_
;
550 scoped_ptr
<ResourceScheduler
> scheduler_
;
552 DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHostImpl
);
555 } // namespace content
557 #endif // CONTENT_BROWSER_LOADER_RESOURCE_DISPATCHER_HOST_IMPL_H_