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/child/v8_value_converter.h"
17 #include "content/public/common/child_process_host.h"
18 #include "content/public/renderer/render_frame.h"
19 #include "content/public/renderer/render_thread.h"
20 #include "extensions/common/api/messaging/message.h"
21 #include "extensions/common/extension_messages.h"
22 #include "extensions/common/guest_view/guest_view_constants.h"
23 #include "extensions/common/manifest_handlers/externally_connectable.h"
24 #include "extensions/renderer/dispatcher.h"
25 #include "extensions/renderer/event_bindings.h"
26 #include "extensions/renderer/object_backed_native_handler.h"
27 #include "extensions/renderer/script_context.h"
28 #include "extensions/renderer/script_context_set.h"
29 #include "third_party/WebKit/public/web/WebDocument.h"
30 #include "third_party/WebKit/public/web/WebLocalFrame.h"
31 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
32 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
33 #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h"
34 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
35 #include "v8/include/v8.h"
37 // Message passing API example (in a content script):
39 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
40 // var port = runtime.connect();
41 // port.postMessage('Can you hear me now?');
42 // port.onmessage.addListener(function(msg, port) {
43 // alert('response=' + msg);
44 // port.postMessage('I got your reponse');
47 using content::RenderThread
;
48 using content::V8ValueConverter
;
50 namespace extensions
{
54 struct ExtensionData
{
56 int ref_count
; // how many contexts have a handle to this port
57 PortData() : ref_count(0) {}
59 std::map
<int, PortData
> ports
; // port ID -> data
62 base::LazyInstance
<ExtensionData
> g_extension_data
= LAZY_INSTANCE_INITIALIZER
;
64 bool HasPortData(int port_id
) {
65 return g_extension_data
.Get().ports
.find(port_id
) !=
66 g_extension_data
.Get().ports
.end();
69 ExtensionData::PortData
& GetPortData(int port_id
) {
70 return g_extension_data
.Get().ports
[port_id
];
73 void ClearPortData(int port_id
) {
74 g_extension_data
.Get().ports
.erase(port_id
);
77 const char kPortClosedError
[] = "Attempting to use a disconnected port object";
78 const char kReceivingEndDoesntExistError
[] =
79 "Could not establish connection. Receiving end does not exist.";
81 class ExtensionImpl
: public ObjectBackedNativeHandler
{
83 ExtensionImpl(Dispatcher
* dispatcher
, ScriptContext
* context
)
84 : ObjectBackedNativeHandler(context
), dispatcher_(dispatcher
) {
87 base::Bind(&ExtensionImpl::CloseChannel
, base::Unretained(this)));
90 base::Bind(&ExtensionImpl::PortAddRef
, base::Unretained(this)));
93 base::Bind(&ExtensionImpl::PortRelease
, base::Unretained(this)));
96 base::Bind(&ExtensionImpl::PostMessage
, base::Unretained(this)));
97 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
98 RouteFunction("BindToGC",
99 base::Bind(&ExtensionImpl::BindToGC
, base::Unretained(this)));
102 ~ExtensionImpl() override
{}
105 void ClearPortDataAndNotifyDispatcher(int port_id
) {
106 ClearPortData(port_id
);
107 dispatcher_
->ClearPortData(port_id
);
110 // Sends a message along the given channel.
111 void PostMessage(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
112 content::RenderFrame
* renderframe
= context()->GetRenderFrame();
116 // Arguments are (int32 port_id, string message).
117 CHECK(args
.Length() == 2 && args
[0]->IsInt32() && args
[1]->IsString());
119 int port_id
= args
[0]->Int32Value();
120 if (!HasPortData(port_id
)) {
121 args
.GetIsolate()->ThrowException(v8::Exception::Error(
122 v8::String::NewFromUtf8(args
.GetIsolate(), kPortClosedError
)));
126 renderframe
->Send(new ExtensionHostMsg_PostMessage(
127 renderframe
->GetRoutingID(), port_id
,
128 Message(*v8::String::Utf8Value(args
[1]),
129 blink::WebUserGestureIndicator::isProcessingUserGesture())));
132 // Forcefully disconnects a port.
133 void CloseChannel(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
134 // Arguments are (int32 port_id, boolean notify_browser).
135 CHECK_EQ(2, args
.Length());
136 CHECK(args
[0]->IsInt32());
137 CHECK(args
[1]->IsBoolean());
139 int port_id
= args
[0]->Int32Value();
140 if (!HasPortData(port_id
))
143 // Send via the RenderThread because the RenderFrame might be closing.
144 bool notify_browser
= args
[1]->BooleanValue();
145 if (notify_browser
) {
146 content::RenderThread::Get()->Send(
147 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
150 ClearPortDataAndNotifyDispatcher(port_id
);
153 // A new port has been created for a context. This occurs both when script
154 // opens a connection, and when a connection is opened to this script.
155 void PortAddRef(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
156 // Arguments are (int32 port_id).
157 CHECK_EQ(1, args
.Length());
158 CHECK(args
[0]->IsInt32());
160 int port_id
= args
[0]->Int32Value();
161 ++GetPortData(port_id
).ref_count
;
164 // The frame a port lived in has been destroyed. When there are no more
165 // frames with a reference to a given port, we will disconnect it and notify
166 // the other end of the channel.
167 void PortRelease(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
168 // Arguments are (int32 port_id).
169 CHECK_EQ(1, args
.Length());
170 CHECK(args
[0]->IsInt32());
172 int port_id
= args
[0]->Int32Value();
173 if (HasPortData(port_id
) && --GetPortData(port_id
).ref_count
== 0) {
174 // Send via the RenderThread because the RenderFrame might be closing.
175 content::RenderThread::Get()->Send(
176 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
177 ClearPortDataAndNotifyDispatcher(port_id
);
181 // Holds a |callback| to run sometime after |object| is GC'ed. |callback| will
182 // not be executed re-entrantly to avoid running JS in an unexpected state.
185 static void Bind(v8::Handle
<v8::Object
> object
,
186 v8::Handle
<v8::Function
> callback
,
187 v8::Isolate
* isolate
) {
188 GCCallback
* cb
= new GCCallback(object
, callback
, isolate
);
189 cb
->object_
.SetWeak(cb
, FirstWeakCallback
,
190 v8::WeakCallbackType::kParameter
);
194 static void FirstWeakCallback(
195 const v8::WeakCallbackInfo
<GCCallback
>& data
) {
196 // v8 says we need to explicitly reset weak handles from their callbacks.
197 // It's not implicit as one might expect.
198 data
.GetParameter()->object_
.Reset();
199 data
.SetSecondPassCallback(SecondWeakCallback
);
202 static void SecondWeakCallback(
203 const v8::WeakCallbackInfo
<GCCallback
>& data
) {
204 base::MessageLoop::current()->PostTask(
206 base::Bind(&GCCallback::RunCallback
,
207 base::Owned(data
.GetParameter())));
210 GCCallback(v8::Handle
<v8::Object
> object
,
211 v8::Handle
<v8::Function
> callback
,
212 v8::Isolate
* isolate
)
213 : object_(isolate
, object
),
214 callback_(isolate
, callback
),
218 v8::HandleScope
handle_scope(isolate_
);
219 v8::Handle
<v8::Function
> callback
=
220 v8::Local
<v8::Function
>::New(isolate_
, callback_
);
221 v8::Handle
<v8::Context
> context
= callback
->CreationContext();
222 if (context
.IsEmpty())
224 v8::Context::Scope
context_scope(context
);
225 blink::WebScopedMicrotaskSuppression suppression
;
226 callback
->Call(context
->Global(), 0, NULL
);
229 v8::Global
<v8::Object
> object_
;
230 v8::Global
<v8::Function
> callback_
;
231 v8::Isolate
* isolate_
;
233 DISALLOW_COPY_AND_ASSIGN(GCCallback
);
236 // void BindToGC(object, callback)
238 // Binds |callback| to be invoked *sometime after* |object| is garbage
239 // collected. We don't call the method re-entrantly so as to avoid executing
240 // JS in some bizarro undefined mid-GC state.
241 void BindToGC(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
242 CHECK(args
.Length() == 2 && args
[0]->IsObject() && args
[1]->IsFunction());
243 GCCallback::Bind(args
[0].As
<v8::Object
>(),
244 args
[1].As
<v8::Function
>(),
248 // Dispatcher handle. Not owned.
249 Dispatcher
* dispatcher_
;
252 void DispatchOnConnectToScriptContext(
254 const std::string
& channel_name
,
255 const ExtensionMsg_TabConnectionInfo
* source
,
256 const ExtensionMsg_ExternalConnectionInfo
& info
,
257 const std::string
& tls_channel_id
,
259 ScriptContext
* script_context
) {
260 // Only dispatch the events if this is the requested target frame (0 = main
261 // frame; positive = child frame).
262 content::RenderFrame
* renderframe
= script_context
->GetRenderFrame();
263 if (info
.target_frame_id
== 0 && renderframe
->GetWebFrame()->parent() != NULL
)
265 if (info
.target_frame_id
> 0 &&
266 renderframe
->GetRoutingID() != info
.target_frame_id
)
268 v8::Isolate
* isolate
= script_context
->isolate();
269 v8::HandleScope
handle_scope(isolate
);
271 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
273 const std::string
& source_url_spec
= info
.source_url
.spec();
274 std::string target_extension_id
= script_context
->GetExtensionID();
275 const Extension
* extension
= script_context
->extension();
277 v8::Handle
<v8::Value
> tab
= v8::Null(isolate
);
278 v8::Handle
<v8::Value
> tls_channel_id_value
= v8::Undefined(isolate
);
279 v8::Handle
<v8::Value
> guest_process_id
= v8::Undefined(isolate
);
282 if (!source
->tab
.empty() && !extension
->is_platform_app())
283 tab
= converter
->ToV8Value(&source
->tab
, script_context
->v8_context());
285 ExternallyConnectableInfo
* externally_connectable
=
286 ExternallyConnectableInfo::Get(extension
);
287 if (externally_connectable
&&
288 externally_connectable
->accepts_tls_channel_id
) {
289 tls_channel_id_value
= v8::String::NewFromUtf8(isolate
,
290 tls_channel_id
.c_str(),
291 v8::String::kNormalString
,
292 tls_channel_id
.size());
295 if (info
.guest_process_id
!= content::ChildProcessHost::kInvalidUniqueID
)
296 guest_process_id
= v8::Integer::New(isolate
, info
.guest_process_id
);
299 v8::Handle
<v8::Value
> arguments
[] = {
301 v8::Integer::New(isolate
, target_port_id
),
303 v8::String::NewFromUtf8(isolate
,
304 channel_name
.c_str(),
305 v8::String::kNormalString
,
306 channel_name
.size()),
310 v8::Integer::New(isolate
, source
->frame_id
),
314 v8::String::NewFromUtf8(isolate
,
315 info
.source_id
.c_str(),
316 v8::String::kNormalString
,
317 info
.source_id
.size()),
319 v8::String::NewFromUtf8(isolate
,
320 target_extension_id
.c_str(),
321 v8::String::kNormalString
,
322 target_extension_id
.size()),
324 v8::String::NewFromUtf8(isolate
,
325 source_url_spec
.c_str(),
326 v8::String::kNormalString
,
327 source_url_spec
.size()),
329 tls_channel_id_value
,
332 v8::Handle
<v8::Value
> retval
=
333 script_context
->module_system()->CallModuleMethod(
334 "messaging", "dispatchOnConnect", arraysize(arguments
), arguments
);
336 if (!retval
.IsEmpty()) {
337 CHECK(retval
->IsBoolean());
338 *port_created
|= retval
->BooleanValue();
340 LOG(ERROR
) << "Empty return value from dispatchOnConnect.";
344 void DeliverMessageToScriptContext(const Message
& message
,
346 ScriptContext
* script_context
) {
347 v8::Isolate
* isolate
= script_context
->isolate();
348 v8::HandleScope
handle_scope(isolate
);
350 // Check to see whether the context has this port before bothering to create
352 v8::Handle
<v8::Value
> port_id_handle
=
353 v8::Integer::New(isolate
, target_port_id
);
354 v8::Handle
<v8::Value
> has_port
=
355 script_context
->module_system()->CallModuleMethod(
356 "messaging", "hasPort", 1, &port_id_handle
);
358 CHECK(!has_port
.IsEmpty());
359 if (!has_port
->BooleanValue())
362 std::vector
<v8::Handle
<v8::Value
> > arguments
;
363 arguments
.push_back(v8::String::NewFromUtf8(isolate
,
364 message
.data
.c_str(),
365 v8::String::kNormalString
,
366 message
.data
.size()));
367 arguments
.push_back(port_id_handle
);
369 scoped_ptr
<blink::WebScopedUserGesture
> web_user_gesture
;
370 scoped_ptr
<blink::WebScopedWindowFocusAllowedIndicator
> allow_window_focus
;
371 if (message
.user_gesture
) {
372 web_user_gesture
.reset(new blink::WebScopedUserGesture
);
374 if (script_context
->web_frame()) {
375 blink::WebDocument document
= script_context
->web_frame()->document();
376 allow_window_focus
.reset(new blink::WebScopedWindowFocusAllowedIndicator(
381 script_context
->module_system()->CallModuleMethod(
382 "messaging", "dispatchOnMessage", &arguments
);
385 void DispatchOnDisconnectToScriptContext(int port_id
,
386 const std::string
& error_message
,
387 ScriptContext
* script_context
) {
388 v8::Isolate
* isolate
= script_context
->isolate();
389 v8::HandleScope
handle_scope(isolate
);
391 std::vector
<v8::Handle
<v8::Value
> > arguments
;
392 arguments
.push_back(v8::Integer::New(isolate
, port_id
));
393 if (!error_message
.empty()) {
395 v8::String::NewFromUtf8(isolate
, error_message
.c_str()));
397 arguments
.push_back(v8::Null(isolate
));
400 script_context
->module_system()->CallModuleMethod(
401 "messaging", "dispatchOnDisconnect", &arguments
);
406 ObjectBackedNativeHandler
* MessagingBindings::Get(Dispatcher
* dispatcher
,
407 ScriptContext
* context
) {
408 return new ExtensionImpl(dispatcher
, context
);
412 void MessagingBindings::DispatchOnConnect(
413 const ScriptContextSet
& context_set
,
415 const std::string
& channel_name
,
416 const ExtensionMsg_TabConnectionInfo
& source
,
417 const ExtensionMsg_ExternalConnectionInfo
& info
,
418 const std::string
& tls_channel_id
,
419 content::RenderFrame
* restrict_to_render_frame
) {
420 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
421 content::RenderView
* restrict_to_render_view
=
422 restrict_to_render_frame
? restrict_to_render_frame
->GetRenderView()
424 bool port_created
= false;
426 info
.target_id
, restrict_to_render_view
,
427 base::Bind(&DispatchOnConnectToScriptContext
, target_port_id
,
428 channel_name
, &source
, info
, tls_channel_id
, &port_created
));
430 // If we didn't create a port, notify the other end of the channel (treat it
433 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
434 target_port_id
, kReceivingEndDoesntExistError
));
439 void MessagingBindings::DeliverMessage(
440 const ScriptContextSet
& context_set
,
442 const Message
& message
,
443 content::RenderFrame
* restrict_to_render_frame
) {
444 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
445 content::RenderView
* restrict_to_render_view
=
446 restrict_to_render_frame
? restrict_to_render_frame
->GetRenderView()
449 restrict_to_render_view
,
450 base::Bind(&DeliverMessageToScriptContext
, message
, target_port_id
));
454 void MessagingBindings::DispatchOnDisconnect(
455 const ScriptContextSet
& context_set
,
457 const std::string
& error_message
,
458 content::RenderFrame
* restrict_to_render_frame
) {
459 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
460 content::RenderView
* restrict_to_render_view
=
461 restrict_to_render_frame
? restrict_to_render_frame
->GetRenderView()
464 restrict_to_render_view
,
465 base::Bind(&DispatchOnDisconnectToScriptContext
, port_id
, error_message
));
468 } // namespace extensions