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_EVENT_ROUTER_H_
6 #define EXTENSIONS_BROWSER_EVENT_ROUTER_H_
13 #include "base/callback.h"
14 #include "base/compiler_specific.h"
15 #include "base/containers/hash_tables.h"
16 #include "base/memory/linked_ptr.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/scoped_observer.h"
19 #include "base/values.h"
20 #include "components/keyed_service/core/keyed_service.h"
21 #include "content/public/browser/notification_observer.h"
22 #include "content/public/browser/notification_registrar.h"
23 #include "content/public/browser/render_process_host_observer.h"
24 #include "extensions/browser/event_listener_map.h"
25 #include "extensions/browser/extension_event_histogram_value.h"
26 #include "extensions/browser/extension_registry_observer.h"
27 #include "extensions/common/event_filtering_info.h"
28 #include "ipc/ipc_sender.h"
35 class RenderProcessHost
;
38 namespace extensions
{
43 class ExtensionRegistry
;
46 struct EventDispatchInfo
;
47 struct EventListenerInfo
;
49 class EventRouter
: public KeyedService
,
50 public content::NotificationObserver
,
51 public ExtensionRegistryObserver
,
52 public EventListenerMap::Delegate
,
53 public content::RenderProcessHostObserver
{
55 // These constants convey the state of our knowledge of whether we're in
56 // a user-caused gesture as part of DispatchEvent.
57 enum UserGestureState
{
58 USER_GESTURE_UNKNOWN
= 0,
59 USER_GESTURE_ENABLED
= 1,
60 USER_GESTURE_NOT_ENABLED
= 2,
63 // The pref key for the list of event names for which an extension has
64 // registered from its lazy background page.
65 static const char kRegisteredEvents
[];
67 // Observers register interest in events with a particular name and are
68 // notified when a listener is added or removed. Observers are matched by
69 // the base name of the event (e.g. adding an event listener for event name
70 // "foo.onBar/123" will trigger observers registered for "foo.onBar").
73 // Called when a listener is added.
74 virtual void OnListenerAdded(const EventListenerInfo
& details
) {}
75 // Called when a listener is removed.
76 virtual void OnListenerRemoved(const EventListenerInfo
& details
) {}
79 // Gets the EventRouter for |browser_context|.
80 static EventRouter
* Get(content::BrowserContext
* browser_context
);
82 // Converts event names like "foo.onBar/123" into "foo.onBar". Event names
83 // without a "/" are returned unchanged.
84 static std::string
GetBaseEventName(const std::string
& full_event_name
);
86 // Sends an event via ipc_sender to the given extension. Can be called on any
88 static void DispatchEvent(IPC::Sender
* ipc_sender
,
89 void* browser_context_id
,
90 const std::string
& extension_id
,
91 const std::string
& event_name
,
92 scoped_ptr
<base::ListValue
> event_args
,
93 UserGestureState user_gesture
,
94 const EventFilteringInfo
& info
);
96 // An EventRouter is shared between |browser_context| and its associated
97 // incognito context. |extension_prefs| may be NULL in tests.
98 EventRouter(content::BrowserContext
* browser_context
,
99 ExtensionPrefs
* extension_prefs
);
100 ~EventRouter() override
;
102 // Add or remove an extension as an event listener for |event_name|.
104 // Note that multiple extensions can share a process due to process
105 // collapsing. Also, a single extension can have 2 processes if it is a split
107 void AddEventListener(const std::string
& event_name
,
108 content::RenderProcessHost
* process
,
109 const std::string
& extension_id
);
110 void RemoveEventListener(const std::string
& event_name
,
111 content::RenderProcessHost
* process
,
112 const std::string
& extension_id
);
114 // Add or remove a URL as an event listener for |event_name|.
115 void AddEventListenerForURL(const std::string
& event_name
,
116 content::RenderProcessHost
* process
,
117 const GURL
& listener_url
);
118 void RemoveEventListenerForURL(const std::string
& event_name
,
119 content::RenderProcessHost
* process
,
120 const GURL
& listener_url
);
122 EventListenerMap
& listeners() { return listeners_
; }
124 // Registers an observer to be notified when an event listener for
125 // |event_name| is added or removed. There can currently be only one observer
126 // for each distinct |event_name|.
127 void RegisterObserver(Observer
* observer
,
128 const std::string
& event_name
);
130 // Unregisters an observer from all events.
131 void UnregisterObserver(Observer
* observer
);
133 // Add or remove the extension as having a lazy background page that listens
134 // to the event. The difference from the above methods is that these will be
135 // remembered even after the process goes away. We use this list to decide
136 // which extension pages to load when dispatching an event.
137 void AddLazyEventListener(const std::string
& event_name
,
138 const std::string
& extension_id
);
139 void RemoveLazyEventListener(const std::string
& event_name
,
140 const std::string
& extension_id
);
142 // If |add_lazy_listener| is true also add the lazy version of this listener.
143 void AddFilteredEventListener(const std::string
& event_name
,
144 content::RenderProcessHost
* process
,
145 const std::string
& extension_id
,
146 const base::DictionaryValue
& filter
,
147 bool add_lazy_listener
);
149 // If |remove_lazy_listener| is true also remove the lazy version of this
151 void RemoveFilteredEventListener(const std::string
& event_name
,
152 content::RenderProcessHost
* process
,
153 const std::string
& extension_id
,
154 const base::DictionaryValue
& filter
,
155 bool remove_lazy_listener
);
157 // Returns true if there is at least one listener for the given event.
158 bool HasEventListener(const std::string
& event_name
);
160 // Returns true if the extension is listening to the given event.
161 bool ExtensionHasEventListener(const std::string
& extension_id
,
162 const std::string
& event_name
);
164 // Return or set the list of events for which the given extension has
166 std::set
<std::string
> GetRegisteredEvents(const std::string
& extension_id
);
167 void SetRegisteredEvents(const std::string
& extension_id
,
168 const std::set
<std::string
>& events
);
170 // Broadcasts an event to every listener registered for that event.
171 virtual void BroadcastEvent(scoped_ptr
<Event
> event
);
173 // Dispatches an event to the given extension.
174 virtual void DispatchEventToExtension(const std::string
& extension_id
,
175 scoped_ptr
<Event
> event
);
177 // Dispatches |event| to the given extension as if the extension has a lazy
178 // listener for it. NOTE: This should be used rarely, for dispatching events
179 // to extensions that haven't had a chance to add their own listeners yet, eg:
180 // newly installed extensions.
181 void DispatchEventWithLazyListener(const std::string
& extension_id
,
182 scoped_ptr
<Event
> event
);
184 // Record the Event Ack from the renderer. (One less event in-flight.)
185 void OnEventAck(content::BrowserContext
* context
,
186 const std::string
& extension_id
);
189 friend class EventRouterTest
;
191 // The extension and process that contains the event listener for a given
193 struct ListenerProcess
;
195 // A map between an event name and a set of extensions that are listening
197 typedef std::map
<std::string
, std::set
<ListenerProcess
> > ListenerMap
;
199 // An identifier for an event dispatch that is used to prevent double dispatch
200 // due to race conditions between the direct and lazy dispatch paths.
201 typedef std::pair
<const content::BrowserContext
*, std::string
>
202 EventDispatchIdentifier
;
204 // TODO(gdk): Document this.
205 static void DispatchExtensionMessage(
206 IPC::Sender
* ipc_sender
,
207 void* browser_context_id
,
208 const std::string
& extension_id
,
210 const std::string
& event_name
,
211 base::ListValue
* event_args
,
212 UserGestureState user_gesture
,
213 const extensions::EventFilteringInfo
& info
);
215 void Observe(int type
,
216 const content::NotificationSource
& source
,
217 const content::NotificationDetails
& details
) override
;
218 // ExtensionRegistryObserver implementation.
219 void OnExtensionLoaded(content::BrowserContext
* browser_context
,
220 const Extension
* extension
) override
;
221 void OnExtensionUnloaded(content::BrowserContext
* browser_context
,
222 const Extension
* extension
,
223 UnloadedExtensionInfo::Reason reason
) override
;
225 // Returns true if the given listener map contains a event listeners for
226 // the given event. If |extension_id| is non-empty, we also check that that
227 // extension is one of the listeners.
228 bool HasEventListenerImpl(const ListenerMap
& listeners
,
229 const std::string
& extension_id
,
230 const std::string
& event_name
);
232 // Shared by DispatchEvent*. If |restrict_to_extension_id| is empty, the
233 // event is broadcast.
234 // An event that just came off the pending list may not be delayed again.
235 void DispatchEventImpl(const std::string
& restrict_to_extension_id
,
236 const linked_ptr
<Event
>& event
);
238 // Ensures that all lazy background pages that are interested in the given
239 // event are loaded, and queues the event if the page is not ready yet.
240 // Inserts an EventDispatchIdentifier into |already_dispatched| for each lazy
241 // event dispatch that is queued.
242 void DispatchLazyEvent(const std::string
& extension_id
,
243 const linked_ptr
<Event
>& event
,
244 std::set
<EventDispatchIdentifier
>* already_dispatched
,
245 const base::DictionaryValue
* listener_filter
);
247 // Dispatches the event to the specified extension or URL running in
249 void DispatchEventToProcess(const std::string
& extension_id
,
250 const GURL
& listener_url
,
251 content::RenderProcessHost
* process
,
252 const linked_ptr
<Event
>& event
,
253 const base::DictionaryValue
* listener_filter
);
255 // Returns false when the event is scoped to a context and the listening
256 // extension does not have access to events from that context. Also fills
257 // |event_args| with the proper arguments to send, which may differ if
258 // the event crosses the incognito boundary.
259 bool CanDispatchEventToBrowserContext(content::BrowserContext
* context
,
260 const Extension
* extension
,
261 const linked_ptr
<Event
>& event
);
263 // Possibly loads given extension's background page in preparation to
264 // dispatch an event. Returns true if the event was queued for subsequent
265 // dispatch, false otherwise.
266 bool MaybeLoadLazyBackgroundPageToDispatchEvent(
267 content::BrowserContext
* context
,
268 const Extension
* extension
,
269 const linked_ptr
<Event
>& event
,
270 const base::DictionaryValue
* listener_filter
);
272 // Adds a filter to an event.
273 void AddFilterToEvent(const std::string
& event_name
,
274 const std::string
& extension_id
,
275 const base::DictionaryValue
* filter
);
277 // Removes a filter from an event.
278 void RemoveFilterFromEvent(const std::string
& event_name
,
279 const std::string
& extension_id
,
280 const base::DictionaryValue
* filter
);
282 // Returns the dictionary of event filters that the given extension has
284 const base::DictionaryValue
* GetFilteredEvents(
285 const std::string
& extension_id
);
287 // Track the dispatched events that have not yet sent an ACK from the
289 void IncrementInFlightEvents(content::BrowserContext
* context
,
290 const Extension
* extension
,
292 const std::string
& event_name
);
295 static void IncrementInFlightEventsOnUI(void* browser_context_id
,
296 const std::string
& extension_id
,
298 const std::string
& event_name
);
300 void DispatchPendingEvent(const linked_ptr
<Event
>& event
,
301 ExtensionHost
* host
);
303 // Implementation of EventListenerMap::Delegate.
304 void OnListenerAdded(const EventListener
* listener
) override
;
305 void OnListenerRemoved(const EventListener
* listener
) override
;
307 // RenderProcessHostObserver implementation.
308 void RenderProcessExited(content::RenderProcessHost
* host
,
309 base::TerminationStatus status
,
310 int exit_code
) override
;
311 void RenderProcessHostDestroyed(content::RenderProcessHost
* host
) override
;
313 content::BrowserContext
* browser_context_
;
315 // The ExtensionPrefs associated with |browser_context_|. May be NULL in
317 ExtensionPrefs
* extension_prefs_
;
319 content::NotificationRegistrar registrar_
;
321 ScopedObserver
<ExtensionRegistry
, ExtensionRegistryObserver
>
322 extension_registry_observer_
;
324 EventListenerMap listeners_
;
326 // Map from base event name to observer.
327 typedef base::hash_map
<std::string
, Observer
*> ObserverMap
;
328 ObserverMap observers_
;
330 std::set
<content::RenderProcessHost
*> observed_process_set_
;
332 DISALLOW_COPY_AND_ASSIGN(EventRouter
);
336 // This callback should return true if the event should be dispatched to the
337 // given context and extension, and false otherwise.
338 typedef base::Callback
<bool(content::BrowserContext
*,
341 const base::DictionaryValue
*)>
342 WillDispatchCallback
;
344 // The identifier for the event, for histograms. In most cases this
345 // correlates 1:1 with |event_name|, in some cases events will generate
346 // their own names, but they cannot generate their own identifier.
347 events::HistogramValue histogram_value
;
349 // The event to dispatch.
350 std::string event_name
;
352 // Arguments to send to the event listener.
353 scoped_ptr
<base::ListValue
> event_args
;
355 // If non-NULL, then the event will not be sent to other BrowserContexts
356 // unless the extension has permission (e.g. incognito tab update -> normal
357 // tab only works if extension is allowed incognito access).
358 content::BrowserContext
* restrict_to_browser_context
;
360 // If not empty, the event is only sent to extensions with host permissions
364 // Whether a user gesture triggered the event.
365 EventRouter::UserGestureState user_gesture
;
367 // Extra information used to filter which events are sent to the listener.
368 EventFilteringInfo filter_info
;
370 // If specified, this is called before dispatching an event to each
371 // extension. The third argument is a mutable reference to event_args,
372 // allowing the caller to provide different arguments depending on the
373 // extension and profile. This is guaranteed to be called synchronously with
374 // DispatchEvent, so callers don't need to worry about lifetime.
376 // NOTE: the Extension argument to this may be NULL because it's possible for
377 // this event to be dispatched to non-extension processes, like WebUI.
378 WillDispatchCallback will_dispatch_callback
;
380 Event(events::HistogramValue histogram_value
,
381 const std::string
& event_name
,
382 scoped_ptr
<base::ListValue
> event_args
);
384 Event(events::HistogramValue histogram_value
,
385 const std::string
& event_name
,
386 scoped_ptr
<base::ListValue
> event_args
,
387 content::BrowserContext
* restrict_to_browser_context
);
389 Event(events::HistogramValue histogram_value
,
390 const std::string
& event_name
,
391 scoped_ptr
<base::ListValue
> event_args
,
392 content::BrowserContext
* restrict_to_browser_context
,
393 const GURL
& event_url
,
394 EventRouter::UserGestureState user_gesture
,
395 const EventFilteringInfo
& info
);
399 // Makes a deep copy of this instance. Ownership is transferred to the
404 struct EventListenerInfo
{
405 EventListenerInfo(const std::string
& event_name
,
406 const std::string
& extension_id
,
407 const GURL
& listener_url
,
408 content::BrowserContext
* browser_context
);
409 // The event name including any sub-event, e.g. "runtime.onStartup" or
410 // "webRequest.onCompleted/123".
411 const std::string event_name
;
413 const std::string extension_id
;
414 const GURL listener_url
;
415 content::BrowserContext
* browser_context
;
418 } // namespace extensions
420 #endif // EXTENSIONS_BROWSER_EVENT_ROUTER_H_