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 #ifndef CHROME_BROWSER_EXTENSIONS_API_WEB_REQUEST_WEB_REQUEST_API_H_
6 #define CHROME_BROWSER_EXTENSIONS_API_WEB_REQUEST_WEB_REQUEST_API_H_
15 #include "base/memory/singleton.h"
16 #include "base/time.h"
17 #include "chrome/browser/extensions/api/declarative_webrequest/request_stages.h"
18 #include "chrome/browser/extensions/api/web_request/web_request_api_helpers.h"
19 #include "chrome/browser/extensions/extension_function.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/common/extensions/url_pattern_set.h"
22 #include "ipc/ipc_message.h"
23 #include "net/base/completion_callback.h"
24 #include "net/base/network_delegate.h"
25 #include "net/http/http_request_headers.h"
26 #include "webkit/glue/resource_type.h"
28 class ExtensionInfoMap
;
29 class ExtensionWebRequestTimeTracker
;
33 class DictionaryValue
;
39 class RenderProcessHost
;
42 namespace extensions
{
43 class WebRequestRulesRegistry
;
47 class AuthCredentials
;
48 class AuthChallengeInfo
;
49 class HttpRequestHeaders
;
50 class HttpResponseHeaders
;
54 // This class observes network events and routes them to the appropriate
55 // extensions listening to those events. All methods must be called on the IO
56 // thread unless otherwise specified.
57 class ExtensionWebRequestEventRouter
{
59 struct BlockedRequest
;
63 kOnBeforeRequest
= 1 << 0,
64 kOnBeforeSendHeaders
= 1 << 1,
65 kOnSendHeaders
= 1 << 2,
66 kOnHeadersReceived
= 1 << 3,
67 kOnBeforeRedirect
= 1 << 4,
68 kOnAuthRequired
= 1 << 5,
69 kOnResponseStarted
= 1 << 6,
70 kOnErrorOccurred
= 1 << 7,
71 kOnCompleted
= 1 << 8,
74 // Internal representation of the webRequest.RequestFilter type, used to
75 // filter what network events an extension cares about.
76 struct RequestFilter
{
78 std::vector
<ResourceType::Type
> types
;
85 // Returns false if there was an error initializing. If it is a user error,
86 // an error message is provided, otherwise the error is internal (and
88 bool InitFromValue(const base::DictionaryValue
& value
, std::string
* error
);
91 // Internal representation of the extraInfoSpec parameter on webRequest
92 // events, used to specify extra information to be included with network
94 struct ExtraInfoSpec
{
96 REQUEST_HEADERS
= 1<<0,
97 RESPONSE_HEADERS
= 1<<1,
99 ASYNC_BLOCKING
= 1<<3,
102 static bool InitFromValue(const base::ListValue
& value
,
103 int* extra_info_spec
);
106 // Contains an extension's response to a blocking event.
107 struct EventResponse
{
108 // ID of the extension that sent this response.
109 std::string extension_id
;
111 // The time that the extension was installed. Used for deciding order of
112 // precedence in case multiple extensions respond with conflicting
114 base::Time extension_install_time
;
116 // Response values. These are mutually exclusive.
119 scoped_ptr
<net::HttpRequestHeaders
> request_headers
;
120 scoped_ptr
<extension_web_request_api_helpers::ResponseHeaders
>
123 scoped_ptr
<net::AuthCredentials
> auth_credentials
;
125 EventResponse(const std::string
& extension_id
,
126 const base::Time
& extension_install_time
);
129 DISALLOW_COPY_AND_ASSIGN(EventResponse
);
132 static ExtensionWebRequestEventRouter
* GetInstance();
134 void RegisterRulesRegistry(
135 scoped_refptr
<extensions::WebRequestRulesRegistry
> rules_registry
);
137 // Dispatches the OnBeforeRequest event to any extensions whose filters match
138 // the given request. Returns net::ERR_IO_PENDING if an extension is
139 // intercepting the request, OK otherwise.
140 int OnBeforeRequest(void* profile
,
141 ExtensionInfoMap
* extension_info_map
,
142 net::URLRequest
* request
,
143 const net::CompletionCallback
& callback
,
146 // Dispatches the onBeforeSendHeaders event. This is fired for HTTP(s)
147 // requests only, and allows modification of the outgoing request headers.
148 // Returns net::ERR_IO_PENDING if an extension is intercepting the request, OK
150 int OnBeforeSendHeaders(void* profile
,
151 ExtensionInfoMap
* extension_info_map
,
152 net::URLRequest
* request
,
153 const net::CompletionCallback
& callback
,
154 net::HttpRequestHeaders
* headers
);
156 // Dispatches the onSendHeaders event. This is fired for HTTP(s) requests
158 void OnSendHeaders(void* profile
,
159 ExtensionInfoMap
* extension_info_map
,
160 net::URLRequest
* request
,
161 const net::HttpRequestHeaders
& headers
);
163 // Dispatches the onHeadersReceived event. This is fired for HTTP(s)
164 // requests only, and allows modification of incoming response headers.
165 // Returns net::ERR_IO_PENDING if an extension is intercepting the request,
166 // OK otherwise. |original_response_headers| is reference counted. |callback|
167 // and |override_response_headers| are owned by a URLRequestJob. They are
168 // guaranteed to be valid until |callback| is called or OnURLRequestDestroyed
169 // is called (whatever comes first).
170 // Do not modify |original_response_headers| directly but write new ones
171 // into |override_response_headers|.
172 int OnHeadersReceived(
174 ExtensionInfoMap
* extension_info_map
,
175 net::URLRequest
* request
,
176 const net::CompletionCallback
& callback
,
177 net::HttpResponseHeaders
* original_response_headers
,
178 scoped_refptr
<net::HttpResponseHeaders
>* override_response_headers
);
180 // Dispatches the OnAuthRequired event to any extensions whose filters match
181 // the given request. If the listener is not registered as "blocking", then
182 // AUTH_REQUIRED_RESPONSE_OK is returned. Otherwise,
183 // AUTH_REQUIRED_RESPONSE_IO_PENDING is returned and |callback| will be
185 net::NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
187 ExtensionInfoMap
* extension_info_map
,
188 net::URLRequest
* request
,
189 const net::AuthChallengeInfo
& auth_info
,
190 const net::NetworkDelegate::AuthCallback
& callback
,
191 net::AuthCredentials
* credentials
);
193 // Dispatches the onBeforeRedirect event. This is fired for HTTP(s) requests
195 void OnBeforeRedirect(void* profile
,
196 ExtensionInfoMap
* extension_info_map
,
197 net::URLRequest
* request
,
198 const GURL
& new_location
);
200 // Dispatches the onResponseStarted event indicating that the first bytes of
201 // the response have arrived.
202 void OnResponseStarted(void* profile
,
203 ExtensionInfoMap
* extension_info_map
,
204 net::URLRequest
* request
);
206 // Dispatches the onComplete event.
207 void OnCompleted(void* profile
,
208 ExtensionInfoMap
* extension_info_map
,
209 net::URLRequest
* request
);
211 // Dispatches an onErrorOccurred event.
212 void OnErrorOccurred(void* profile
,
213 ExtensionInfoMap
* extension_info_map
,
214 net::URLRequest
* request
,
217 // Notifications when objects are going away.
218 void OnURLRequestDestroyed(void* profile
, net::URLRequest
* request
);
220 // Called when an event listener handles a blocking event and responds.
223 const std::string
& extension_id
,
224 const std::string
& event_name
,
225 const std::string
& sub_event_name
,
227 EventResponse
* response
);
229 // Adds a listener to the given event. |event_name| specifies the event being
230 // listened to. |sub_event_name| is an internal event uniquely generated in
231 // the extension process to correspond to the given filter and
233 void AddEventListener(
235 const std::string
& extension_id
,
236 const std::string
& extension_name
,
237 const std::string
& event_name
,
238 const std::string
& sub_event_name
,
239 const RequestFilter
& filter
,
241 base::WeakPtr
<IPC::Message::Sender
> ipc_sender
);
243 // Removes the listener for the given sub-event.
244 void RemoveEventListener(
246 const std::string
& extension_id
,
247 const std::string
& sub_event_name
);
249 // Called when an incognito profile is created or destroyed.
250 void OnOTRProfileCreated(void* original_profile
,
252 void OnOTRProfileDestroyed(void* original_profile
,
255 // Registers a |callback| that is executed when the next page load happens.
256 // The callback is then deleted.
257 void AddCallbackForPageLoad(const base::Closure
& callback
);
260 friend struct DefaultSingletonTraits
<ExtensionWebRequestEventRouter
>;
261 struct EventListener
;
262 typedef std::map
<std::string
, std::set
<EventListener
> > ListenerMapForProfile
;
263 typedef std::map
<void*, ListenerMapForProfile
> ListenerMap
;
264 typedef std::map
<uint64
, BlockedRequest
> BlockedRequestMap
;
265 // Map of request_id -> bit vector of EventTypes already signaled
266 typedef std::map
<uint64
, int> SignaledRequestMap
;
267 typedef std::map
<void*, void*> CrossProfileMap
;
268 typedef std::list
<base::Closure
> CallbacksForPageLoad
;
270 ExtensionWebRequestEventRouter();
271 ~ExtensionWebRequestEventRouter();
273 // Ensures that future callbacks for |request| are ignored so that it can be
275 void ClearPendingCallbacks(net::URLRequest
* request
);
279 net::URLRequest
* request
,
280 const std::vector
<const EventListener
*>& listeners
,
281 const base::ListValue
& args
);
283 // Returns a list of event listeners that care about the given event, based
284 // on their filter parameters. |extra_info_spec| will contain the combined
285 // set of extra_info_spec flags that every matching listener asked for.
286 std::vector
<const EventListener
*> GetMatchingListeners(
288 ExtensionInfoMap
* extension_info_map
,
289 const std::string
& event_name
,
290 net::URLRequest
* request
,
291 int* extra_info_spec
);
293 // Helper for the above functions. This is called twice: once for the profile
294 // of the event, the next time for the "cross" profile (i.e. the incognito
295 // profile if the event is originally for the normal profile, or vice versa).
296 void GetMatchingListenersImpl(
298 ExtensionInfoMap
* extension_info_map
,
299 bool crosses_incognito
,
300 const std::string
& event_name
,
304 ResourceType::Type resource_type
,
305 bool is_request_from_extension
,
306 int* extra_info_spec
,
307 std::vector
<const ExtensionWebRequestEventRouter::EventListener
*>*
310 // Decrements the count of event handlers blocking the given request. When the
311 // count reaches 0, we stop blocking the request and proceed it using the
312 // method requested by the extension with the highest precedence. Precedence
313 // is decided by extension install time. If |response| is non-NULL, this
314 // method assumes ownership.
315 void DecrementBlockCount(
317 const std::string
& extension_id
,
318 const std::string
& event_name
,
320 EventResponse
* response
);
322 // Processes the generated deltas from blocked_requests_ on the specified
323 // request. If |call_back| is true, the callback registered in
324 // |blocked_requests_| is called.
325 // The function returns the error code for the network request. This is
326 // mostly relevant in case the caller passes |call_callback| = false
327 // and wants to return the correct network error code himself.
328 int ExecuteDeltas(void* profile
, uint64 request_id
, bool call_callback
);
330 // Evaluates the rules of the declarative webrequest API and stores
331 // modifications to the request that result from WebRequestActions as
332 // deltas in |blocked_requests_|. Returns whether any deltas were
334 bool ProcessDeclarativeRules(net::URLRequest
* request
,
335 extensions::RequestStages request_stage
);
337 // Sets the flag that |event_type| has been signaled for |request_id|.
338 // Returns the value of the flag before setting it.
339 bool GetAndSetSignaled(uint64 request_id
, EventTypes event_type
);
341 // Clears the flag that |event_type| has been signaled for |request_id|.
342 void ClearSignaled(uint64 request_id
, EventTypes event_type
);
344 // Returns whether |request| represents a top level window navigation.
345 bool IsPageLoad(net::URLRequest
* request
) const;
347 // Called on a page load to process all registered callbacks.
348 void NotifyPageLoad();
350 // A map for each profile that maps an event name to a set of extensions that
351 // are listening to that event.
352 ListenerMap listeners_
;
354 // A map of network requests that are waiting for at least one event handler
356 BlockedRequestMap blocked_requests_
;
358 // A map of request ids to a bitvector indicating which events have been
359 // signaled and should not be sent again.
360 SignaledRequestMap signaled_requests_
;
362 // A map of original profile -> corresponding incognito profile (and vice
364 CrossProfileMap cross_profile_map_
;
366 // Keeps track of time spent waiting on extensions using the blocking
368 scoped_ptr
<ExtensionWebRequestTimeTracker
> request_time_tracker_
;
370 CallbacksForPageLoad callbacks_for_page_load_
;
372 scoped_refptr
<extensions::WebRequestRulesRegistry
> rules_registry_
;
374 DISALLOW_COPY_AND_ASSIGN(ExtensionWebRequestEventRouter
);
377 class WebRequestAddEventListener
: public SyncIOThreadExtensionFunction
{
379 virtual bool RunImpl() OVERRIDE
;
380 DECLARE_EXTENSION_FUNCTION_NAME("webRequest.addEventListener");
383 class WebRequestEventHandled
: public SyncIOThreadExtensionFunction
{
385 virtual bool RunImpl() OVERRIDE
;
386 DECLARE_EXTENSION_FUNCTION_NAME("webRequest.eventHandled");
389 class WebRequestHandlerBehaviorChanged
: public SyncIOThreadExtensionFunction
{
391 virtual bool RunImpl() OVERRIDE
;
392 DECLARE_EXTENSION_FUNCTION_NAME(
393 "webRequest.handlerBehaviorChanged");
396 virtual void GetQuotaLimitHeuristics(
397 QuotaLimitHeuristics
* heuristics
) const OVERRIDE
;
398 // Handle quota exceeded gracefully: Only warn the user but still execute the
400 virtual void OnQuotaExceeded() OVERRIDE
;
403 // Send updates to |host| with information about what webRequest-related
404 // extensions are installed.
405 // TODO(mpcomplete): remove. http://crbug.com/100411
406 void SendExtensionWebRequestStatusToHost(content::RenderProcessHost
* host
);
408 #endif // CHROME_BROWSER_EXTENSIONS_API_WEB_REQUEST_WEB_REQUEST_API_H_