Implementation of leveldb-backed PrefStore.
[chromium-blink-merge.git] / extensions / renderer / messaging_bindings.cc
blobd442681479ebe64a7fd4970795caa7ef1fe2d70e
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.
5 #include "extensions/renderer/messaging_bindings.h"
7 #include <map>
8 #include <string>
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/lazy_instance.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/values.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/api/messaging/message.h"
20 #include "extensions/common/extension_messages.h"
21 #include "extensions/common/manifest_handlers/externally_connectable.h"
22 #include "extensions/renderer/dispatcher.h"
23 #include "extensions/renderer/event_bindings.h"
24 #include "extensions/renderer/object_backed_native_handler.h"
25 #include "extensions/renderer/scoped_persistent.h"
26 #include "extensions/renderer/script_context.h"
27 #include "extensions/renderer/script_context_set.h"
28 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
29 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
30 #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h"
31 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
32 #include "v8/include/v8.h"
34 // Message passing API example (in a content script):
35 // var extension =
36 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
37 // var port = runtime.connect();
38 // port.postMessage('Can you hear me now?');
39 // port.onmessage.addListener(function(msg, port) {
40 // alert('response=' + msg);
41 // port.postMessage('I got your reponse');
42 // });
44 using content::RenderThread;
45 using content::V8ValueConverter;
47 namespace extensions {
49 namespace {
51 struct ExtensionData {
52 struct PortData {
53 int ref_count; // how many contexts have a handle to this port
54 PortData() : ref_count(0) {}
56 std::map<int, PortData> ports; // port ID -> data
59 base::LazyInstance<ExtensionData> g_extension_data = LAZY_INSTANCE_INITIALIZER;
61 bool HasPortData(int port_id) {
62 return g_extension_data.Get().ports.find(port_id) !=
63 g_extension_data.Get().ports.end();
66 ExtensionData::PortData& GetPortData(int port_id) {
67 return g_extension_data.Get().ports[port_id];
70 void ClearPortData(int port_id) {
71 g_extension_data.Get().ports.erase(port_id);
74 const char kPortClosedError[] = "Attempting to use a disconnected port object";
75 const char kReceivingEndDoesntExistError[] =
76 "Could not establish connection. Receiving end does not exist.";
78 class ExtensionImpl : public ObjectBackedNativeHandler {
79 public:
80 ExtensionImpl(Dispatcher* dispatcher, ScriptContext* context)
81 : ObjectBackedNativeHandler(context), dispatcher_(dispatcher) {
82 RouteFunction(
83 "CloseChannel",
84 base::Bind(&ExtensionImpl::CloseChannel, base::Unretained(this)));
85 RouteFunction(
86 "PortAddRef",
87 base::Bind(&ExtensionImpl::PortAddRef, base::Unretained(this)));
88 RouteFunction(
89 "PortRelease",
90 base::Bind(&ExtensionImpl::PortRelease, base::Unretained(this)));
91 RouteFunction(
92 "PostMessage",
93 base::Bind(&ExtensionImpl::PostMessage, base::Unretained(this)));
94 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
95 RouteFunction("BindToGC",
96 base::Bind(&ExtensionImpl::BindToGC, base::Unretained(this)));
99 virtual ~ExtensionImpl() {}
101 private:
102 void ClearPortDataAndNotifyDispatcher(int port_id) {
103 ClearPortData(port_id);
104 dispatcher_->ClearPortData(port_id);
107 // Sends a message along the given channel.
108 void PostMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
109 content::RenderView* renderview = context()->GetRenderView();
110 if (!renderview)
111 return;
113 // Arguments are (int32 port_id, string message).
114 CHECK(args.Length() == 2 && args[0]->IsInt32() && args[1]->IsString());
116 int port_id = args[0]->Int32Value();
117 if (!HasPortData(port_id)) {
118 args.GetIsolate()->ThrowException(v8::Exception::Error(
119 v8::String::NewFromUtf8(args.GetIsolate(), kPortClosedError)));
120 return;
123 renderview->Send(new ExtensionHostMsg_PostMessage(
124 renderview->GetRoutingID(), port_id,
125 Message(*v8::String::Utf8Value(args[1]),
126 blink::WebUserGestureIndicator::isProcessingUserGesture())));
129 // Forcefully disconnects a port.
130 void CloseChannel(const v8::FunctionCallbackInfo<v8::Value>& args) {
131 // Arguments are (int32 port_id, boolean notify_browser).
132 CHECK_EQ(2, args.Length());
133 CHECK(args[0]->IsInt32());
134 CHECK(args[1]->IsBoolean());
136 int port_id = args[0]->Int32Value();
137 if (!HasPortData(port_id))
138 return;
140 // Send via the RenderThread because the RenderView might be closing.
141 bool notify_browser = args[1]->BooleanValue();
142 if (notify_browser) {
143 content::RenderThread::Get()->Send(
144 new ExtensionHostMsg_CloseChannel(port_id, std::string()));
147 ClearPortDataAndNotifyDispatcher(port_id);
150 // A new port has been created for a context. This occurs both when script
151 // opens a connection, and when a connection is opened to this script.
152 void PortAddRef(const v8::FunctionCallbackInfo<v8::Value>& args) {
153 // Arguments are (int32 port_id).
154 CHECK_EQ(1, args.Length());
155 CHECK(args[0]->IsInt32());
157 int port_id = args[0]->Int32Value();
158 ++GetPortData(port_id).ref_count;
161 // The frame a port lived in has been destroyed. When there are no more
162 // frames with a reference to a given port, we will disconnect it and notify
163 // the other end of the channel.
164 void PortRelease(const v8::FunctionCallbackInfo<v8::Value>& args) {
165 // Arguments are (int32 port_id).
166 CHECK_EQ(1, args.Length());
167 CHECK(args[0]->IsInt32());
169 int port_id = args[0]->Int32Value();
170 if (HasPortData(port_id) && --GetPortData(port_id).ref_count == 0) {
171 // Send via the RenderThread because the RenderView might be closing.
172 content::RenderThread::Get()->Send(
173 new ExtensionHostMsg_CloseChannel(port_id, std::string()));
174 ClearPortDataAndNotifyDispatcher(port_id);
178 // Holds a |callback| to run sometime after |object| is GC'ed. |callback| will
179 // not be executed re-entrantly to avoid running JS in an unexpected state.
180 class GCCallback {
181 public:
182 static void Bind(v8::Handle<v8::Object> object,
183 v8::Handle<v8::Function> callback,
184 v8::Isolate* isolate) {
185 GCCallback* cb = new GCCallback(object, callback, isolate);
186 cb->object_.SetWeak(cb, NearDeathCallback);
189 private:
190 static void NearDeathCallback(
191 const v8::WeakCallbackData<v8::Object, GCCallback>& data) {
192 // v8 says we need to explicitly reset weak handles from their callbacks.
193 // It's not implicit as one might expect.
194 data.GetParameter()->object_.reset();
195 base::MessageLoop::current()->PostTask(
196 FROM_HERE,
197 base::Bind(&GCCallback::RunCallback,
198 base::Owned(data.GetParameter())));
201 GCCallback(v8::Handle<v8::Object> object,
202 v8::Handle<v8::Function> callback,
203 v8::Isolate* isolate)
204 : object_(object), callback_(callback), isolate_(isolate) {}
206 void RunCallback() {
207 v8::HandleScope handle_scope(isolate_);
208 v8::Handle<v8::Function> callback = callback_.NewHandle(isolate_);
209 v8::Handle<v8::Context> context = callback->CreationContext();
210 if (context.IsEmpty())
211 return;
212 v8::Context::Scope context_scope(context);
213 blink::WebScopedMicrotaskSuppression suppression;
214 callback->Call(context->Global(), 0, NULL);
217 ScopedPersistent<v8::Object> object_;
218 ScopedPersistent<v8::Function> callback_;
219 v8::Isolate* isolate_;
221 DISALLOW_COPY_AND_ASSIGN(GCCallback);
224 // void BindToGC(object, callback)
226 // Binds |callback| to be invoked *sometime after* |object| is garbage
227 // collected. We don't call the method re-entrantly so as to avoid executing
228 // JS in some bizarro undefined mid-GC state.
229 void BindToGC(const v8::FunctionCallbackInfo<v8::Value>& args) {
230 CHECK(args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction());
231 GCCallback::Bind(args[0].As<v8::Object>(),
232 args[1].As<v8::Function>(),
233 args.GetIsolate());
236 // Dispatcher handle. Not owned.
237 Dispatcher* dispatcher_;
240 } // namespace
242 ObjectBackedNativeHandler* MessagingBindings::Get(Dispatcher* dispatcher,
243 ScriptContext* context) {
244 return new ExtensionImpl(dispatcher, context);
247 // static
248 void MessagingBindings::DispatchOnConnect(
249 const ScriptContextSet::ContextSet& contexts,
250 int target_port_id,
251 const std::string& channel_name,
252 const base::DictionaryValue& source_tab,
253 const std::string& source_extension_id,
254 const std::string& target_extension_id,
255 const GURL& source_url,
256 const std::string& tls_channel_id,
257 content::RenderView* restrict_to_render_view) {
258 v8::Isolate* isolate = v8::Isolate::GetCurrent();
259 v8::HandleScope handle_scope(isolate);
261 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
263 bool port_created = false;
264 std::string source_url_spec = source_url.spec();
266 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
267 for (ScriptContextSet::ContextSet::const_iterator it = contexts.begin();
268 it != contexts.end();
269 ++it) {
270 if (restrict_to_render_view &&
271 restrict_to_render_view != (*it)->GetRenderView()) {
272 continue;
275 // TODO(kalman): remove when ContextSet::ForEach is available.
276 if ((*it)->v8_context().IsEmpty())
277 continue;
279 v8::Handle<v8::Value> tab = v8::Null(isolate);
280 v8::Handle<v8::Value> tls_channel_id_value = v8::Undefined(isolate);
281 const Extension* extension = (*it)->extension();
282 if (extension) {
283 if (!source_tab.empty() && !extension->is_platform_app())
284 tab = converter->ToV8Value(&source_tab, (*it)->v8_context());
286 ExternallyConnectableInfo* externally_connectable =
287 ExternallyConnectableInfo::Get(extension);
288 if (externally_connectable &&
289 externally_connectable->accepts_tls_channel_id) {
290 tls_channel_id_value =
291 v8::String::NewFromUtf8(isolate,
292 tls_channel_id.c_str(),
293 v8::String::kNormalString,
294 tls_channel_id.size());
298 v8::Handle<v8::Value> arguments[] = {
299 // portId
300 v8::Integer::New(isolate, target_port_id),
301 // channelName
302 v8::String::NewFromUtf8(isolate,
303 channel_name.c_str(),
304 v8::String::kNormalString,
305 channel_name.size()),
306 // sourceTab
307 tab,
308 // sourceExtensionId
309 v8::String::NewFromUtf8(isolate,
310 source_extension_id.c_str(),
311 v8::String::kNormalString,
312 source_extension_id.size()),
313 // targetExtensionId
314 v8::String::NewFromUtf8(isolate,
315 target_extension_id.c_str(),
316 v8::String::kNormalString,
317 target_extension_id.size()),
318 // sourceUrl
319 v8::String::NewFromUtf8(isolate,
320 source_url_spec.c_str(),
321 v8::String::kNormalString,
322 source_url_spec.size()),
323 // tlsChannelId
324 tls_channel_id_value,
327 v8::Handle<v8::Value> retval = (*it)->module_system()->CallModuleMethod(
328 "messaging", "dispatchOnConnect", arraysize(arguments), arguments);
330 if (retval.IsEmpty()) {
331 LOG(ERROR) << "Empty return value from dispatchOnConnect.";
332 continue;
335 CHECK(retval->IsBoolean());
336 port_created |= retval->BooleanValue();
339 // If we didn't create a port, notify the other end of the channel (treat it
340 // as a disconnect).
341 if (!port_created) {
342 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
343 target_port_id, kReceivingEndDoesntExistError));
347 // static
348 void MessagingBindings::DeliverMessage(
349 const ScriptContextSet::ContextSet& contexts,
350 int target_port_id,
351 const Message& message,
352 content::RenderView* restrict_to_render_view) {
353 scoped_ptr<blink::WebScopedUserGesture> web_user_gesture;
354 scoped_ptr<blink::WebScopedWindowFocusAllowedIndicator> allow_window_focus;
355 if (message.user_gesture) {
356 web_user_gesture.reset(new blink::WebScopedUserGesture);
357 allow_window_focus.reset(new blink::WebScopedWindowFocusAllowedIndicator);
360 v8::Isolate* isolate = v8::Isolate::GetCurrent();
361 v8::HandleScope handle_scope(isolate);
363 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
364 for (ScriptContextSet::ContextSet::const_iterator it = contexts.begin();
365 it != contexts.end();
366 ++it) {
367 if (restrict_to_render_view &&
368 restrict_to_render_view != (*it)->GetRenderView()) {
369 continue;
372 // TODO(kalman): remove when ContextSet::ForEach is available.
373 if ((*it)->v8_context().IsEmpty())
374 continue;
376 // Check to see whether the context has this port before bothering to create
377 // the message.
378 v8::Handle<v8::Value> port_id_handle =
379 v8::Integer::New(isolate, target_port_id);
380 v8::Handle<v8::Value> has_port = (*it)->module_system()->CallModuleMethod(
381 "messaging", "hasPort", 1, &port_id_handle);
383 CHECK(!has_port.IsEmpty());
384 if (!has_port->BooleanValue())
385 continue;
387 std::vector<v8::Handle<v8::Value> > arguments;
388 arguments.push_back(v8::String::NewFromUtf8(isolate,
389 message.data.c_str(),
390 v8::String::kNormalString,
391 message.data.size()));
392 arguments.push_back(port_id_handle);
393 (*it)->module_system()->CallModuleMethod(
394 "messaging", "dispatchOnMessage", &arguments);
398 // static
399 void MessagingBindings::DispatchOnDisconnect(
400 const ScriptContextSet::ContextSet& contexts,
401 int port_id,
402 const std::string& error_message,
403 content::RenderView* restrict_to_render_view) {
404 v8::Isolate* isolate = v8::Isolate::GetCurrent();
405 v8::HandleScope handle_scope(isolate);
407 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
408 for (ScriptContextSet::ContextSet::const_iterator it = contexts.begin();
409 it != contexts.end();
410 ++it) {
411 if (restrict_to_render_view &&
412 restrict_to_render_view != (*it)->GetRenderView()) {
413 continue;
416 // TODO(kalman): remove when ContextSet::ForEach is available.
417 if ((*it)->v8_context().IsEmpty())
418 continue;
420 std::vector<v8::Handle<v8::Value> > arguments;
421 arguments.push_back(v8::Integer::New(isolate, port_id));
422 if (!error_message.empty()) {
423 arguments.push_back(
424 v8::String::NewFromUtf8(isolate, error_message.c_str()));
425 } else {
426 arguments.push_back(v8::Null(isolate));
428 (*it)->module_system()->CallModuleMethod(
429 "messaging", "dispatchOnDisconnect", &arguments);
433 } // namespace extensions