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 30 namespace extensions { 31 32 namespace { 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. 37 typedef std::map<std::string, int> EventListenerCounts; 38 39 // A map of extension IDs to listener counts for that extension. 40 base::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. 47 typedef std::map<std::string, linked_ptr<ValueCounter> > 48 FilteredEventListenerCounts; 49 50 // A map of extension IDs to filtered listener counts for that extension. 51 base::LazyInstance<std::map<std::string, FilteredEventListenerCounts> > 52 g_filtered_listener_counts = LAZY_INSTANCE_INITIALIZER; 53 54 base::LazyInstance<EventFilter> g_event_filter = LAZY_INSTANCE_INITIALIZER; 55 56 bool 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 65 EventFilteringInfo 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. 90 bool 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. 105 bool 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 118 EventBindings::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 137 EventBindings::~EventBindings() {} 138 139 // Attach an event name to an object. 140 void 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( 154 new ExtensionHostMsg_AddListener(extension_id, 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 167 void 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( 181 new ExtensionHostMsg_RemoveListener(extension_id, 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. 200 void 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 if (extension_id.empty()) { 214 args.GetReturnValue().Set(static_cast<int32_t>(-1)); 215 return; 216 } 217 218 scoped_ptr<base::DictionaryValue> filter; 219 scoped_ptr<content::V8ValueConverter> converter( 220 content::V8ValueConverter::create()); 221 222 base::DictionaryValue* filter_dict = NULL; 223 base::Value* filter_value = 224 converter->FromV8Value(args[1]->ToObject(), context()->v8_context()); 225 if (!filter_value) { 226 args.GetReturnValue().Set(static_cast<int32_t>(-1)); 227 return; 228 } 229 if (!filter_value->GetAsDictionary(&filter_dict)) { 230 delete filter_value; 231 args.GetReturnValue().Set(static_cast<int32_t>(-1)); 232 return; 233 } 234 235 filter.reset(filter_dict); 236 EventFilter& event_filter = g_event_filter.Get(); 237 int id = 238 event_filter.AddEventMatcher(event_name, ParseEventMatcher(filter.get())); 239 240 // Only send IPCs the first time a filter gets added. 241 if (AddFilter(event_name, extension_id, filter.get())) { 242 bool lazy = IsLazyBackgroundPage(context()->GetRenderView(), 243 context()->extension()); 244 content::RenderThread::Get()->Send(new ExtensionHostMsg_AddFilteredListener( 245 extension_id, event_name, *filter, lazy)); 246 } 247 248 args.GetReturnValue().Set(static_cast<int32_t>(id)); 249 } 250 251 void EventBindings::DetachFilteredEvent( 252 const v8::FunctionCallbackInfo<v8::Value>& args) { 253 CHECK_EQ(2, args.Length()); 254 CHECK(args[0]->IsInt32()); 255 CHECK(args[1]->IsBoolean()); 256 bool is_manual = args[1]->BooleanValue(); 257 258 std::string extension_id = context()->GetExtensionID(); 259 if (extension_id.empty()) 260 return; 261 262 int matcher_id = args[0]->Int32Value(); 263 EventFilter& event_filter = g_event_filter.Get(); 264 EventMatcher* event_matcher = event_filter.GetEventMatcher(matcher_id); 265 266 const std::string& event_name = event_filter.GetEventName(matcher_id); 267 268 // Only send IPCs the last time a filter gets removed. 269 if (RemoveFilter(event_name, extension_id, event_matcher->value())) { 270 bool lazy = is_manual && IsLazyBackgroundPage(context()->GetRenderView(), 271 context()->extension()); 272 content::RenderThread::Get()->Send( 273 new ExtensionHostMsg_RemoveFilteredListener( 274 extension_id, event_name, *event_matcher->value(), lazy)); 275 } 276 277 event_filter.RemoveEventMatcher(matcher_id); 278 } 279 280 void EventBindings::MatchAgainstEventFilter( 281 const v8::FunctionCallbackInfo<v8::Value>& args) { 282 v8::Isolate* isolate = args.GetIsolate(); 283 typedef std::set<EventFilter::MatcherID> MatcherIDs; 284 EventFilter& event_filter = g_event_filter.Get(); 285 std::string event_name = *v8::String::Utf8Value(args[0]->ToString()); 286 EventFilteringInfo info = ParseFromObject(args[1]->ToObject(), isolate); 287 // Only match events routed to this context's RenderView or ones that don't 288 // have a routingId in their filter. 289 MatcherIDs matched_event_filters = event_filter.MatchEvent( 290 event_name, info, context()->GetRenderView()->GetRoutingID()); 291 v8::Handle<v8::Array> array( 292 v8::Array::New(isolate, matched_event_filters.size())); 293 int i = 0; 294 for (MatcherIDs::iterator it = matched_event_filters.begin(); 295 it != matched_event_filters.end(); 296 ++it) { 297 array->Set(v8::Integer::New(isolate, i++), v8::Integer::New(isolate, *it)); 298 } 299 args.GetReturnValue().Set(array); 300 } 301 302 scoped_ptr<EventMatcher> EventBindings::ParseEventMatcher( 303 base::DictionaryValue* filter_dict) { 304 return scoped_ptr<EventMatcher>(new EventMatcher( 305 scoped_ptr<base::DictionaryValue>(filter_dict->DeepCopy()), 306 context()->GetRenderView()->GetRoutingID())); 307 } 308 309 } // namespace extensions 310