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/gc_callback.h"
29 #include "extensions/renderer/object_backed_native_handler.h"
30 #include "extensions/renderer/script_context.h"
31 #include "extensions/renderer/script_context_set.h"
32 #include "extensions/renderer/v8_helpers.h"
33 #include "third_party/WebKit/public/web/WebDocument.h"
34 #include "third_party/WebKit/public/web/WebLocalFrame.h"
35 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
36 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
37 #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h"
38 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
39 #include "v8/include/v8.h"
41 // Message passing API example (in a content script):
43 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
44 // var port = runtime.connect();
45 // port.postMessage('Can you hear me now?');
46 // port.onmessage.addListener(function(msg, port) {
47 // alert('response=' + msg);
48 // port.postMessage('I got your reponse');
51 using content::RenderThread
;
52 using content::V8ValueConverter
;
54 namespace extensions
{
56 using v8_helpers::ToV8String
;
57 using v8_helpers::ToV8StringUnsafe
;
58 using v8_helpers::IsEmptyOrUndefied
;
62 // Tracks every reference between ScriptContexts and Ports, by ID.
68 // Returns true if |context| references |port_id|.
69 bool HasReference(ScriptContext
* context
, int port_id
) const {
70 auto ports
= contexts_to_ports_
.find(context
);
71 return ports
!= contexts_to_ports_
.end() &&
72 ports
->second
.count(port_id
) > 0;
75 // Marks |context| and |port_id| as referencing each other.
76 void AddReference(ScriptContext
* context
, int port_id
) {
77 contexts_to_ports_
[context
].insert(port_id
);
80 // Removes the references between |context| and |port_id|.
81 // Returns true if a reference was removed, false if the reference didn't
82 // exist to be removed.
83 bool RemoveReference(ScriptContext
* context
, int port_id
) {
84 auto ports
= contexts_to_ports_
.find(context
);
85 if (ports
== contexts_to_ports_
.end() ||
86 ports
->second
.erase(port_id
) == 0) {
89 if (ports
->second
.empty())
90 contexts_to_ports_
.erase(context
);
94 // Returns true if this tracker has any reference to |port_id|.
95 bool HasPort(int port_id
) const {
96 for (auto it
: contexts_to_ports_
) {
97 if (it
.second
.count(port_id
) > 0)
103 // Deletes all references to |port_id|.
104 void DeletePort(int port_id
) {
105 for (auto it
= contexts_to_ports_
.begin();
106 it
!= contexts_to_ports_
.end();) {
107 if (it
->second
.erase(port_id
) > 0 && it
->second
.empty())
108 contexts_to_ports_
.erase(it
++);
114 // Gets every port ID that has a reference to |context|.
115 std::set
<int> GetPortsForContext(ScriptContext
* context
) const {
116 auto ports
= contexts_to_ports_
.find(context
);
117 return ports
== contexts_to_ports_
.end() ? std::set
<int>() : ports
->second
;
121 // Maps ScriptContexts to the port IDs that have a reference to it.
122 std::map
<ScriptContext
*, std::set
<int>> contexts_to_ports_
;
124 DISALLOW_COPY_AND_ASSIGN(PortTracker
);
127 base::LazyInstance
<PortTracker
> g_port_tracker
= LAZY_INSTANCE_INITIALIZER
;
129 const char kPortClosedError
[] = "Attempting to use a disconnected port object";
130 const char kReceivingEndDoesntExistError
[] =
131 "Could not establish connection. Receiving end does not exist.";
133 class ExtensionImpl
: public ObjectBackedNativeHandler
{
135 ExtensionImpl(Dispatcher
* dispatcher
, ScriptContext
* context
)
136 : ObjectBackedNativeHandler(context
),
137 dispatcher_(dispatcher
),
138 weak_ptr_factory_(this) {
141 base::Bind(&ExtensionImpl::CloseChannel
, base::Unretained(this)));
144 base::Bind(&ExtensionImpl::PortAddRef
, base::Unretained(this)));
147 base::Bind(&ExtensionImpl::PortRelease
, base::Unretained(this)));
150 base::Bind(&ExtensionImpl::PostMessage
, base::Unretained(this)));
151 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
152 RouteFunction("BindToGC",
153 base::Bind(&ExtensionImpl::BindToGC
, base::Unretained(this)));
155 // Observe |context| so that port references to it can be cleared.
156 context
->AddInvalidationObserver(base::Bind(
157 &ExtensionImpl::OnContextInvalidated
, weak_ptr_factory_
.GetWeakPtr()));
160 ~ExtensionImpl() override
{}
163 void OnContextInvalidated() {
164 for (int port_id
: g_port_tracker
.Get().GetPortsForContext(context()))
165 ReleasePort(port_id
);
168 void ClearPortDataAndNotifyDispatcher(int port_id
) {
169 g_port_tracker
.Get().DeletePort(port_id
);
170 dispatcher_
->ClearPortData(port_id
);
173 // Sends a message along the given channel.
174 void PostMessage(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
175 content::RenderFrame
* renderframe
= context()->GetRenderFrame();
179 // Arguments are (int32 port_id, string message).
180 CHECK(args
.Length() == 2 && args
[0]->IsInt32() && args
[1]->IsString());
182 int port_id
= args
[0].As
<v8::Int32
>()->Value();
183 if (!g_port_tracker
.Get().HasPort(port_id
)) {
184 v8::Local
<v8::String
> error_message
=
185 ToV8StringUnsafe(args
.GetIsolate(), kPortClosedError
);
186 args
.GetIsolate()->ThrowException(v8::Exception::Error(error_message
));
190 renderframe
->Send(new ExtensionHostMsg_PostMessage(
191 renderframe
->GetRoutingID(), port_id
,
192 Message(*v8::String::Utf8Value(args
[1]),
193 blink::WebUserGestureIndicator::isProcessingUserGesture())));
196 // Forcefully disconnects a port.
197 void CloseChannel(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
198 // Arguments are (int32 port_id, boolean notify_browser).
199 CHECK_EQ(2, args
.Length());
200 CHECK(args
[0]->IsInt32());
201 CHECK(args
[1]->IsBoolean());
203 int port_id
= args
[0].As
<v8::Int32
>()->Value();
204 if (!g_port_tracker
.Get().HasPort(port_id
))
207 // Send via the RenderThread because the RenderFrame might be closing.
208 bool notify_browser
= args
[1].As
<v8::Boolean
>()->Value();
209 if (notify_browser
) {
210 content::RenderThread::Get()->Send(
211 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
214 ClearPortDataAndNotifyDispatcher(port_id
);
217 // A new port has been created for a context. This occurs both when script
218 // opens a connection, and when a connection is opened to this script.
219 void PortAddRef(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
220 // Arguments are (int32 port_id).
221 CHECK_EQ(1, args
.Length());
222 CHECK(args
[0]->IsInt32());
224 int port_id
= args
[0].As
<v8::Int32
>()->Value();
225 g_port_tracker
.Get().AddReference(context(), port_id
);
228 // The frame a port lived in has been destroyed. When there are no more
229 // frames with a reference to a given port, we will disconnect it and notify
230 // the other end of the channel.
231 void PortRelease(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
232 // Arguments are (int32 port_id).
233 CHECK(args
.Length() == 1 && args
[0]->IsInt32());
234 ReleasePort(args
[0].As
<v8::Int32
>()->Value());
237 // Releases the reference to |port_id| for this context, and clears all port
238 // data if there are no more references.
239 void ReleasePort(int port_id
) {
240 if (g_port_tracker
.Get().RemoveReference(context(), port_id
) &&
241 !g_port_tracker
.Get().HasPort(port_id
)) {
242 // Send via the RenderThread because the RenderFrame might be closing.
243 content::RenderThread::Get()->Send(
244 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
245 ClearPortDataAndNotifyDispatcher(port_id
);
249 // void BindToGC(object, callback, port_id)
251 // Binds |callback| to be invoked *sometime after* |object| is garbage
252 // collected. We don't call the method re-entrantly so as to avoid executing
253 // JS in some bizarro undefined mid-GC state, nor do we then call into the
254 // script context if it's been invalidated.
256 // If the script context *is* invalidated in the meantime, as a slight hack,
257 // release the port with ID |port_id| if it's >= 0.
258 void BindToGC(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
259 CHECK(args
.Length() == 3 && args
[0]->IsObject() && args
[1]->IsFunction() &&
261 int port_id
= args
[2].As
<v8::Int32
>()->Value();
262 base::Closure fallback
= base::Bind(&base::DoNothing
);
264 fallback
= base::Bind(&ExtensionImpl::ReleasePort
,
265 weak_ptr_factory_
.GetWeakPtr(), port_id
);
267 // Destroys itself when the object is GC'd or context is invalidated.
268 new GCCallback(context(), args
[0].As
<v8::Object
>(),
269 args
[1].As
<v8::Function
>(), fallback
);
272 // Dispatcher handle. Not owned.
273 Dispatcher
* dispatcher_
;
275 base::WeakPtrFactory
<ExtensionImpl
> weak_ptr_factory_
;
278 void DispatchOnConnectToScriptContext(
280 const std::string
& channel_name
,
281 const ExtensionMsg_TabConnectionInfo
* source
,
282 const ExtensionMsg_ExternalConnectionInfo
& info
,
283 const std::string
& tls_channel_id
,
285 ScriptContext
* script_context
) {
286 // Only dispatch the events if this is the requested target frame (0 = main
287 // frame; positive = child frame).
288 content::RenderFrame
* renderframe
= script_context
->GetRenderFrame();
289 if (info
.target_frame_id
== 0 && renderframe
->GetWebFrame()->parent() != NULL
)
291 if (info
.target_frame_id
> 0 &&
292 renderframe
->GetRoutingID() != info
.target_frame_id
)
294 v8::Isolate
* isolate
= script_context
->isolate();
295 v8::HandleScope
handle_scope(isolate
);
297 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
299 const std::string
& source_url_spec
= info
.source_url
.spec();
300 std::string target_extension_id
= script_context
->GetExtensionID();
301 const Extension
* extension
= script_context
->extension();
303 v8::Local
<v8::Value
> tab
= v8::Null(isolate
);
304 v8::Local
<v8::Value
> tls_channel_id_value
= v8::Undefined(isolate
);
305 v8::Local
<v8::Value
> guest_process_id
= v8::Undefined(isolate
);
306 v8::Local
<v8::Value
> guest_render_frame_routing_id
= v8::Undefined(isolate
);
309 if (!source
->tab
.empty() && !extension
->is_platform_app())
310 tab
= converter
->ToV8Value(&source
->tab
, script_context
->v8_context());
312 ExternallyConnectableInfo
* externally_connectable
=
313 ExternallyConnectableInfo::Get(extension
);
314 if (externally_connectable
&&
315 externally_connectable
->accepts_tls_channel_id
) {
316 v8::Local
<v8::String
> v8_tls_channel_id
;
317 if (ToV8String(isolate
, tls_channel_id
.c_str(), &v8_tls_channel_id
))
318 tls_channel_id_value
= v8_tls_channel_id
;
321 if (info
.guest_process_id
!= content::ChildProcessHost::kInvalidUniqueID
) {
322 guest_process_id
= v8::Integer::New(isolate
, info
.guest_process_id
);
323 guest_render_frame_routing_id
=
324 v8::Integer::New(isolate
, info
.guest_render_frame_routing_id
);
328 v8::Local
<v8::String
> v8_channel_name
;
329 v8::Local
<v8::String
> v8_source_id
;
330 v8::Local
<v8::String
> v8_target_extension_id
;
331 v8::Local
<v8::String
> v8_source_url_spec
;
332 if (!ToV8String(isolate
, channel_name
.c_str(), &v8_channel_name
) ||
333 !ToV8String(isolate
, info
.source_id
.c_str(), &v8_source_id
) ||
334 !ToV8String(isolate
, target_extension_id
.c_str(),
335 &v8_target_extension_id
) ||
336 !ToV8String(isolate
, source_url_spec
.c_str(), &v8_source_url_spec
)) {
337 NOTREACHED() << "dispatchOnConnect() passed non-string argument";
341 v8::Local
<v8::Value
> arguments
[] = {
343 v8::Integer::New(isolate
, target_port_id
),
349 v8::Integer::New(isolate
, source
->frame_id
),
352 // guestRenderFrameRoutingId
353 guest_render_frame_routing_id
,
357 v8_target_extension_id
,
361 tls_channel_id_value
,
364 v8::Local
<v8::Value
> retval
=
365 script_context
->module_system()->CallModuleMethod(
366 "messaging", "dispatchOnConnect", arraysize(arguments
), arguments
);
368 if (!IsEmptyOrUndefied(retval
)) {
369 CHECK(retval
->IsBoolean());
370 *port_created
|= retval
.As
<v8::Boolean
>()->Value();
372 LOG(ERROR
) << "Empty return value from dispatchOnConnect.";
376 void DeliverMessageToScriptContext(const Message
& message
,
378 ScriptContext
* script_context
) {
379 v8::Isolate
* isolate
= script_context
->isolate();
380 v8::HandleScope
handle_scope(isolate
);
382 // Check to see whether the context has this port before bothering to create
384 v8::Local
<v8::Value
> port_id_handle
=
385 v8::Integer::New(isolate
, target_port_id
);
386 v8::Local
<v8::Value
> has_port
=
387 script_context
->module_system()->CallModuleMethod("messaging", "hasPort",
389 // Could be empty/undefined if an exception was thrown.
390 // TODO(kalman): Should this be built into CallModuleMethod?
391 if (IsEmptyOrUndefied(has_port
))
393 CHECK(has_port
->IsBoolean());
394 if (!has_port
.As
<v8::Boolean
>()->Value())
397 v8::Local
<v8::String
> v8_data
;
398 if (!ToV8String(isolate
, message
.data
.c_str(), &v8_data
))
400 std::vector
<v8::Local
<v8::Value
>> arguments
;
401 arguments
.push_back(v8_data
);
402 arguments
.push_back(port_id_handle
);
404 scoped_ptr
<blink::WebScopedUserGesture
> web_user_gesture
;
405 scoped_ptr
<blink::WebScopedWindowFocusAllowedIndicator
> allow_window_focus
;
406 if (message
.user_gesture
) {
407 web_user_gesture
.reset(new blink::WebScopedUserGesture
);
409 if (script_context
->web_frame()) {
410 blink::WebDocument document
= script_context
->web_frame()->document();
411 allow_window_focus
.reset(new blink::WebScopedWindowFocusAllowedIndicator(
416 script_context
->module_system()->CallModuleMethod(
417 "messaging", "dispatchOnMessage", &arguments
);
420 void DispatchOnDisconnectToScriptContext(int port_id
,
421 const std::string
& error_message
,
422 ScriptContext
* script_context
) {
423 v8::Isolate
* isolate
= script_context
->isolate();
424 v8::HandleScope
handle_scope(isolate
);
426 std::vector
<v8::Local
<v8::Value
>> arguments
;
427 arguments
.push_back(v8::Integer::New(isolate
, port_id
));
428 v8::Local
<v8::String
> v8_error_message
;
429 if (!error_message
.empty())
430 ToV8String(isolate
, error_message
.c_str(), &v8_error_message
);
431 if (!v8_error_message
.IsEmpty()) {
432 arguments
.push_back(v8_error_message
);
434 arguments
.push_back(v8::Null(isolate
));
437 script_context
->module_system()->CallModuleMethod(
438 "messaging", "dispatchOnDisconnect", &arguments
);
443 ObjectBackedNativeHandler
* MessagingBindings::Get(Dispatcher
* dispatcher
,
444 ScriptContext
* context
) {
445 return new ExtensionImpl(dispatcher
, context
);
449 void MessagingBindings::DispatchOnConnect(
450 const ScriptContextSet
& context_set
,
452 const std::string
& channel_name
,
453 const ExtensionMsg_TabConnectionInfo
& source
,
454 const ExtensionMsg_ExternalConnectionInfo
& info
,
455 const std::string
& tls_channel_id
,
456 content::RenderFrame
* restrict_to_render_frame
) {
457 bool port_created
= false;
459 info
.target_id
, restrict_to_render_frame
,
460 base::Bind(&DispatchOnConnectToScriptContext
, target_port_id
,
461 channel_name
, &source
, info
, tls_channel_id
, &port_created
));
463 // If we didn't create a port, notify the other end of the channel (treat it
466 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
467 target_port_id
, kReceivingEndDoesntExistError
));
472 void MessagingBindings::DeliverMessage(
473 const ScriptContextSet
& context_set
,
475 const Message
& message
,
476 content::RenderFrame
* restrict_to_render_frame
) {
478 restrict_to_render_frame
,
479 base::Bind(&DeliverMessageToScriptContext
, message
, target_port_id
));
483 void MessagingBindings::DispatchOnDisconnect(
484 const ScriptContextSet
& context_set
,
486 const std::string
& error_message
,
487 content::RenderFrame
* restrict_to_render_frame
) {
489 restrict_to_render_frame
,
490 base::Bind(&DispatchOnDisconnectToScriptContext
, port_id
, error_message
));
493 } // namespace extensions