1// Copyright 2014 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.
4
5#include "extensions/renderer/event_bindings.h"
6
7#include <map>
8#include <set>
9#include <string>
10#include <vector>
11
12#include "base/basictypes.h"
13#include "base/bind.h"
14#include "base/lazy_instance.h"
15#include "base/memory/scoped_ptr.h"
16#include "content/public/renderer/render_thread.h"
17#include "content/public/renderer/render_view.h"
18#include "content/public/renderer/v8_value_converter.h"
19#include "extensions/common/event_filter.h"
20#include "extensions/common/extension.h"
21#include "extensions/common/extension_messages.h"
22#include "extensions/common/manifest_handlers/background_info.h"
23#include "extensions/common/value_counter.h"
24#include "extensions/renderer/dispatcher.h"
25#include "extensions/renderer/extension_helper.h"
26#include "extensions/renderer/object_backed_native_handler.h"
27#include "url/gurl.h"
28#include "v8/include/v8.h"
29
30namespace extensions {
31
32namespace {
33
34// A map of event names to the number of contexts listening to that event.
35// We notify the browser about event listeners when we transition between 0
36// and 1.
37typedef std::map<std::string, int> EventListenerCounts;
38
39// A map of extension IDs to listener counts for that extension.
40base::LazyInstance<std::map<std::string, EventListenerCounts> >
41    g_listener_counts = LAZY_INSTANCE_INITIALIZER;
42
43// A map of event names to a (filter -> count) map. The map is used to keep
44// track of which filters are in effect for which events.
45// We notify the browser about filtered event listeners when we transition
46// between 0 and 1.
47typedef std::map<std::string, linked_ptr<ValueCounter> >
48    FilteredEventListenerCounts;
49
50// A map of extension IDs to filtered listener counts for that extension.
51base::LazyInstance<std::map<std::string, FilteredEventListenerCounts> >
52    g_filtered_listener_counts = LAZY_INSTANCE_INITIALIZER;
53
54base::LazyInstance<EventFilter> g_event_filter = LAZY_INSTANCE_INITIALIZER;
55
56bool IsLazyBackgroundPage(content::RenderView* render_view,
57                          const Extension* extension) {
58  if (!render_view)
59    return false;
60  ExtensionHelper* helper = ExtensionHelper::Get(render_view);
61  return (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
62          helper->view_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE);
63}
64
65EventFilteringInfo ParseFromObject(v8::Handle<v8::Object> object,
66                                   v8::Isolate* isolate) {
67  EventFilteringInfo info;
68  v8::Handle<v8::String> url(v8::String::NewFromUtf8(isolate, "url"));
69  if (object->Has(url)) {
70    v8::Handle<v8::Value> url_value(object->Get(url));
71    info.SetURL(GURL(*v8::String::Utf8Value(url_value)));
72  }
73  v8::Handle<v8::String> instance_id(
74      v8::String::NewFromUtf8(isolate, "instanceId"));
75  if (object->Has(instance_id)) {
76    v8::Handle<v8::Value> instance_id_value(object->Get(instance_id));
77    info.SetInstanceID(instance_id_value->IntegerValue());
78  }
79  v8::Handle<v8::String> service_type(
80      v8::String::NewFromUtf8(isolate, "serviceType"));
81  if (object->Has(service_type)) {
82    v8::Handle<v8::Value> service_type_value(object->Get(service_type));
83    info.SetServiceType(*v8::String::Utf8Value(service_type_value));
84  }
85  return info;
86}
87
88// Add a filter to |event_name| in |extension_id|, returning true if it
89// was the first filter for that event in that extension.
90bool AddFilter(const std::string& event_name,
91               const std::string& extension_id,
92               base::DictionaryValue* filter) {
93  FilteredEventListenerCounts& counts =
94      g_filtered_listener_counts.Get()[extension_id];
95  FilteredEventListenerCounts::iterator it = counts.find(event_name);
96  if (it == counts.end())
97    counts[event_name].reset(new ValueCounter);
98
99  int result = counts[event_name]->Add(*filter);
100  return 1 == result;
101}
102
103// Remove a filter from |event_name| in |extension_id|, returning true if it
104// was the last filter for that event in that extension.
105bool RemoveFilter(const std::string& event_name,
106                  const std::string& extension_id,
107                  base::DictionaryValue* filter) {
108  FilteredEventListenerCounts& counts =
109      g_filtered_listener_counts.Get()[extension_id];
110  FilteredEventListenerCounts::iterator it = counts.find(event_name);
111  if (it == counts.end())
112    return false;
113  return 0 == it->second->Remove(*filter);
114}
115
116}  // namespace
117
118EventBindings::EventBindings(Dispatcher* dispatcher, ScriptContext* context)
119    : ObjectBackedNativeHandler(context), dispatcher_(dispatcher) {
120  RouteFunction(
121      "AttachEvent",
122      base::Bind(&EventBindings::AttachEvent, base::Unretained(this)));
123  RouteFunction(
124      "DetachEvent",
125      base::Bind(&EventBindings::DetachEvent, base::Unretained(this)));
126  RouteFunction(
127      "AttachFilteredEvent",
128      base::Bind(&EventBindings::AttachFilteredEvent, base::Unretained(this)));
129  RouteFunction(
130      "DetachFilteredEvent",
131      base::Bind(&EventBindings::DetachFilteredEvent, base::Unretained(this)));
132  RouteFunction("MatchAgainstEventFilter",
133                base::Bind(&EventBindings::MatchAgainstEventFilter,
134                           base::Unretained(this)));
135}
136
137EventBindings::~EventBindings() {}
138
139// Attach an event name to an object.
140void EventBindings::AttachEvent(
141    const v8::FunctionCallbackInfo<v8::Value>& args) {
142  CHECK_EQ(1, args.Length());
143  CHECK(args[0]->IsString());
144
145  std::string event_name = *v8::String::Utf8Value(args[0]->ToString());
146
147  if (!dispatcher_->CheckContextAccessToExtensionAPI(event_name, context()))
148    return;
149
150  std::string extension_id = context()->GetExtensionID();
151  EventListenerCounts& listener_counts = g_listener_counts.Get()[extension_id];
152  if (++listener_counts[event_name] == 1) {
153    content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
154        extension_id, context()->GetURL(), event_name));
155  }
156
157  // This is called the first time the page has added a listener. Since
158  // the background page is the only lazy page, we know this is the first
159  // time this listener has been registered.
160  if (IsLazyBackgroundPage(context()->GetRenderView(),
161                           context()->extension())) {
162    content::RenderThread::Get()->Send(
163        new ExtensionHostMsg_AddLazyListener(extension_id, event_name));
164  }
165}
166
167void EventBindings::DetachEvent(
168    const v8::FunctionCallbackInfo<v8::Value>& args) {
169  CHECK_EQ(2, args.Length());
170  CHECK(args[0]->IsString());
171  CHECK(args[1]->IsBoolean());
172
173  std::string event_name = *v8::String::Utf8Value(args[0]);
174  bool is_manual = args[1]->BooleanValue();
175
176  std::string extension_id = context()->GetExtensionID();
177  EventListenerCounts& listener_counts = g_listener_counts.Get()[extension_id];
178
179  if (--listener_counts[event_name] == 0) {
180    content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener(
181        extension_id, context()->GetURL(), event_name));
182  }
183
184  // DetachEvent is called when the last listener for the context is
185  // removed. If the context is the background page, and it removes the
186  // last listener manually, then we assume that it is no longer interested
187  // in being awakened for this event.
188  if (is_manual && IsLazyBackgroundPage(context()->GetRenderView(),
189                                        context()->extension())) {
190    content::RenderThread::Get()->Send(
191        new ExtensionHostMsg_RemoveLazyListener(extension_id, event_name));
192  }
193}
194
195// MatcherID AttachFilteredEvent(string event_name, object filter)
196// event_name - Name of the event to attach.
197// filter - Which instances of the named event are we interested in.
198// returns the id assigned to the listener, which will be returned from calls
199// to MatchAgainstEventFilter where this listener matches.
200void EventBindings::AttachFilteredEvent(
201    const v8::FunctionCallbackInfo<v8::Value>& args) {
202  CHECK_EQ(2, args.Length());
203  CHECK(args[0]->IsString());
204  CHECK(args[1]->IsObject());
205
206  std::string event_name = *v8::String::Utf8Value(args[0]);
207
208  // This method throws an exception if it returns false.
209  if (!dispatcher_->CheckContextAccessToExtensionAPI(event_name, context()))
210    return;
211
212  std::string extension_id = context()->GetExtensionID();
213
214  scoped_ptr<base::DictionaryValue> filter;
215  scoped_ptr<content::V8ValueConverter> converter(
216      content::V8ValueConverter::create());
217
218  base::DictionaryValue* filter_dict = NULL;
219  base::Value* filter_value =
220      converter->FromV8Value(args[1]->ToObject(), context()->v8_context());
221  if (!filter_value) {
222    args.GetReturnValue().Set(static_cast<int32_t>(-1));
223    return;
224  }
225  if (!filter_value->GetAsDictionary(&filter_dict)) {
226    delete filter_value;
227    args.GetReturnValue().Set(static_cast<int32_t>(-1));
228    return;
229  }
230
231  filter.reset(filter_dict);
232  EventFilter& event_filter = g_event_filter.Get();
233  int id =
234      event_filter.AddEventMatcher(event_name, ParseEventMatcher(filter.get()));
235
236  // Only send IPCs the first time a filter gets added.
237  if (AddFilter(event_name, extension_id, filter.get())) {
238    bool lazy = IsLazyBackgroundPage(context()->GetRenderView(),
239                                     context()->extension());
240    content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener(
241        extension_id, event_name, *filter, lazy));
242  }
243
244  args.GetReturnValue().Set(static_cast<int32_t>(id));
245}
246
247void EventBindings::DetachFilteredEvent(
248    const v8::FunctionCallbackInfo<v8::Value>& args) {
249  CHECK_EQ(2, args.Length());
250  CHECK(args[0]->IsInt32());
251  CHECK(args[1]->IsBoolean());
252  bool is_manual = args[1]->BooleanValue();
253
254  std::string extension_id = context()->GetExtensionID();
255
256  int matcher_id = args[0]->Int32Value();
257  EventFilter& event_filter = g_event_filter.Get();
258  EventMatcher* event_matcher = event_filter.GetEventMatcher(matcher_id);
259
260  const std::string& event_name = event_filter.GetEventName(matcher_id);
261
262  // Only send IPCs the last time a filter gets removed.
263  if (RemoveFilter(event_name, extension_id, event_matcher->value())) {
264    bool lazy = is_manual && IsLazyBackgroundPage(context()->GetRenderView(),
265                                                  context()->extension());
266    content::RenderThread::Get()->Send(
267        new ExtensionHostMsg_RemoveFilteredListener(
268            extension_id, event_name, *event_matcher->value(), lazy));
269  }
270
271  event_filter.RemoveEventMatcher(matcher_id);
272}
273
274void EventBindings::MatchAgainstEventFilter(
275    const v8::FunctionCallbackInfo<v8::Value>& args) {
276  v8::Isolate* isolate = args.GetIsolate();
277  typedef std::set<EventFilter::MatcherID> MatcherIDs;
278  EventFilter& event_filter = g_event_filter.Get();
279  std::string event_name = *v8::String::Utf8Value(args[0]->ToString());
280  EventFilteringInfo info = ParseFromObject(args[1]->ToObject(), isolate);
281  // Only match events routed to this context's RenderView or ones that don't
282  // have a routingId in their filter.
283  MatcherIDs matched_event_filters = event_filter.MatchEvent(
284      event_name, info, context()->GetRenderView()->GetRoutingID());
285  v8::Handle<v8::Array> array(
286      v8::Array::New(isolate, matched_event_filters.size()));
287  int i = 0;
288  for (MatcherIDs::iterator it = matched_event_filters.begin();
289       it != matched_event_filters.end();
290       ++it) {
291    array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it));
292  }
293  args.GetReturnValue().Set(array);
294}
295
296scoped_ptr<EventMatcher> EventBindings::ParseEventMatcher(
297    base::DictionaryValue* filter_dict) {
298  return scoped_ptr<EventMatcher>(new EventMatcher(
299      scoped_ptr<base::DictionaryValue>(filter_dict->DeepCopy()),
300      context()->GetRenderView()->GetRoutingID()));
301}
302
303}  // namespace extensions
304