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::Local
<v8::Object
> object
,
186 v8::Local
<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::Local
<v8::Object
> object
,
211 v8::Local
<v8::Function
> callback
,
212 v8::Isolate
* isolate
)
213 : object_(isolate
, object
),
214 callback_(isolate
, callback
),
218 v8::HandleScope
handle_scope(isolate_
);
219 v8::Local
<v8::Function
> callback
=
220 v8::Local
<v8::Function
>::New(isolate_
, callback_
);
221 v8::Local
<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::Local
<v8::Value
> tab
= v8::Null(isolate
);
278 v8::Local
<v8::Value
> tls_channel_id_value
= v8::Undefined(isolate
);
279 v8::Local
<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::Local
<v8::Value
> arguments
[] = {
301 v8::Integer::New(isolate
, target_port_id
),
303 v8::String::NewFromUtf8(isolate
, channel_name
.c_str(),
304 v8::String::kNormalString
, channel_name
.size()),
308 v8::Integer::New(isolate
, source
->frame_id
),
312 v8::String::NewFromUtf8(isolate
, info
.source_id
.c_str(),
313 v8::String::kNormalString
, info
.source_id
.size()),
315 v8::String::NewFromUtf8(isolate
, target_extension_id
.c_str(),
316 v8::String::kNormalString
,
317 target_extension_id
.size()),
319 v8::String::NewFromUtf8(isolate
, source_url_spec
.c_str(),
320 v8::String::kNormalString
,
321 source_url_spec
.size()),
323 tls_channel_id_value
,
326 v8::Local
<v8::Value
> retval
=
327 script_context
->module_system()->CallModuleMethod(
328 "messaging", "dispatchOnConnect", arraysize(arguments
), arguments
);
330 if (!retval
.IsEmpty()) {
331 CHECK(retval
->IsBoolean());
332 *port_created
|= retval
->BooleanValue();
334 LOG(ERROR
) << "Empty return value from dispatchOnConnect.";
338 void DeliverMessageToScriptContext(const Message
& message
,
340 ScriptContext
* script_context
) {
341 v8::Isolate
* isolate
= script_context
->isolate();
342 v8::HandleScope
handle_scope(isolate
);
344 // Check to see whether the context has this port before bothering to create
346 v8::Local
<v8::Value
> port_id_handle
=
347 v8::Integer::New(isolate
, target_port_id
);
348 v8::Local
<v8::Value
> has_port
=
349 script_context
->module_system()->CallModuleMethod("messaging", "hasPort",
352 CHECK(!has_port
.IsEmpty());
353 if (!has_port
->BooleanValue())
356 std::vector
<v8::Local
<v8::Value
>> arguments
;
357 arguments
.push_back(v8::String::NewFromUtf8(isolate
,
358 message
.data
.c_str(),
359 v8::String::kNormalString
,
360 message
.data
.size()));
361 arguments
.push_back(port_id_handle
);
363 scoped_ptr
<blink::WebScopedUserGesture
> web_user_gesture
;
364 scoped_ptr
<blink::WebScopedWindowFocusAllowedIndicator
> allow_window_focus
;
365 if (message
.user_gesture
) {
366 web_user_gesture
.reset(new blink::WebScopedUserGesture
);
368 if (script_context
->web_frame()) {
369 blink::WebDocument document
= script_context
->web_frame()->document();
370 allow_window_focus
.reset(new blink::WebScopedWindowFocusAllowedIndicator(
375 script_context
->module_system()->CallModuleMethod(
376 "messaging", "dispatchOnMessage", &arguments
);
379 void DispatchOnDisconnectToScriptContext(int port_id
,
380 const std::string
& error_message
,
381 ScriptContext
* script_context
) {
382 v8::Isolate
* isolate
= script_context
->isolate();
383 v8::HandleScope
handle_scope(isolate
);
385 std::vector
<v8::Local
<v8::Value
>> arguments
;
386 arguments
.push_back(v8::Integer::New(isolate
, port_id
));
387 if (!error_message
.empty()) {
389 v8::String::NewFromUtf8(isolate
, error_message
.c_str()));
391 arguments
.push_back(v8::Null(isolate
));
394 script_context
->module_system()->CallModuleMethod(
395 "messaging", "dispatchOnDisconnect", &arguments
);
400 ObjectBackedNativeHandler
* MessagingBindings::Get(Dispatcher
* dispatcher
,
401 ScriptContext
* context
) {
402 return new ExtensionImpl(dispatcher
, context
);
406 void MessagingBindings::DispatchOnConnect(
407 const ScriptContextSet
& context_set
,
409 const std::string
& channel_name
,
410 const ExtensionMsg_TabConnectionInfo
& source
,
411 const ExtensionMsg_ExternalConnectionInfo
& info
,
412 const std::string
& tls_channel_id
,
413 content::RenderFrame
* restrict_to_render_frame
) {
414 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
415 content::RenderView
* restrict_to_render_view
=
416 restrict_to_render_frame
? restrict_to_render_frame
->GetRenderView()
418 bool port_created
= false;
420 info
.target_id
, restrict_to_render_view
,
421 base::Bind(&DispatchOnConnectToScriptContext
, target_port_id
,
422 channel_name
, &source
, info
, tls_channel_id
, &port_created
));
424 // If we didn't create a port, notify the other end of the channel (treat it
427 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
428 target_port_id
, kReceivingEndDoesntExistError
));
433 void MessagingBindings::DeliverMessage(
434 const ScriptContextSet
& context_set
,
436 const Message
& message
,
437 content::RenderFrame
* restrict_to_render_frame
) {
438 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
439 content::RenderView
* restrict_to_render_view
=
440 restrict_to_render_frame
? restrict_to_render_frame
->GetRenderView()
443 restrict_to_render_view
,
444 base::Bind(&DeliverMessageToScriptContext
, message
, target_port_id
));
448 void MessagingBindings::DispatchOnDisconnect(
449 const ScriptContextSet
& context_set
,
451 const std::string
& error_message
,
452 content::RenderFrame
* restrict_to_render_frame
) {
453 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
454 content::RenderView
* restrict_to_render_view
=
455 restrict_to_render_frame
? restrict_to_render_frame
->GetRenderView()
458 restrict_to_render_view
,
459 base::Bind(&DispatchOnDisconnectToScriptContext
, port_id
, error_message
));
462 } // namespace extensions