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"
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 "third_party/WebKit/public/web/WebUserGestureToken.h"
33 #include "v8/include/v8.h"
35 // Message passing API example (in a content script):
37 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
38 // var port = runtime.connect();
39 // port.postMessage('Can you hear me now?');
40 // port.onmessage.addListener(function(msg, port) {
41 // alert('response=' + msg);
42 // port.postMessage('I got your reponse');
45 using content::RenderThread
;
46 using content::V8ValueConverter
;
48 namespace extensions
{
52 struct ExtensionData
{
54 int ref_count
; // how many contexts have a handle to this port
55 PortData() : ref_count(0) {}
57 std::map
<int, PortData
> ports
; // port ID -> data
60 base::LazyInstance
<ExtensionData
> g_extension_data
= LAZY_INSTANCE_INITIALIZER
;
62 bool HasPortData(int port_id
) {
63 return g_extension_data
.Get().ports
.find(port_id
) !=
64 g_extension_data
.Get().ports
.end();
67 ExtensionData::PortData
& GetPortData(int port_id
) {
68 return g_extension_data
.Get().ports
[port_id
];
71 void ClearPortData(int port_id
) {
72 g_extension_data
.Get().ports
.erase(port_id
);
75 const char kPortClosedError
[] = "Attempting to use a disconnected port object";
76 const char kReceivingEndDoesntExistError
[] =
77 "Could not establish connection. Receiving end does not exist.";
79 class ExtensionImpl
: public ObjectBackedNativeHandler
{
81 ExtensionImpl(Dispatcher
* dispatcher
, ScriptContext
* context
)
82 : ObjectBackedNativeHandler(context
), dispatcher_(dispatcher
) {
85 base::Bind(&ExtensionImpl::CloseChannel
, base::Unretained(this)));
88 base::Bind(&ExtensionImpl::PortAddRef
, base::Unretained(this)));
91 base::Bind(&ExtensionImpl::PortRelease
, base::Unretained(this)));
94 base::Bind(&ExtensionImpl::PostMessage
, base::Unretained(this)));
95 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
96 RouteFunction("BindToGC",
97 base::Bind(&ExtensionImpl::BindToGC
, base::Unretained(this)));
100 virtual ~ExtensionImpl() {}
103 void ClearPortDataAndNotifyDispatcher(int port_id
) {
104 ClearPortData(port_id
);
105 dispatcher_
->ClearPortData(port_id
);
108 bool ShouldForwardUserGesture() {
109 return blink::WebUserGestureIndicator::isProcessingUserGesture() &&
110 !blink::WebUserGestureIndicator::currentUserGestureToken()
114 // Sends a message along the given channel.
115 void PostMessage(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
116 content::RenderView
* renderview
= context()->GetRenderView();
120 // Arguments are (int32 port_id, string message).
121 CHECK(args
.Length() == 2 && args
[0]->IsInt32() && args
[1]->IsString());
123 int port_id
= args
[0]->Int32Value();
124 if (!HasPortData(port_id
)) {
125 args
.GetIsolate()->ThrowException(v8::Exception::Error(
126 v8::String::NewFromUtf8(args
.GetIsolate(), kPortClosedError
)));
130 renderview
->Send(new ExtensionHostMsg_PostMessage(
131 renderview
->GetRoutingID(),
133 Message(*v8::String::Utf8Value(args
[1]), ShouldForwardUserGesture())));
136 // Forcefully disconnects a port.
137 void CloseChannel(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
138 // Arguments are (int32 port_id, boolean notify_browser).
139 CHECK_EQ(2, args
.Length());
140 CHECK(args
[0]->IsInt32());
141 CHECK(args
[1]->IsBoolean());
143 int port_id
= args
[0]->Int32Value();
144 if (!HasPortData(port_id
))
147 // Send via the RenderThread because the RenderView might be closing.
148 bool notify_browser
= args
[1]->BooleanValue();
149 if (notify_browser
) {
150 content::RenderThread::Get()->Send(
151 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
154 ClearPortDataAndNotifyDispatcher(port_id
);
157 // A new port has been created for a context. This occurs both when script
158 // opens a connection, and when a connection is opened to this script.
159 void PortAddRef(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
160 // Arguments are (int32 port_id).
161 CHECK_EQ(1, args
.Length());
162 CHECK(args
[0]->IsInt32());
164 int port_id
= args
[0]->Int32Value();
165 ++GetPortData(port_id
).ref_count
;
168 // The frame a port lived in has been destroyed. When there are no more
169 // frames with a reference to a given port, we will disconnect it and notify
170 // the other end of the channel.
171 void PortRelease(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
172 // Arguments are (int32 port_id).
173 CHECK_EQ(1, args
.Length());
174 CHECK(args
[0]->IsInt32());
176 int port_id
= args
[0]->Int32Value();
177 if (HasPortData(port_id
) && --GetPortData(port_id
).ref_count
== 0) {
178 // Send via the RenderThread because the RenderView might be closing.
179 content::RenderThread::Get()->Send(
180 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
181 ClearPortDataAndNotifyDispatcher(port_id
);
185 // Holds a |callback| to run sometime after |object| is GC'ed. |callback| will
186 // not be executed re-entrantly to avoid running JS in an unexpected state.
189 static void Bind(v8::Handle
<v8::Object
> object
,
190 v8::Handle
<v8::Function
> callback
,
191 v8::Isolate
* isolate
) {
192 GCCallback
* cb
= new GCCallback(object
, callback
, isolate
);
193 cb
->object_
.SetWeak(cb
, NearDeathCallback
);
197 static void NearDeathCallback(
198 const v8::WeakCallbackData
<v8::Object
, GCCallback
>& data
) {
199 // v8 says we need to explicitly reset weak handles from their callbacks.
200 // It's not implicit as one might expect.
201 data
.GetParameter()->object_
.reset();
202 base::MessageLoop::current()->PostTask(
204 base::Bind(&GCCallback::RunCallback
,
205 base::Owned(data
.GetParameter())));
208 GCCallback(v8::Handle
<v8::Object
> object
,
209 v8::Handle
<v8::Function
> callback
,
210 v8::Isolate
* isolate
)
211 : object_(object
), callback_(callback
), isolate_(isolate
) {}
214 v8::HandleScope
handle_scope(isolate_
);
215 v8::Handle
<v8::Function
> callback
= callback_
.NewHandle(isolate_
);
216 v8::Handle
<v8::Context
> context
= callback
->CreationContext();
217 if (context
.IsEmpty())
219 v8::Context::Scope
context_scope(context
);
220 blink::WebScopedMicrotaskSuppression suppression
;
221 callback
->Call(context
->Global(), 0, NULL
);
224 ScopedPersistent
<v8::Object
> object_
;
225 ScopedPersistent
<v8::Function
> callback_
;
226 v8::Isolate
* isolate_
;
228 DISALLOW_COPY_AND_ASSIGN(GCCallback
);
231 // void BindToGC(object, callback)
233 // Binds |callback| to be invoked *sometime after* |object| is garbage
234 // collected. We don't call the method re-entrantly so as to avoid executing
235 // JS in some bizarro undefined mid-GC state.
236 void BindToGC(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
237 CHECK(args
.Length() == 2 && args
[0]->IsObject() && args
[1]->IsFunction());
238 GCCallback::Bind(args
[0].As
<v8::Object
>(),
239 args
[1].As
<v8::Function
>(),
243 // Dispatcher handle. Not owned.
244 Dispatcher
* dispatcher_
;
249 ObjectBackedNativeHandler
* MessagingBindings::Get(Dispatcher
* dispatcher
,
250 ScriptContext
* context
) {
251 return new ExtensionImpl(dispatcher
, context
);
255 void MessagingBindings::DispatchOnConnect(
256 const ScriptContextSet::ContextSet
& contexts
,
258 const std::string
& channel_name
,
259 const base::DictionaryValue
& source_tab
,
260 const std::string
& source_extension_id
,
261 const std::string
& target_extension_id
,
262 const GURL
& source_url
,
263 const std::string
& tls_channel_id
,
264 content::RenderView
* restrict_to_render_view
) {
265 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
266 v8::HandleScope
handle_scope(isolate
);
268 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
270 bool port_created
= false;
271 std::string source_url_spec
= source_url
.spec();
273 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
274 for (ScriptContextSet::ContextSet::const_iterator it
= contexts
.begin();
275 it
!= contexts
.end();
277 if (restrict_to_render_view
&&
278 restrict_to_render_view
!= (*it
)->GetRenderView()) {
282 // TODO(kalman): remove when ContextSet::ForEach is available.
283 if ((*it
)->v8_context().IsEmpty())
286 v8::Handle
<v8::Value
> tab
= v8::Null(isolate
);
287 v8::Handle
<v8::Value
> tls_channel_id_value
= v8::Undefined(isolate
);
288 const Extension
* extension
= (*it
)->extension();
290 if (!source_tab
.empty() && !extension
->is_platform_app())
291 tab
= converter
->ToV8Value(&source_tab
, (*it
)->v8_context());
293 ExternallyConnectableInfo
* externally_connectable
=
294 ExternallyConnectableInfo::Get(extension
);
295 if (externally_connectable
&&
296 externally_connectable
->accepts_tls_channel_id
) {
297 tls_channel_id_value
=
298 v8::String::NewFromUtf8(isolate
,
299 tls_channel_id
.c_str(),
300 v8::String::kNormalString
,
301 tls_channel_id
.size());
305 v8::Handle
<v8::Value
> arguments
[] = {
307 v8::Integer::New(isolate
, target_port_id
),
309 v8::String::NewFromUtf8(isolate
,
310 channel_name
.c_str(),
311 v8::String::kNormalString
,
312 channel_name
.size()),
316 v8::String::NewFromUtf8(isolate
,
317 source_extension_id
.c_str(),
318 v8::String::kNormalString
,
319 source_extension_id
.size()),
321 v8::String::NewFromUtf8(isolate
,
322 target_extension_id
.c_str(),
323 v8::String::kNormalString
,
324 target_extension_id
.size()),
326 v8::String::NewFromUtf8(isolate
,
327 source_url_spec
.c_str(),
328 v8::String::kNormalString
,
329 source_url_spec
.size()),
331 tls_channel_id_value
,
334 v8::Handle
<v8::Value
> retval
= (*it
)->module_system()->CallModuleMethod(
335 "messaging", "dispatchOnConnect", arraysize(arguments
), arguments
);
337 if (retval
.IsEmpty()) {
338 LOG(ERROR
) << "Empty return value from dispatchOnConnect.";
342 CHECK(retval
->IsBoolean());
343 port_created
|= retval
->BooleanValue();
346 // If we didn't create a port, notify the other end of the channel (treat it
349 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
350 target_port_id
, kReceivingEndDoesntExistError
));
355 void MessagingBindings::DeliverMessage(
356 const ScriptContextSet::ContextSet
& contexts
,
358 const Message
& message
,
359 content::RenderView
* restrict_to_render_view
) {
360 scoped_ptr
<blink::WebScopedUserGesture
> web_user_gesture
;
361 scoped_ptr
<blink::WebScopedWindowFocusAllowedIndicator
> allow_window_focus
;
362 if (message
.user_gesture
) {
363 web_user_gesture
.reset(new blink::WebScopedUserGesture
);
364 blink::WebUserGestureIndicator::currentUserGestureToken().setForwarded();
365 allow_window_focus
.reset(new blink::WebScopedWindowFocusAllowedIndicator
);
368 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
369 v8::HandleScope
handle_scope(isolate
);
371 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
372 for (ScriptContextSet::ContextSet::const_iterator it
= contexts
.begin();
373 it
!= contexts
.end();
375 if (restrict_to_render_view
&&
376 restrict_to_render_view
!= (*it
)->GetRenderView()) {
380 // TODO(kalman): remove when ContextSet::ForEach is available.
381 if ((*it
)->v8_context().IsEmpty())
384 // Check to see whether the context has this port before bothering to create
386 v8::Handle
<v8::Value
> port_id_handle
=
387 v8::Integer::New(isolate
, target_port_id
);
388 v8::Handle
<v8::Value
> has_port
= (*it
)->module_system()->CallModuleMethod(
389 "messaging", "hasPort", 1, &port_id_handle
);
391 CHECK(!has_port
.IsEmpty());
392 if (!has_port
->BooleanValue())
395 std::vector
<v8::Handle
<v8::Value
> > arguments
;
396 arguments
.push_back(v8::String::NewFromUtf8(isolate
,
397 message
.data
.c_str(),
398 v8::String::kNormalString
,
399 message
.data
.size()));
400 arguments
.push_back(port_id_handle
);
401 (*it
)->module_system()->CallModuleMethod(
402 "messaging", "dispatchOnMessage", &arguments
);
407 void MessagingBindings::DispatchOnDisconnect(
408 const ScriptContextSet::ContextSet
& contexts
,
410 const std::string
& error_message
,
411 content::RenderView
* restrict_to_render_view
) {
412 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
413 v8::HandleScope
handle_scope(isolate
);
415 // TODO(kalman): pass in the full ScriptContextSet; call ForEach.
416 for (ScriptContextSet::ContextSet::const_iterator it
= contexts
.begin();
417 it
!= contexts
.end();
419 if (restrict_to_render_view
&&
420 restrict_to_render_view
!= (*it
)->GetRenderView()) {
424 // TODO(kalman): remove when ContextSet::ForEach is available.
425 if ((*it
)->v8_context().IsEmpty())
428 std::vector
<v8::Handle
<v8::Value
> > arguments
;
429 arguments
.push_back(v8::Integer::New(isolate
, port_id
));
430 if (!error_message
.empty()) {
432 v8::String::NewFromUtf8(isolate
, error_message
.c_str()));
434 arguments
.push_back(v8::Null(isolate
));
436 (*it
)->module_system()->CallModuleMethod(
437 "messaging", "dispatchOnDisconnect", &arguments
);
441 } // namespace extensions