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 EXTENSIONS_BROWSER_API_WEB_REQUEST_WEB_REQUEST_API_H_
6 #define EXTENSIONS_BROWSER_API_WEB_REQUEST_WEB_REQUEST_API_H_
14 #include "base/memory/singleton.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/strings/string_util.h"
17 #include "base/time/time.h"
18 #include "content/public/common/resource_type.h"
19 #include "extensions/browser/api/declarative/rules_registry.h"
20 #include "extensions/browser/api/declarative_webrequest/request_stage.h"
21 #include "extensions/browser/api/web_request/web_request_api_helpers.h"
22 #include "extensions/browser/api/web_request/web_request_permissions.h"
23 #include "extensions/browser/browser_context_keyed_api_factory.h"
24 #include "extensions/browser/event_router.h"
25 #include "extensions/browser/extension_function.h"
26 #include "extensions/common/url_pattern_set.h"
27 #include "ipc/ipc_sender.h"
28 #include "net/base/completion_callback.h"
29 #include "net/base/network_delegate.h"
30 #include "net/http/http_request_headers.h"
32 class ExtensionWebRequestTimeTracker
;
36 class DictionaryValue
;
46 class AuthCredentials
;
47 class AuthChallengeInfo
;
48 class HttpRequestHeaders
;
49 class HttpResponseHeaders
;
53 namespace extensions
{
56 class WebRequestRulesRegistry
;
57 class WebRequestEventRouterDelegate
;
59 // Support class for the WebRequest API. Lives on the UI thread. Most of the
60 // work is done by ExtensionWebRequestEventRouter below. This class observes
61 // extensions::EventRouter to deal with event listeners. There is one instance
62 // per BrowserContext which is shared with incognito.
63 class WebRequestAPI
: public BrowserContextKeyedAPI
,
64 public EventRouter::Observer
{
66 explicit WebRequestAPI(content::BrowserContext
* context
);
67 ~WebRequestAPI() override
;
69 // BrowserContextKeyedAPI support:
70 static BrowserContextKeyedAPIFactory
<WebRequestAPI
>* GetFactoryInstance();
72 // EventRouter::Observer overrides:
73 void OnListenerRemoved(const EventListenerInfo
& details
) override
;
76 friend class BrowserContextKeyedAPIFactory
<WebRequestAPI
>;
78 // BrowserContextKeyedAPI support:
79 static const char* service_name() { return "WebRequestAPI"; }
80 static const bool kServiceRedirectedInIncognito
= true;
81 static const bool kServiceIsNULLWhileTesting
= true;
83 content::BrowserContext
* browser_context_
;
85 DISALLOW_COPY_AND_ASSIGN(WebRequestAPI
);
88 } // namespace extensions
90 // This class observes network events and routes them to the appropriate
91 // extensions listening to those events. All methods must be called on the IO
92 // thread unless otherwise specified.
93 class ExtensionWebRequestEventRouter
94 : public base::SupportsWeakPtr
<ExtensionWebRequestEventRouter
> {
96 struct BlockedRequest
;
100 kOnBeforeRequest
= 1 << 0,
101 kOnBeforeSendHeaders
= 1 << 1,
102 kOnSendHeaders
= 1 << 2,
103 kOnHeadersReceived
= 1 << 3,
104 kOnBeforeRedirect
= 1 << 4,
105 kOnAuthRequired
= 1 << 5,
106 kOnResponseStarted
= 1 << 6,
107 kOnErrorOccurred
= 1 << 7,
108 kOnCompleted
= 1 << 8,
111 // Internal representation of the webRequest.RequestFilter type, used to
112 // filter what network events an extension cares about.
113 struct RequestFilter
{
117 // Returns false if there was an error initializing. If it is a user error,
118 // an error message is provided, otherwise the error is internal (and
120 bool InitFromValue(const base::DictionaryValue
& value
, std::string
* error
);
122 extensions::URLPatternSet urls
;
123 std::vector
<content::ResourceType
> types
;
128 // Internal representation of the extraInfoSpec parameter on webRequest
129 // events, used to specify extra information to be included with network
131 struct ExtraInfoSpec
{
133 REQUEST_HEADERS
= 1<<0,
134 RESPONSE_HEADERS
= 1<<1,
136 ASYNC_BLOCKING
= 1<<3,
140 static bool InitFromValue(const base::ListValue
& value
,
141 int* extra_info_spec
);
144 // Contains an extension's response to a blocking event.
145 struct EventResponse
{
146 EventResponse(const std::string
& extension_id
,
147 const base::Time
& extension_install_time
);
150 // ID of the extension that sent this response.
151 std::string extension_id
;
153 // The time that the extension was installed. Used for deciding order of
154 // precedence in case multiple extensions respond with conflicting
156 base::Time extension_install_time
;
158 // Response values. These are mutually exclusive.
161 scoped_ptr
<net::HttpRequestHeaders
> request_headers
;
162 scoped_ptr
<extension_web_request_api_helpers::ResponseHeaders
>
165 scoped_ptr
<net::AuthCredentials
> auth_credentials
;
167 DISALLOW_COPY_AND_ASSIGN(EventResponse
);
170 static ExtensionWebRequestEventRouter
* GetInstance();
172 // Registers a rule registry. Pass null for |rules_registry| to unregister
173 // the rule registry for |browser_context|.
174 void RegisterRulesRegistry(
175 void* browser_context
,
176 int rules_registry_id
,
177 scoped_refptr
<extensions::WebRequestRulesRegistry
> rules_registry
);
179 // Dispatches the OnBeforeRequest event to any extensions whose filters match
180 // the given request. Returns net::ERR_IO_PENDING if an extension is
181 // intercepting the request, OK otherwise.
182 int OnBeforeRequest(void* browser_context
,
183 extensions::InfoMap
* extension_info_map
,
184 net::URLRequest
* request
,
185 const net::CompletionCallback
& callback
,
188 // Dispatches the onBeforeSendHeaders event. This is fired for HTTP(s)
189 // requests only, and allows modification of the outgoing request headers.
190 // Returns net::ERR_IO_PENDING if an extension is intercepting the request, OK
192 int OnBeforeSendHeaders(void* browser_context
,
193 extensions::InfoMap
* extension_info_map
,
194 net::URLRequest
* request
,
195 const net::CompletionCallback
& callback
,
196 net::HttpRequestHeaders
* headers
);
198 // Dispatches the onSendHeaders event. This is fired for HTTP(s) requests
200 void OnSendHeaders(void* browser_context
,
201 extensions::InfoMap
* extension_info_map
,
202 net::URLRequest
* request
,
203 const net::HttpRequestHeaders
& headers
);
205 // Dispatches the onHeadersReceived event. This is fired for HTTP(s)
206 // requests only, and allows modification of incoming response headers.
207 // Returns net::ERR_IO_PENDING if an extension is intercepting the request,
208 // OK otherwise. |original_response_headers| is reference counted. |callback|
209 // |override_response_headers| and |allowed_unsafe_redirect_url| are owned by
210 // a URLRequestJob. They are guaranteed to be valid until |callback| is called
211 // or OnURLRequestDestroyed is called (whatever comes first).
212 // Do not modify |original_response_headers| directly but write new ones
213 // into |override_response_headers|.
214 int OnHeadersReceived(
215 void* browser_context
,
216 extensions::InfoMap
* extension_info_map
,
217 net::URLRequest
* request
,
218 const net::CompletionCallback
& callback
,
219 const net::HttpResponseHeaders
* original_response_headers
,
220 scoped_refptr
<net::HttpResponseHeaders
>* override_response_headers
,
221 GURL
* allowed_unsafe_redirect_url
);
223 // Dispatches the OnAuthRequired event to any extensions whose filters match
224 // the given request. If the listener is not registered as "blocking", then
225 // AUTH_REQUIRED_RESPONSE_OK is returned. Otherwise,
226 // AUTH_REQUIRED_RESPONSE_IO_PENDING is returned and |callback| will be
228 net::NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
229 void* browser_context
,
230 extensions::InfoMap
* extension_info_map
,
231 net::URLRequest
* request
,
232 const net::AuthChallengeInfo
& auth_info
,
233 const net::NetworkDelegate::AuthCallback
& callback
,
234 net::AuthCredentials
* credentials
);
236 // Dispatches the onBeforeRedirect event. This is fired for HTTP(s) requests
238 void OnBeforeRedirect(void* browser_context
,
239 extensions::InfoMap
* extension_info_map
,
240 net::URLRequest
* request
,
241 const GURL
& new_location
);
243 // Dispatches the onResponseStarted event indicating that the first bytes of
244 // the response have arrived.
245 void OnResponseStarted(void* browser_context
,
246 extensions::InfoMap
* extension_info_map
,
247 net::URLRequest
* request
);
249 // Dispatches the onComplete event.
250 void OnCompleted(void* browser_context
,
251 extensions::InfoMap
* extension_info_map
,
252 net::URLRequest
* request
);
254 // Dispatches an onErrorOccurred event.
255 void OnErrorOccurred(void* browser_context
,
256 extensions::InfoMap
* extension_info_map
,
257 net::URLRequest
* request
,
260 // Notifications when objects are going away.
261 void OnURLRequestDestroyed(void* browser_context
, net::URLRequest
* request
);
263 // Called when an event listener handles a blocking event and responds.
265 void* browser_context
,
266 const std::string
& extension_id
,
267 const std::string
& event_name
,
268 const std::string
& sub_event_name
,
270 EventResponse
* response
);
272 // Adds a listener to the given event. |event_name| specifies the event being
273 // listened to. |sub_event_name| is an internal event uniquely generated in
274 // the extension process to correspond to the given filter and
275 // extra_info_spec. It returns true on success, false on failure.
276 bool AddEventListener(
277 void* browser_context
,
278 const std::string
& extension_id
,
279 const std::string
& extension_name
,
280 const std::string
& event_name
,
281 const std::string
& sub_event_name
,
282 const RequestFilter
& filter
,
284 int embedder_process_id
,
285 int web_view_instance_id
,
286 base::WeakPtr
<IPC::Sender
> ipc_sender
);
288 // Removes the listener for the given sub-event.
289 void RemoveEventListener(
290 void* browser_context
,
291 const std::string
& extension_id
,
292 const std::string
& sub_event_name
,
293 int embedder_process_id
,
294 int web_view_instance_id
);
296 // Removes the listeners for a given <webview>.
297 void RemoveWebViewEventListeners(
298 void* browser_context
,
299 const std::string
& extension_id
,
300 int embedder_process_id
,
301 int web_view_instance_id
);
303 // Called when an incognito browser_context is created or destroyed.
304 void OnOTRBrowserContextCreated(void* original_browser_context
,
305 void* otr_browser_context
);
306 void OnOTRBrowserContextDestroyed(void* original_browser_context
,
307 void* otr_browser_context
);
309 // Registers a |callback| that is executed when the next page load happens.
310 // The callback is then deleted.
311 void AddCallbackForPageLoad(const base::Closure
& callback
);
314 friend struct DefaultSingletonTraits
<ExtensionWebRequestEventRouter
>;
316 struct EventListener
;
317 typedef std::map
<std::string
, std::set
<EventListener
> >
318 ListenerMapForBrowserContext
;
319 typedef std::map
<void*, ListenerMapForBrowserContext
> ListenerMap
;
320 typedef std::map
<uint64
, BlockedRequest
> BlockedRequestMap
;
321 // Map of request_id -> bit vector of EventTypes already signaled
322 typedef std::map
<uint64
, int> SignaledRequestMap
;
323 // For each browser_context: a bool indicating whether it is an incognito
324 // browser_context, and a pointer to the corresponding (non-)incognito
326 typedef std::map
<void*, std::pair
<bool, void*> > CrossBrowserContextMap
;
327 typedef std::list
<base::Closure
> CallbacksForPageLoad
;
329 ExtensionWebRequestEventRouter();
330 ~ExtensionWebRequestEventRouter();
332 // Ensures that future callbacks for |request| are ignored so that it can be
334 void ClearPendingCallbacks(net::URLRequest
* request
);
337 void* browser_context
,
338 net::URLRequest
* request
,
339 const std::vector
<const EventListener
*>& listeners
,
340 const base::ListValue
& args
);
342 // Returns a list of event listeners that care about the given event, based
343 // on their filter parameters. |extra_info_spec| will contain the combined
344 // set of extra_info_spec flags that every matching listener asked for.
345 std::vector
<const EventListener
*> GetMatchingListeners(
346 void* browser_context
,
347 extensions::InfoMap
* extension_info_map
,
348 const std::string
& event_name
,
349 net::URLRequest
* request
,
350 int* extra_info_spec
);
352 // Helper for the above functions. This is called twice: once for the
353 // browser_context of the event, the next time for the "cross" browser_context
354 // (i.e. the incognito browser_context if the event is originally for the
355 // normal browser_context, or vice versa).
356 void GetMatchingListenersImpl(
357 void* browser_context
,
358 net::URLRequest
* request
,
359 extensions::InfoMap
* extension_info_map
,
360 bool crosses_incognito
,
361 const std::string
& event_name
,
363 int render_process_host_id
,
365 content::ResourceType resource_type
,
366 bool is_async_request
,
367 bool is_request_from_extension
,
368 int* extra_info_spec
,
369 std::vector
<const ExtensionWebRequestEventRouter::EventListener
*>*
372 // Decrements the count of event handlers blocking the given request. When the
373 // count reaches 0, we stop blocking the request and proceed it using the
374 // method requested by the extension with the highest precedence. Precedence
375 // is decided by extension install time. If |response| is non-NULL, this
376 // method assumes ownership.
377 void DecrementBlockCount(
378 void* browser_context
,
379 const std::string
& extension_id
,
380 const std::string
& event_name
,
382 EventResponse
* response
);
384 // Logs an extension action.
385 void LogExtensionActivity(
386 void* browser_context_id
,
388 const std::string
& extension_id
,
390 const std::string
& api_call
,
391 scoped_ptr
<base::DictionaryValue
> details
);
393 // Processes the generated deltas from blocked_requests_ on the specified
394 // request. If |call_back| is true, the callback registered in
395 // |blocked_requests_| is called.
396 // The function returns the error code for the network request. This is
397 // mostly relevant in case the caller passes |call_callback| = false
398 // and wants to return the correct network error code himself.
400 void* browser_context
, uint64 request_id
, bool call_callback
);
402 // Evaluates the rules of the declarative webrequest API and stores
403 // modifications to the request that result from WebRequestActions as
404 // deltas in |blocked_requests_|. |original_response_headers| should only be
405 // set for the OnHeadersReceived stage and NULL otherwise. Returns whether any
406 // deltas were generated.
407 bool ProcessDeclarativeRules(
408 void* browser_context
,
409 extensions::InfoMap
* extension_info_map
,
410 const std::string
& event_name
,
411 net::URLRequest
* request
,
412 extensions::RequestStage request_stage
,
413 const net::HttpResponseHeaders
* original_response_headers
);
415 // If the BlockedRequest contains messages_to_extension entries in the event
416 // deltas, we send them to subscribers of
417 // chrome.declarativeWebRequest.onMessage.
419 void* browser_context
, const BlockedRequest
& blocked_request
);
421 // Called when the RulesRegistry is ready to unblock a request that was
422 // waiting for said event.
423 void OnRulesRegistryReady(
424 void* browser_context
,
425 const std::string
& event_name
,
427 extensions::RequestStage request_stage
);
429 // Extracts from |request| information for the keys requestId, url, method,
430 // frameId, tabId, type, and timeStamp and writes these into |out| to be
431 // passed on to extensions.
432 void ExtractRequestInfo(net::URLRequest
* request
, base::DictionaryValue
* out
);
434 // Sets the flag that |event_type| has been signaled for |request_id|.
435 // Returns the value of the flag before setting it.
436 bool GetAndSetSignaled(uint64 request_id
, EventTypes event_type
);
438 // Clears the flag that |event_type| has been signaled for |request_id|.
439 void ClearSignaled(uint64 request_id
, EventTypes event_type
);
441 // Returns whether |request| represents a top level window navigation.
442 bool IsPageLoad(net::URLRequest
* request
) const;
444 // Called on a page load to process all registered callbacks.
445 void NotifyPageLoad();
447 // Returns the matching cross browser_context (the regular browser_context if
448 // |browser_context| is OTR and vice versa).
449 void* GetCrossBrowserContext(void* browser_context
) const;
451 // Determines whether the specified browser_context is an incognito
452 // browser_context (based on the contents of the cross-browser_context table
453 // and without dereferencing the browser_context pointer).
454 bool IsIncognitoBrowserContext(void* browser_context
) const;
456 // Returns true if |request| was already signaled to some event handlers.
457 bool WasSignaled(const net::URLRequest
& request
) const;
459 // A map for each browser_context that maps an event name to a set of
460 // extensions that are listening to that event.
461 ListenerMap listeners_
;
463 // A map of network requests that are waiting for at least one event handler
465 BlockedRequestMap blocked_requests_
;
467 // A map of request ids to a bitvector indicating which events have been
468 // signaled and should not be sent again.
469 SignaledRequestMap signaled_requests_
;
471 // A map of original browser_context -> corresponding incognito
472 // browser_context (and vice versa).
473 CrossBrowserContextMap cross_browser_context_map_
;
475 // Keeps track of time spent waiting on extensions using the blocking
477 scoped_ptr
<ExtensionWebRequestTimeTracker
> request_time_tracker_
;
479 CallbacksForPageLoad callbacks_for_page_load_
;
481 typedef std::pair
<void*, int> RulesRegistryKey
;
482 // Maps each browser_context (and OTRBrowserContext) and a webview key to its
483 // respective rules registry.
484 std::map
<RulesRegistryKey
,
485 scoped_refptr
<extensions::WebRequestRulesRegistry
> > rules_registries_
;
487 scoped_ptr
<extensions::WebRequestEventRouterDelegate
>
488 web_request_event_router_delegate_
;
490 DISALLOW_COPY_AND_ASSIGN(ExtensionWebRequestEventRouter
);
493 class WebRequestInternalFunction
: public SyncIOThreadExtensionFunction
{
495 WebRequestInternalFunction() {}
498 ~WebRequestInternalFunction() override
{}
500 const std::string
& extension_id_safe() const {
501 return extension() ? extension_id() : base::EmptyString();
505 class WebRequestInternalAddEventListenerFunction
506 : public WebRequestInternalFunction
{
508 DECLARE_EXTENSION_FUNCTION("webRequestInternal.addEventListener",
509 WEBREQUESTINTERNAL_ADDEVENTLISTENER
)
512 ~WebRequestInternalAddEventListenerFunction() override
{}
514 // ExtensionFunction:
515 bool RunSync() override
;
518 class WebRequestInternalEventHandledFunction
519 : public WebRequestInternalFunction
{
521 DECLARE_EXTENSION_FUNCTION("webRequestInternal.eventHandled",
522 WEBREQUESTINTERNAL_EVENTHANDLED
)
525 ~WebRequestInternalEventHandledFunction() override
{}
527 // Unblocks the network request and sets |error_| such that the developer
528 // console will show the respective error message. Use this function to handle
529 // incorrect requests from the extension that cannot be detected by the schema
531 void RespondWithError(
532 const std::string
& event_name
,
533 const std::string
& sub_event_name
,
535 scoped_ptr
<ExtensionWebRequestEventRouter::EventResponse
> response
,
536 const std::string
& error
);
538 // ExtensionFunction:
539 bool RunSync() override
;
542 class WebRequestHandlerBehaviorChangedFunction
543 : public WebRequestInternalFunction
{
545 DECLARE_EXTENSION_FUNCTION("webRequest.handlerBehaviorChanged",
546 WEBREQUEST_HANDLERBEHAVIORCHANGED
)
549 ~WebRequestHandlerBehaviorChangedFunction() override
{}
551 // ExtensionFunction:
552 void GetQuotaLimitHeuristics(
553 extensions::QuotaLimitHeuristics
* heuristics
) const override
;
554 // Handle quota exceeded gracefully: Only warn the user but still execute the
556 void OnQuotaExceeded(const std::string
& error
) override
;
557 bool RunSync() override
;
560 #endif // EXTENSIONS_BROWSER_API_WEB_REQUEST_WEB_REQUEST_API_H_