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
229 // assignment. This is marked virtual so it can be overriden in testing.
230 virtual 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. This is marked virtual so it can be overriden in
243 virtual scoped_ptr
<ResourceHandler
> MaybeInterceptAsStream(
244 net::URLRequest
* request
,
245 ResourceResponse
* response
,
246 std::string
* payload
);
248 ResourceScheduler
* scheduler() { return scheduler_
.get(); }
250 // Called by a ResourceHandler when it's ready to start reading data and
251 // sending it to the renderer. Returns true if there are enough file
252 // descriptors available for the shared memory buffer. If false is returned,
253 // the request should cancel.
254 bool HasSufficientResourcesForRequest(net::URLRequest
* request
);
256 // Called by a ResourceHandler after it has finished its request and is done
257 // using its shared memory buffer. Frees up that file descriptor to be used
259 void FinishedWithResourcesForRequest(net::URLRequest
* request
);
261 // PlzNavigate: Begins a request for NavigationURLLoader. |loader| is the
262 // loader to attach to the leaf resource handler.
263 void BeginNavigationRequest(ResourceContext
* resource_context
,
264 int64 frame_tree_node_id
,
265 const CommonNavigationParams
& common_params
,
266 const NavigationRequestInfo
& info
,
267 scoped_refptr
<ResourceRequestBody
> request_body
,
268 NavigationURLLoaderImplCore
* loader
);
271 friend class ResourceDispatcherHostTest
;
273 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
274 TestBlockedRequestsProcessDies
);
275 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
276 CalculateApproximateMemoryCost
);
277 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
278 DetachableResourceTimesOut
);
279 FRIEND_TEST_ALL_PREFIXES(ResourceDispatcherHostTest
,
280 TestProcessCancelDetachableTimesOut
);
284 struct OustandingRequestsStats
{
289 friend class ShutdownTask
;
290 friend class ResourceMessageDelegate
;
292 // ResourceLoaderDelegate implementation:
293 ResourceDispatcherHostLoginDelegate
* CreateLoginDelegate(
294 ResourceLoader
* loader
,
295 net::AuthChallengeInfo
* auth_info
) override
;
296 bool HandleExternalProtocol(ResourceLoader
* loader
, const GURL
& url
) override
;
297 void DidStartRequest(ResourceLoader
* loader
) override
;
298 void DidReceiveRedirect(ResourceLoader
* loader
, const GURL
& new_url
) override
;
299 void DidReceiveResponse(ResourceLoader
* loader
) override
;
300 void DidFinishLoading(ResourceLoader
* loader
) override
;
302 // An init helper that runs on the IO thread.
305 // A shutdown helper that runs on the IO thread.
308 // Helper function for regular and download requests.
309 void BeginRequestInternal(scoped_ptr
<net::URLRequest
> request
,
310 scoped_ptr
<ResourceHandler
> handler
);
312 void StartLoading(ResourceRequestInfoImpl
* info
,
313 const linked_ptr
<ResourceLoader
>& loader
);
315 // We keep track of how much memory each request needs and how many requests
316 // are issued by each renderer. These are known as OustandingRequestStats.
317 // Memory limits apply to all requests sent to us by the renderers. There is a
318 // limit for each renderer. File descriptor limits apply to requests that are
319 // receiving their body. These are known as in-flight requests. There is a
320 // global limit that applies for the browser process. Each render is allowed
321 // to use up to a fraction of that.
323 // Returns the OustandingRequestsStats for |info|'s renderer, or an empty
324 // struct if that renderer has no outstanding requests.
325 OustandingRequestsStats
GetOutstandingRequestsStats(
326 const ResourceRequestInfoImpl
& info
);
328 // Updates |outstanding_requests_stats_map_| with the specified |stats| for
329 // the renderer that made the request in |info|.
330 void UpdateOutstandingRequestsStats(const ResourceRequestInfoImpl
& info
,
331 const OustandingRequestsStats
& stats
);
333 // Called every time an outstanding request is created or deleted. |count|
334 // indicates whether the request is new or deleted. |count| must be 1 or -1.
335 OustandingRequestsStats
IncrementOutstandingRequestsMemory(
337 const ResourceRequestInfoImpl
& info
);
339 // Called when an in flight request allocates or releases a shared memory
340 // buffer. |count| indicates whether the request is issuing or finishing.
341 // |count| must be 1 or -1.
342 OustandingRequestsStats
IncrementOutstandingRequestsCount(
344 ResourceRequestInfoImpl
* info
);
346 // Estimate how much heap space |request| will consume to run.
347 static int CalculateApproximateMemoryCost(net::URLRequest
* request
);
349 // Force cancels any pending requests for the given route id. This method
350 // acts like CancelRequestsForProcess when route_id is -1.
351 void CancelRequestsForRoute(int child_id
, int route_id
);
353 // The list of all requests that we have pending. This list is not really
354 // optimized, and assumes that we have relatively few requests pending at once
355 // since some operations require brute-force searching of the list.
357 // It may be enhanced in the future to provide some kind of prioritization
358 // mechanism. We should also consider a hashtable or binary tree if it turns
359 // out we have a lot of things here.
360 typedef std::map
<GlobalRequestID
, linked_ptr
<ResourceLoader
> > LoaderMap
;
362 // Deletes the pending request identified by the iterator passed in.
363 // This function will invalidate the iterator passed in. Callers should
364 // not rely on this iterator being valid on return.
365 void RemovePendingLoader(const LoaderMap::iterator
& iter
);
367 // Checks all pending requests and updates the load states and upload
368 // progress if necessary.
369 void UpdateLoadStates();
371 // Resumes or cancels (if |cancel_requests| is true) any blocked requests.
372 void ProcessBlockedRequestsForRoute(int child_id
,
374 bool cancel_requests
);
376 void OnRequestResource(int routing_id
,
378 const ResourceHostMsg_Request
& request_data
);
379 void OnSyncLoad(int request_id
,
380 const ResourceHostMsg_Request
& request_data
,
381 IPC::Message
* sync_result
);
383 // Update the ResourceRequestInfo and internal maps when a request is
384 // transferred from one process to another.
385 void UpdateRequestForTransfer(int child_id
,
388 const ResourceHostMsg_Request
& request_data
,
389 const linked_ptr
<ResourceLoader
>& loader
);
391 void BeginRequest(int request_id
,
392 const ResourceHostMsg_Request
& request_data
,
393 IPC::Message
* sync_result
, // only valid for sync
394 int route_id
); // only valid for async
396 // Creates a ResourceHandler to be used by BeginRequest() for normal resource
398 scoped_ptr
<ResourceHandler
> CreateResourceHandler(
399 net::URLRequest
* request
,
400 const ResourceHostMsg_Request
& request_data
,
401 IPC::Message
* sync_result
,
405 ResourceContext
* resource_context
);
407 // Wraps |handler| in the standard resource handlers for normal resource
408 // loading and navigation requests. This adds BufferedResourceHandler and
409 // ResourceThrottles.
410 scoped_ptr
<ResourceHandler
> AddStandardHandlers(
411 net::URLRequest
* request
,
412 ResourceType resource_type
,
413 ResourceContext
* resource_context
,
414 AppCacheService
* appcache_service
,
417 scoped_ptr
<ResourceHandler
> handler
);
419 void OnDataDownloadedACK(int request_id
);
420 void OnUploadProgressACK(int request_id
);
421 void OnCancelRequest(int request_id
);
422 void OnReleaseDownloadedFile(int request_id
);
424 // Creates ResourceRequestInfoImpl for a download or page save.
425 // |download| should be true if the request is a file download.
426 ResourceRequestInfoImpl
* CreateRequestInfo(
430 ResourceContext
* context
);
432 // Relationship of resource being authenticated with the top level page.
433 enum HttpAuthRelationType
{
434 HTTP_AUTH_RELATION_TOP
, // Top-level page itself
435 HTTP_AUTH_RELATION_SAME_DOMAIN
, // Sub-content from same domain
436 HTTP_AUTH_RELATION_BLOCKED_CROSS
, // Blocked Sub-content from cross domain
437 HTTP_AUTH_RELATION_ALLOWED_CROSS
, // Allowed Sub-content per command line
438 HTTP_AUTH_RELATION_LAST
441 HttpAuthRelationType
HttpAuthRelationTypeOf(const GURL
& request_url
,
442 const GURL
& first_party
);
444 // Returns whether the URLRequest identified by |transferred_request_id| is
445 // currently in the process of being transferred to a different renderer.
446 // This happens if a request is redirected cross-site and needs to be resumed
447 // by a new render view.
448 bool IsTransferredNavigation(
449 const GlobalRequestID
& transferred_request_id
) const;
451 ResourceLoader
* GetLoader(const GlobalRequestID
& id
) const;
452 ResourceLoader
* GetLoader(int child_id
, int request_id
) const;
454 // Registers |delegate| to receive resource IPC messages targeted to the
456 void RegisterResourceMessageDelegate(const GlobalRequestID
& id
,
457 ResourceMessageDelegate
* delegate
);
458 void UnregisterResourceMessageDelegate(const GlobalRequestID
& id
,
459 ResourceMessageDelegate
* delegate
);
461 int BuildLoadFlagsForRequest(const ResourceHostMsg_Request
& request_data
,
465 LoaderMap pending_loaders_
;
467 // Collection of temp files downloaded for child processes via
468 // the download_to_file mechanism. We avoid deleting them until
469 // the client no longer needs them.
470 typedef std::map
<int, scoped_refptr
<storage::ShareableFileReference
> >
471 DeletableFilesMap
; // key is request id
472 typedef std::map
<int, DeletableFilesMap
>
473 RegisteredTempFiles
; // key is child process id
474 RegisteredTempFiles registered_temp_files_
;
476 // A timer that periodically calls UpdateLoadStates while pending_requests_
478 scoped_ptr
<base::RepeatingTimer
<ResourceDispatcherHostImpl
> >
479 update_load_states_timer_
;
481 // We own the save file manager.
482 scoped_refptr
<SaveFileManager
> save_file_manager_
;
484 // Request ID for browser initiated requests. request_ids generated by
485 // child processes are counted up from 0, while browser created requests
486 // start at -2 and go down from there. (We need to start at -2 because -1 is
487 // used as a special value all over the resource_dispatcher_host for
488 // uninitialized variables.) This way, we no longer have the unlikely (but
489 // observed in the real world!) event where we have two requests with the same
493 // True if the resource dispatcher host has been shut down.
496 typedef std::vector
<linked_ptr
<ResourceLoader
> > BlockedLoadersList
;
497 typedef std::map
<GlobalRoutingID
, BlockedLoadersList
*> BlockedLoadersMap
;
498 BlockedLoadersMap blocked_loaders_map_
;
500 // Maps the child_ids to the approximate number of bytes
501 // being used to service its resource requests. No entry implies 0 cost.
502 typedef std::map
<int, OustandingRequestsStats
> OutstandingRequestsStatsMap
;
503 OutstandingRequestsStatsMap outstanding_requests_stats_map_
;
505 // |num_in_flight_requests_| is the total number of requests currently issued
506 // summed across all renderers.
507 int num_in_flight_requests_
;
509 // |max_num_in_flight_requests_| is the upper bound on how many requests
510 // can be in flight at once. It's based on the maximum number of file
511 // descriptors open per process. We need a global limit for the browser
513 int max_num_in_flight_requests_
;
515 // |max_num_in_flight_requests_| is the upper bound on how many requests
516 // can be issued at once. It's based on the maximum number of file
517 // descriptors open per process. We need a per-renderer limit so that no
518 // single renderer can hog the browser's limit.
519 int max_num_in_flight_requests_per_process_
;
521 // |max_outstanding_requests_cost_per_process_| is the upper bound on how
522 // many outstanding requests can be issued per child process host.
523 // The constraint is expressed in terms of bytes (where the cost of
524 // individual requests is given by CalculateApproximateMemoryCost).
525 // The total number of outstanding requests is roughly:
526 // (max_outstanding_requests_cost_per_process_ /
527 // kAvgBytesPerOutstandingRequest)
528 int max_outstanding_requests_cost_per_process_
;
530 // Time of the last user gesture. Stored so that we can add a load
531 // flag to requests occurring soon after a gesture to indicate they
532 // may be because of explicit user action.
533 base::TimeTicks last_user_gesture_time_
;
535 // Used during IPC message dispatching so that the handlers can get a pointer
536 // to the source of the message.
537 ResourceMessageFilter
* filter_
;
539 ResourceDispatcherHostDelegate
* delegate_
;
541 bool allow_cross_origin_auth_prompt_
;
543 // http://crbug.com/90971 - Assists in tracking down use-after-frees on
545 std::set
<const ResourceContext
*> active_resource_contexts_
;
547 typedef std::map
<GlobalRequestID
,
548 ObserverList
<ResourceMessageDelegate
>*> DelegateMap
;
549 DelegateMap delegate_map_
;
551 scoped_ptr
<ResourceScheduler
> scheduler_
;
553 DISALLOW_COPY_AND_ASSIGN(ResourceDispatcherHostImpl
);
556 } // namespace content
558 #endif // CONTENT_BROWSER_LOADER_RESOURCE_DISPATCHER_HOST_IMPL_H_