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/callback.h"
14 #include "base/lazy_instance.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/values.h"
18 #include "components/guest_view/common/guest_view_constants.h"
19 #include "content/public/child/v8_value_converter.h"
20 #include "content/public/common/child_process_host.h"
21 #include "content/public/renderer/render_frame.h"
22 #include "content/public/renderer/render_thread.h"
23 #include "extensions/common/api/messaging/message.h"
24 #include "extensions/common/extension_messages.h"
25 #include "extensions/common/manifest_handlers/externally_connectable.h"
26 #include "extensions/renderer/dispatcher.h"
27 #include "extensions/renderer/event_bindings.h"
28 #include "extensions/renderer/object_backed_native_handler.h"
29 #include "extensions/renderer/script_context.h"
30 #include "extensions/renderer/script_context_set.h"
31 #include "extensions/renderer/v8_helpers.h"
32 #include "third_party/WebKit/public/web/WebDocument.h"
33 #include "third_party/WebKit/public/web/WebLocalFrame.h"
34 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
35 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
36 #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h"
37 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
38 #include "v8/include/v8.h"
40 // Message passing API example (in a content script):
42 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
43 // var port = runtime.connect();
44 // port.postMessage('Can you hear me now?');
45 // port.onmessage.addListener(function(msg, port) {
46 // alert('response=' + msg);
47 // port.postMessage('I got your reponse');
50 using content::RenderThread
;
51 using content::V8ValueConverter
;
53 namespace extensions
{
55 using v8_helpers::ToV8String
;
56 using v8_helpers::ToV8StringUnsafe
;
57 using v8_helpers::IsEmptyOrUndefied
;
61 // Binds |callback| to run when |object| is garbage collected. So as to not
62 // re-entrantly call into v8, we execute this function asynchronously, at
63 // which point |context| may have been invalidated. If so, |callback| is not
64 // run, and |fallback| will be called instead.
66 // Deletes itself when the object args[0] is garbage collected or when the
67 // context is invalidated.
68 class GCCallback
: public base::SupportsWeakPtr
<GCCallback
> {
70 GCCallback(ScriptContext
* context
,
71 const v8::Local
<v8::Object
>& object
,
72 const v8::Local
<v8::Function
>& callback
,
73 const base::Closure
& fallback
)
75 object_(context
->isolate(), object
),
76 callback_(context
->isolate(), callback
),
78 object_
.SetWeak(this, FirstWeakCallback
, v8::WeakCallbackType::kParameter
);
79 context
->AddInvalidationObserver(
80 base::Bind(&GCCallback::OnContextInvalidated
, AsWeakPtr()));
84 static void FirstWeakCallback(const v8::WeakCallbackInfo
<GCCallback
>& data
) {
85 // v8 says we need to explicitly reset weak handles from their callbacks.
86 // It's not implicit as one might expect.
87 data
.GetParameter()->object_
.Reset();
88 data
.SetSecondPassCallback(SecondWeakCallback
);
91 static void SecondWeakCallback(const v8::WeakCallbackInfo
<GCCallback
>& data
) {
92 base::MessageLoop::current()->PostTask(
94 base::Bind(&GCCallback::RunCallback
, data
.GetParameter()->AsWeakPtr()));
99 v8::Isolate
* isolate
= context_
->isolate();
100 v8::HandleScope
handle_scope(isolate
);
101 context_
->CallFunction(v8::Local
<v8::Function
>::New(isolate
, callback_
));
105 void OnContextInvalidated() {
111 // ScriptContext which owns this GCCallback.
112 ScriptContext
* context_
;
114 // Holds a global handle to the object this GCCallback is bound to.
115 v8::Global
<v8::Object
> object_
;
117 // Function to run when |object_| bound to this GCCallback is GC'd.
118 v8::Global
<v8::Function
> callback_
;
120 // Function to run if context is invalidated before we have a chance
121 // to execute |callback_|.
122 base::Closure fallback_
;
124 DISALLOW_COPY_AND_ASSIGN(GCCallback
);
127 // Tracks every reference between ScriptContexts and Ports, by ID.
133 // Returns true if |context| references |port_id|.
134 bool HasReference(ScriptContext
* context
, int port_id
) const {
135 auto ports
= contexts_to_ports_
.find(context
);
136 return ports
!= contexts_to_ports_
.end() &&
137 ports
->second
.count(port_id
) > 0;
140 // Marks |context| and |port_id| as referencing each other.
141 void AddReference(ScriptContext
* context
, int port_id
) {
142 contexts_to_ports_
[context
].insert(port_id
);
145 // Removes the references between |context| and |port_id|.
146 // Returns true if a reference was removed, false if the reference didn't
147 // exist to be removed.
148 bool RemoveReference(ScriptContext
* context
, int port_id
) {
149 auto ports
= contexts_to_ports_
.find(context
);
150 if (ports
== contexts_to_ports_
.end() ||
151 ports
->second
.erase(port_id
) == 0) {
154 if (ports
->second
.empty())
155 contexts_to_ports_
.erase(context
);
159 // Returns true if this tracker has any reference to |port_id|.
160 bool HasPort(int port_id
) const {
161 for (auto it
: contexts_to_ports_
) {
162 if (it
.second
.count(port_id
) > 0)
168 // Deletes all references to |port_id|.
169 void DeletePort(int port_id
) {
170 for (auto it
= contexts_to_ports_
.begin();
171 it
!= contexts_to_ports_
.end();) {
172 if (it
->second
.erase(port_id
) > 0 && it
->second
.empty())
173 contexts_to_ports_
.erase(it
++);
179 // Gets every port ID that has a reference to |context|.
180 std::set
<int> GetPortsForContext(ScriptContext
* context
) const {
181 auto ports
= contexts_to_ports_
.find(context
);
182 return ports
== contexts_to_ports_
.end() ? std::set
<int>() : ports
->second
;
186 // Maps ScriptContexts to the port IDs that have a reference to it.
187 std::map
<ScriptContext
*, std::set
<int>> contexts_to_ports_
;
189 DISALLOW_COPY_AND_ASSIGN(PortTracker
);
192 base::LazyInstance
<PortTracker
> g_port_tracker
= LAZY_INSTANCE_INITIALIZER
;
194 const char kPortClosedError
[] = "Attempting to use a disconnected port object";
195 const char kReceivingEndDoesntExistError
[] =
196 "Could not establish connection. Receiving end does not exist.";
198 class ExtensionImpl
: public ObjectBackedNativeHandler
{
200 ExtensionImpl(Dispatcher
* dispatcher
, ScriptContext
* context
)
201 : ObjectBackedNativeHandler(context
),
202 dispatcher_(dispatcher
),
203 weak_ptr_factory_(this) {
206 base::Bind(&ExtensionImpl::CloseChannel
, base::Unretained(this)));
209 base::Bind(&ExtensionImpl::PortAddRef
, base::Unretained(this)));
212 base::Bind(&ExtensionImpl::PortRelease
, base::Unretained(this)));
215 base::Bind(&ExtensionImpl::PostMessage
, base::Unretained(this)));
216 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
217 RouteFunction("BindToGC",
218 base::Bind(&ExtensionImpl::BindToGC
, base::Unretained(this)));
220 // Observe |context| so that port references to it can be cleared.
221 context
->AddInvalidationObserver(base::Bind(
222 &ExtensionImpl::OnContextInvalidated
, weak_ptr_factory_
.GetWeakPtr()));
225 ~ExtensionImpl() override
{}
228 void OnContextInvalidated() {
229 for (int port_id
: g_port_tracker
.Get().GetPortsForContext(context()))
230 ReleasePort(port_id
);
233 void ClearPortDataAndNotifyDispatcher(int port_id
) {
234 g_port_tracker
.Get().DeletePort(port_id
);
235 dispatcher_
->ClearPortData(port_id
);
238 // Sends a message along the given channel.
239 void PostMessage(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
240 content::RenderFrame
* renderframe
= context()->GetRenderFrame();
244 // Arguments are (int32 port_id, string message).
245 CHECK(args
.Length() == 2 && args
[0]->IsInt32() && args
[1]->IsString());
247 int port_id
= args
[0].As
<v8::Int32
>()->Value();
248 if (!g_port_tracker
.Get().HasPort(port_id
)) {
249 v8::Local
<v8::String
> error_message
=
250 ToV8StringUnsafe(args
.GetIsolate(), kPortClosedError
);
251 args
.GetIsolate()->ThrowException(v8::Exception::Error(error_message
));
255 renderframe
->Send(new ExtensionHostMsg_PostMessage(
256 renderframe
->GetRoutingID(), port_id
,
257 Message(*v8::String::Utf8Value(args
[1]),
258 blink::WebUserGestureIndicator::isProcessingUserGesture())));
261 // Forcefully disconnects a port.
262 void CloseChannel(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
263 // Arguments are (int32 port_id, boolean notify_browser).
264 CHECK_EQ(2, args
.Length());
265 CHECK(args
[0]->IsInt32());
266 CHECK(args
[1]->IsBoolean());
268 int port_id
= args
[0].As
<v8::Int32
>()->Value();
269 if (!g_port_tracker
.Get().HasPort(port_id
))
272 // Send via the RenderThread because the RenderFrame might be closing.
273 bool notify_browser
= args
[1].As
<v8::Boolean
>()->Value();
274 if (notify_browser
) {
275 content::RenderThread::Get()->Send(
276 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
279 ClearPortDataAndNotifyDispatcher(port_id
);
282 // A new port has been created for a context. This occurs both when script
283 // opens a connection, and when a connection is opened to this script.
284 void PortAddRef(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
285 // Arguments are (int32 port_id).
286 CHECK_EQ(1, args
.Length());
287 CHECK(args
[0]->IsInt32());
289 int port_id
= args
[0].As
<v8::Int32
>()->Value();
290 g_port_tracker
.Get().AddReference(context(), port_id
);
293 // The frame a port lived in has been destroyed. When there are no more
294 // frames with a reference to a given port, we will disconnect it and notify
295 // the other end of the channel.
296 void PortRelease(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
297 // Arguments are (int32 port_id).
298 CHECK(args
.Length() == 1 && args
[0]->IsInt32());
299 ReleasePort(args
[0].As
<v8::Int32
>()->Value());
302 // Releases the reference to |port_id| for this context, and clears all port
303 // data if there are no more references.
304 void ReleasePort(int port_id
) {
305 if (g_port_tracker
.Get().RemoveReference(context(), port_id
) &&
306 !g_port_tracker
.Get().HasPort(port_id
)) {
307 // Send via the RenderThread because the RenderFrame might be closing.
308 content::RenderThread::Get()->Send(
309 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
310 ClearPortDataAndNotifyDispatcher(port_id
);
314 // void BindToGC(object, callback, port_id)
316 // Binds |callback| to be invoked *sometime after* |object| is garbage
317 // collected. We don't call the method re-entrantly so as to avoid executing
318 // JS in some bizarro undefined mid-GC state, nor do we then call into the
319 // script context if it's been invalidated.
321 // If the script context *is* invalidated in the meantime, as a slight hack,
322 // release the port with ID |port_id| if it's >= 0.
323 void BindToGC(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
324 CHECK(args
.Length() == 3 && args
[0]->IsObject() && args
[1]->IsFunction() &&
326 int port_id
= args
[2].As
<v8::Int32
>()->Value();
327 base::Closure fallback
= base::Bind(&base::DoNothing
);
329 fallback
= base::Bind(&ExtensionImpl::ReleasePort
,
330 weak_ptr_factory_
.GetWeakPtr(), port_id
);
332 // Destroys itself when the object is GC'd or context is invalidated.
333 new GCCallback(context(), args
[0].As
<v8::Object
>(),
334 args
[1].As
<v8::Function
>(), fallback
);
337 // Dispatcher handle. Not owned.
338 Dispatcher
* dispatcher_
;
340 base::WeakPtrFactory
<ExtensionImpl
> weak_ptr_factory_
;
343 void DispatchOnConnectToScriptContext(
345 const std::string
& channel_name
,
346 const ExtensionMsg_TabConnectionInfo
* source
,
347 const ExtensionMsg_ExternalConnectionInfo
& info
,
348 const std::string
& tls_channel_id
,
350 ScriptContext
* script_context
) {
351 // Only dispatch the events if this is the requested target frame (0 = main
352 // frame; positive = child frame).
353 content::RenderFrame
* renderframe
= script_context
->GetRenderFrame();
354 if (info
.target_frame_id
== 0 && renderframe
->GetWebFrame()->parent() != NULL
)
356 if (info
.target_frame_id
> 0 &&
357 renderframe
->GetRoutingID() != info
.target_frame_id
)
359 v8::Isolate
* isolate
= script_context
->isolate();
360 v8::HandleScope
handle_scope(isolate
);
362 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
364 const std::string
& source_url_spec
= info
.source_url
.spec();
365 std::string target_extension_id
= script_context
->GetExtensionID();
366 const Extension
* extension
= script_context
->extension();
368 v8::Local
<v8::Value
> tab
= v8::Null(isolate
);
369 v8::Local
<v8::Value
> tls_channel_id_value
= v8::Undefined(isolate
);
370 v8::Local
<v8::Value
> guest_process_id
= v8::Undefined(isolate
);
371 v8::Local
<v8::Value
> guest_render_frame_routing_id
= v8::Undefined(isolate
);
374 if (!source
->tab
.empty() && !extension
->is_platform_app())
375 tab
= converter
->ToV8Value(&source
->tab
, script_context
->v8_context());
377 ExternallyConnectableInfo
* externally_connectable
=
378 ExternallyConnectableInfo::Get(extension
);
379 if (externally_connectable
&&
380 externally_connectable
->accepts_tls_channel_id
) {
381 v8::Local
<v8::String
> v8_tls_channel_id
;
382 if (ToV8String(isolate
, tls_channel_id
.c_str(), &v8_tls_channel_id
))
383 tls_channel_id_value
= v8_tls_channel_id
;
386 if (info
.guest_process_id
!= content::ChildProcessHost::kInvalidUniqueID
) {
387 guest_process_id
= v8::Integer::New(isolate
, info
.guest_process_id
);
388 guest_render_frame_routing_id
=
389 v8::Integer::New(isolate
, info
.guest_render_frame_routing_id
);
393 v8::Local
<v8::String
> v8_channel_name
;
394 v8::Local
<v8::String
> v8_source_id
;
395 v8::Local
<v8::String
> v8_target_extension_id
;
396 v8::Local
<v8::String
> v8_source_url_spec
;
397 if (!ToV8String(isolate
, channel_name
.c_str(), &v8_channel_name
) ||
398 !ToV8String(isolate
, info
.source_id
.c_str(), &v8_source_id
) ||
399 !ToV8String(isolate
, target_extension_id
.c_str(),
400 &v8_target_extension_id
) ||
401 !ToV8String(isolate
, source_url_spec
.c_str(), &v8_source_url_spec
)) {
402 NOTREACHED() << "dispatchOnConnect() passed non-string argument";
406 v8::Local
<v8::Value
> arguments
[] = {
408 v8::Integer::New(isolate
, target_port_id
),
414 v8::Integer::New(isolate
, source
->frame_id
),
417 // guestRenderFrameRoutingId
418 guest_render_frame_routing_id
,
422 v8_target_extension_id
,
426 tls_channel_id_value
,
429 v8::Local
<v8::Value
> retval
=
430 script_context
->module_system()->CallModuleMethod(
431 "messaging", "dispatchOnConnect", arraysize(arguments
), arguments
);
433 if (!IsEmptyOrUndefied(retval
)) {
434 CHECK(retval
->IsBoolean());
435 *port_created
|= retval
.As
<v8::Boolean
>()->Value();
437 LOG(ERROR
) << "Empty return value from dispatchOnConnect.";
441 void DeliverMessageToScriptContext(const Message
& message
,
443 ScriptContext
* script_context
) {
444 v8::Isolate
* isolate
= script_context
->isolate();
445 v8::HandleScope
handle_scope(isolate
);
447 // Check to see whether the context has this port before bothering to create
449 v8::Local
<v8::Value
> port_id_handle
=
450 v8::Integer::New(isolate
, target_port_id
);
451 v8::Local
<v8::Value
> has_port
=
452 script_context
->module_system()->CallModuleMethod("messaging", "hasPort",
454 // Could be empty/undefined if an exception was thrown.
455 // TODO(kalman): Should this be built into CallModuleMethod?
456 if (IsEmptyOrUndefied(has_port
))
458 CHECK(has_port
->IsBoolean());
459 if (!has_port
.As
<v8::Boolean
>()->Value())
462 v8::Local
<v8::String
> v8_data
;
463 if (!ToV8String(isolate
, message
.data
.c_str(), &v8_data
))
465 std::vector
<v8::Local
<v8::Value
>> arguments
;
466 arguments
.push_back(v8_data
);
467 arguments
.push_back(port_id_handle
);
469 scoped_ptr
<blink::WebScopedUserGesture
> web_user_gesture
;
470 scoped_ptr
<blink::WebScopedWindowFocusAllowedIndicator
> allow_window_focus
;
471 if (message
.user_gesture
) {
472 web_user_gesture
.reset(new blink::WebScopedUserGesture
);
474 if (script_context
->web_frame()) {
475 blink::WebDocument document
= script_context
->web_frame()->document();
476 allow_window_focus
.reset(new blink::WebScopedWindowFocusAllowedIndicator(
481 script_context
->module_system()->CallModuleMethod(
482 "messaging", "dispatchOnMessage", &arguments
);
485 void DispatchOnDisconnectToScriptContext(int port_id
,
486 const std::string
& error_message
,
487 ScriptContext
* script_context
) {
488 v8::Isolate
* isolate
= script_context
->isolate();
489 v8::HandleScope
handle_scope(isolate
);
491 std::vector
<v8::Local
<v8::Value
>> arguments
;
492 arguments
.push_back(v8::Integer::New(isolate
, port_id
));
493 v8::Local
<v8::String
> v8_error_message
;
494 if (!error_message
.empty())
495 ToV8String(isolate
, error_message
.c_str(), &v8_error_message
);
496 if (!v8_error_message
.IsEmpty()) {
497 arguments
.push_back(v8_error_message
);
499 arguments
.push_back(v8::Null(isolate
));
502 script_context
->module_system()->CallModuleMethod(
503 "messaging", "dispatchOnDisconnect", &arguments
);
508 ObjectBackedNativeHandler
* MessagingBindings::Get(Dispatcher
* dispatcher
,
509 ScriptContext
* context
) {
510 return new ExtensionImpl(dispatcher
, context
);
514 void MessagingBindings::DispatchOnConnect(
515 const ScriptContextSet
& context_set
,
517 const std::string
& channel_name
,
518 const ExtensionMsg_TabConnectionInfo
& source
,
519 const ExtensionMsg_ExternalConnectionInfo
& info
,
520 const std::string
& tls_channel_id
,
521 content::RenderFrame
* restrict_to_render_frame
) {
522 bool port_created
= false;
524 info
.target_id
, restrict_to_render_frame
,
525 base::Bind(&DispatchOnConnectToScriptContext
, target_port_id
,
526 channel_name
, &source
, info
, tls_channel_id
, &port_created
));
528 // If we didn't create a port, notify the other end of the channel (treat it
531 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
532 target_port_id
, kReceivingEndDoesntExistError
));
537 void MessagingBindings::DeliverMessage(
538 const ScriptContextSet
& context_set
,
540 const Message
& message
,
541 content::RenderFrame
* restrict_to_render_frame
) {
543 restrict_to_render_frame
,
544 base::Bind(&DeliverMessageToScriptContext
, message
, target_port_id
));
548 void MessagingBindings::DispatchOnDisconnect(
549 const ScriptContextSet
& context_set
,
551 const std::string
& error_message
,
552 content::RenderFrame
* restrict_to_render_frame
) {
554 restrict_to_render_frame
,
555 base::Bind(&DispatchOnDisconnectToScriptContext
, port_id
, error_message
));
558 } // namespace extensions