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/extension_frame_helper.h"
29 #include "extensions/renderer/gc_callback.h"
30 #include "extensions/renderer/object_backed_native_handler.h"
31 #include "extensions/renderer/script_context.h"
32 #include "extensions/renderer/script_context_set.h"
33 #include "extensions/renderer/v8_helpers.h"
34 #include "third_party/WebKit/public/web/WebDocument.h"
35 #include "third_party/WebKit/public/web/WebLocalFrame.h"
36 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
37 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
38 #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h"
39 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
40 #include "v8/include/v8.h"
42 // Message passing API example (in a content script):
44 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
45 // var port = runtime.connect();
46 // port.postMessage('Can you hear me now?');
47 // port.onmessage.addListener(function(msg, port) {
48 // alert('response=' + msg);
49 // port.postMessage('I got your reponse');
52 using content::RenderThread
;
53 using content::V8ValueConverter
;
55 namespace extensions
{
57 using v8_helpers::ToV8String
;
58 using v8_helpers::ToV8StringUnsafe
;
59 using v8_helpers::IsEmptyOrUndefied
;
63 // Tracks every reference between ScriptContexts and Ports, by ID.
69 // Returns true if |context| references |port_id|.
70 bool HasReference(ScriptContext
* context
, int port_id
) const {
71 auto ports
= contexts_to_ports_
.find(context
);
72 return ports
!= contexts_to_ports_
.end() &&
73 ports
->second
.count(port_id
) > 0;
76 // Marks |context| and |port_id| as referencing each other.
77 void AddReference(ScriptContext
* context
, int port_id
) {
78 contexts_to_ports_
[context
].insert(port_id
);
81 // Removes the references between |context| and |port_id|.
82 // Returns true if a reference was removed, false if the reference didn't
83 // exist to be removed.
84 bool RemoveReference(ScriptContext
* context
, int port_id
) {
85 auto ports
= contexts_to_ports_
.find(context
);
86 if (ports
== contexts_to_ports_
.end() ||
87 ports
->second
.erase(port_id
) == 0) {
90 if (ports
->second
.empty())
91 contexts_to_ports_
.erase(context
);
95 // Returns true if this tracker has any reference to |port_id|.
96 bool HasPort(int port_id
) const {
97 for (auto it
: contexts_to_ports_
) {
98 if (it
.second
.count(port_id
) > 0)
104 // Deletes all references to |port_id|.
105 void DeletePort(int port_id
) {
106 for (auto it
= contexts_to_ports_
.begin();
107 it
!= contexts_to_ports_
.end();) {
108 if (it
->second
.erase(port_id
) > 0 && it
->second
.empty())
109 contexts_to_ports_
.erase(it
++);
115 // Gets every port ID that has a reference to |context|.
116 std::set
<int> GetPortsForContext(ScriptContext
* context
) const {
117 auto ports
= contexts_to_ports_
.find(context
);
118 return ports
== contexts_to_ports_
.end() ? std::set
<int>() : ports
->second
;
122 // Maps ScriptContexts to the port IDs that have a reference to it.
123 std::map
<ScriptContext
*, std::set
<int>> contexts_to_ports_
;
125 DISALLOW_COPY_AND_ASSIGN(PortTracker
);
128 base::LazyInstance
<PortTracker
> g_port_tracker
= LAZY_INSTANCE_INITIALIZER
;
130 const char kPortClosedError
[] = "Attempting to use a disconnected port object";
131 const char kReceivingEndDoesntExistError
[] =
132 "Could not establish connection. Receiving end does not exist.";
134 class ExtensionImpl
: public ObjectBackedNativeHandler
{
136 ExtensionImpl(Dispatcher
* dispatcher
, ScriptContext
* context
)
137 : ObjectBackedNativeHandler(context
),
138 dispatcher_(dispatcher
),
139 weak_ptr_factory_(this) {
142 base::Bind(&ExtensionImpl::CloseChannel
, base::Unretained(this)));
145 base::Bind(&ExtensionImpl::PortAddRef
, base::Unretained(this)));
148 base::Bind(&ExtensionImpl::PortRelease
, base::Unretained(this)));
151 base::Bind(&ExtensionImpl::PostMessage
, base::Unretained(this)));
152 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
153 RouteFunction("BindToGC",
154 base::Bind(&ExtensionImpl::BindToGC
, base::Unretained(this)));
156 // Observe |context| so that port references to it can be cleared.
157 context
->AddInvalidationObserver(base::Bind(
158 &ExtensionImpl::OnContextInvalidated
, weak_ptr_factory_
.GetWeakPtr()));
161 ~ExtensionImpl() override
{}
164 void OnContextInvalidated() {
165 for (int port_id
: g_port_tracker
.Get().GetPortsForContext(context()))
166 ReleasePort(port_id
);
169 void ClearPortDataAndNotifyDispatcher(int port_id
) {
170 g_port_tracker
.Get().DeletePort(port_id
);
171 dispatcher_
->ClearPortData(port_id
);
174 // Sends a message along the given channel.
175 void PostMessage(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
176 content::RenderFrame
* renderframe
= context()->GetRenderFrame();
180 // Arguments are (int32 port_id, string message).
181 CHECK(args
.Length() == 2 && args
[0]->IsInt32() && args
[1]->IsString());
183 int port_id
= args
[0].As
<v8::Int32
>()->Value();
184 if (!g_port_tracker
.Get().HasPort(port_id
)) {
185 v8::Local
<v8::String
> error_message
=
186 ToV8StringUnsafe(args
.GetIsolate(), kPortClosedError
);
187 args
.GetIsolate()->ThrowException(v8::Exception::Error(error_message
));
191 renderframe
->Send(new ExtensionHostMsg_PostMessage(
192 renderframe
->GetRoutingID(), port_id
,
193 Message(*v8::String::Utf8Value(args
[1]),
194 blink::WebUserGestureIndicator::isProcessingUserGesture())));
197 // Forcefully disconnects a port.
198 void CloseChannel(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
199 // Arguments are (int32 port_id, boolean notify_browser).
200 CHECK_EQ(2, args
.Length());
201 CHECK(args
[0]->IsInt32());
202 CHECK(args
[1]->IsBoolean());
204 int port_id
= args
[0].As
<v8::Int32
>()->Value();
205 if (!g_port_tracker
.Get().HasPort(port_id
))
208 // Send via the RenderThread because the RenderFrame might be closing.
209 bool notify_browser
= args
[1].As
<v8::Boolean
>()->Value();
210 if (notify_browser
) {
211 content::RenderThread::Get()->Send(
212 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
215 ClearPortDataAndNotifyDispatcher(port_id
);
218 // A new port has been created for a context. This occurs both when script
219 // opens a connection, and when a connection is opened to this script.
220 void PortAddRef(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
221 // Arguments are (int32 port_id).
222 CHECK_EQ(1, args
.Length());
223 CHECK(args
[0]->IsInt32());
225 int port_id
= args
[0].As
<v8::Int32
>()->Value();
226 g_port_tracker
.Get().AddReference(context(), port_id
);
229 // The frame a port lived in has been destroyed. When there are no more
230 // frames with a reference to a given port, we will disconnect it and notify
231 // the other end of the channel.
232 void PortRelease(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
233 // Arguments are (int32 port_id).
234 CHECK(args
.Length() == 1 && args
[0]->IsInt32());
235 ReleasePort(args
[0].As
<v8::Int32
>()->Value());
238 // Releases the reference to |port_id| for this context, and clears all port
239 // data if there are no more references.
240 void ReleasePort(int port_id
) {
241 if (g_port_tracker
.Get().RemoveReference(context(), port_id
) &&
242 !g_port_tracker
.Get().HasPort(port_id
)) {
243 // Send via the RenderThread because the RenderFrame might be closing.
244 content::RenderThread::Get()->Send(
245 new ExtensionHostMsg_CloseChannel(port_id
, std::string()));
246 ClearPortDataAndNotifyDispatcher(port_id
);
250 // void BindToGC(object, callback, port_id)
252 // Binds |callback| to be invoked *sometime after* |object| is garbage
253 // collected. We don't call the method re-entrantly so as to avoid executing
254 // JS in some bizarro undefined mid-GC state, nor do we then call into the
255 // script context if it's been invalidated.
257 // If the script context *is* invalidated in the meantime, as a slight hack,
258 // release the port with ID |port_id| if it's >= 0.
259 void BindToGC(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
260 CHECK(args
.Length() == 3 && args
[0]->IsObject() && args
[1]->IsFunction() &&
262 int port_id
= args
[2].As
<v8::Int32
>()->Value();
263 base::Closure fallback
= base::Bind(&base::DoNothing
);
265 fallback
= base::Bind(&ExtensionImpl::ReleasePort
,
266 weak_ptr_factory_
.GetWeakPtr(), port_id
);
268 // Destroys itself when the object is GC'd or context is invalidated.
269 new GCCallback(context(), args
[0].As
<v8::Object
>(),
270 args
[1].As
<v8::Function
>(), fallback
);
273 // Dispatcher handle. Not owned.
274 Dispatcher
* dispatcher_
;
276 base::WeakPtrFactory
<ExtensionImpl
> weak_ptr_factory_
;
279 void DispatchOnConnectToScriptContext(
281 const std::string
& channel_name
,
282 const ExtensionMsg_TabConnectionInfo
* source
,
283 const ExtensionMsg_ExternalConnectionInfo
& info
,
284 const std::string
& tls_channel_id
,
286 ScriptContext
* script_context
) {
287 // Only dispatch the events if this is the requested target frame (0 = main
288 // frame; positive = child frame).
289 content::RenderFrame
* renderframe
= script_context
->GetRenderFrame();
290 if (info
.target_frame_id
== 0 && renderframe
->GetWebFrame()->parent() != NULL
)
292 if (info
.target_frame_id
> 0 &&
293 renderframe
->GetRoutingID() != info
.target_frame_id
)
296 // Bandaid fix for crbug.com/520303.
297 // TODO(rdevlin.cronin): Fix this properly by routing messages to the correct
298 // RenderFrame from the browser (same with |target_frame_id| in fact).
299 if (info
.target_tab_id
!= -1 &&
300 info
.target_tab_id
!= ExtensionFrameHelper::Get(renderframe
)->tab_id()) {
304 v8::Isolate
* isolate
= script_context
->isolate();
305 v8::HandleScope
handle_scope(isolate
);
307 scoped_ptr
<V8ValueConverter
> converter(V8ValueConverter::create());
309 const std::string
& source_url_spec
= info
.source_url
.spec();
310 std::string target_extension_id
= script_context
->GetExtensionID();
311 const Extension
* extension
= script_context
->extension();
313 v8::Local
<v8::Value
> tab
= v8::Null(isolate
);
314 v8::Local
<v8::Value
> tls_channel_id_value
= v8::Undefined(isolate
);
315 v8::Local
<v8::Value
> guest_process_id
= v8::Undefined(isolate
);
316 v8::Local
<v8::Value
> guest_render_frame_routing_id
= v8::Undefined(isolate
);
319 if (!source
->tab
.empty() && !extension
->is_platform_app())
320 tab
= converter
->ToV8Value(&source
->tab
, script_context
->v8_context());
322 ExternallyConnectableInfo
* externally_connectable
=
323 ExternallyConnectableInfo::Get(extension
);
324 if (externally_connectable
&&
325 externally_connectable
->accepts_tls_channel_id
) {
326 v8::Local
<v8::String
> v8_tls_channel_id
;
327 if (ToV8String(isolate
, tls_channel_id
.c_str(), &v8_tls_channel_id
))
328 tls_channel_id_value
= v8_tls_channel_id
;
331 if (info
.guest_process_id
!= content::ChildProcessHost::kInvalidUniqueID
) {
332 guest_process_id
= v8::Integer::New(isolate
, info
.guest_process_id
);
333 guest_render_frame_routing_id
=
334 v8::Integer::New(isolate
, info
.guest_render_frame_routing_id
);
338 v8::Local
<v8::String
> v8_channel_name
;
339 v8::Local
<v8::String
> v8_source_id
;
340 v8::Local
<v8::String
> v8_target_extension_id
;
341 v8::Local
<v8::String
> v8_source_url_spec
;
342 if (!ToV8String(isolate
, channel_name
.c_str(), &v8_channel_name
) ||
343 !ToV8String(isolate
, info
.source_id
.c_str(), &v8_source_id
) ||
344 !ToV8String(isolate
, target_extension_id
.c_str(),
345 &v8_target_extension_id
) ||
346 !ToV8String(isolate
, source_url_spec
.c_str(), &v8_source_url_spec
)) {
347 NOTREACHED() << "dispatchOnConnect() passed non-string argument";
351 v8::Local
<v8::Value
> arguments
[] = {
353 v8::Integer::New(isolate
, target_port_id
),
359 v8::Integer::New(isolate
, source
->frame_id
),
362 // guestRenderFrameRoutingId
363 guest_render_frame_routing_id
,
367 v8_target_extension_id
,
371 tls_channel_id_value
,
374 v8::Local
<v8::Value
> retval
=
375 script_context
->module_system()->CallModuleMethod(
376 "messaging", "dispatchOnConnect", arraysize(arguments
), arguments
);
378 if (!IsEmptyOrUndefied(retval
)) {
379 CHECK(retval
->IsBoolean());
380 *port_created
|= retval
.As
<v8::Boolean
>()->Value();
382 LOG(ERROR
) << "Empty return value from dispatchOnConnect.";
386 void DeliverMessageToScriptContext(const Message
& message
,
388 ScriptContext
* script_context
) {
389 v8::Isolate
* isolate
= script_context
->isolate();
390 v8::HandleScope
handle_scope(isolate
);
392 // Check to see whether the context has this port before bothering to create
394 v8::Local
<v8::Value
> port_id_handle
=
395 v8::Integer::New(isolate
, target_port_id
);
396 v8::Local
<v8::Value
> has_port
=
397 script_context
->module_system()->CallModuleMethod("messaging", "hasPort",
399 // Could be empty/undefined if an exception was thrown.
400 // TODO(kalman): Should this be built into CallModuleMethod?
401 if (IsEmptyOrUndefied(has_port
))
403 CHECK(has_port
->IsBoolean());
404 if (!has_port
.As
<v8::Boolean
>()->Value())
407 v8::Local
<v8::String
> v8_data
;
408 if (!ToV8String(isolate
, message
.data
.c_str(), &v8_data
))
410 std::vector
<v8::Local
<v8::Value
>> arguments
;
411 arguments
.push_back(v8_data
);
412 arguments
.push_back(port_id_handle
);
414 scoped_ptr
<blink::WebScopedUserGesture
> web_user_gesture
;
415 scoped_ptr
<blink::WebScopedWindowFocusAllowedIndicator
> allow_window_focus
;
416 if (message
.user_gesture
) {
417 web_user_gesture
.reset(new blink::WebScopedUserGesture
);
419 if (script_context
->web_frame()) {
420 blink::WebDocument document
= script_context
->web_frame()->document();
421 allow_window_focus
.reset(new blink::WebScopedWindowFocusAllowedIndicator(
426 script_context
->module_system()->CallModuleMethod(
427 "messaging", "dispatchOnMessage", &arguments
);
430 void DispatchOnDisconnectToScriptContext(int port_id
,
431 const std::string
& error_message
,
432 ScriptContext
* script_context
) {
433 v8::Isolate
* isolate
= script_context
->isolate();
434 v8::HandleScope
handle_scope(isolate
);
436 std::vector
<v8::Local
<v8::Value
>> arguments
;
437 arguments
.push_back(v8::Integer::New(isolate
, port_id
));
438 v8::Local
<v8::String
> v8_error_message
;
439 if (!error_message
.empty())
440 ToV8String(isolate
, error_message
.c_str(), &v8_error_message
);
441 if (!v8_error_message
.IsEmpty()) {
442 arguments
.push_back(v8_error_message
);
444 arguments
.push_back(v8::Null(isolate
));
447 script_context
->module_system()->CallModuleMethod(
448 "messaging", "dispatchOnDisconnect", &arguments
);
453 ObjectBackedNativeHandler
* MessagingBindings::Get(Dispatcher
* dispatcher
,
454 ScriptContext
* context
) {
455 return new ExtensionImpl(dispatcher
, context
);
459 void MessagingBindings::DispatchOnConnect(
460 const ScriptContextSet
& context_set
,
462 const std::string
& channel_name
,
463 const ExtensionMsg_TabConnectionInfo
& source
,
464 const ExtensionMsg_ExternalConnectionInfo
& info
,
465 const std::string
& tls_channel_id
,
466 content::RenderFrame
* restrict_to_render_frame
) {
467 bool port_created
= false;
469 info
.target_id
, restrict_to_render_frame
,
470 base::Bind(&DispatchOnConnectToScriptContext
, target_port_id
,
471 channel_name
, &source
, info
, tls_channel_id
, &port_created
));
473 // If we didn't create a port, notify the other end of the channel (treat it
476 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
477 target_port_id
, kReceivingEndDoesntExistError
));
482 void MessagingBindings::DeliverMessage(
483 const ScriptContextSet
& context_set
,
485 const Message
& message
,
486 content::RenderFrame
* restrict_to_render_frame
) {
488 restrict_to_render_frame
,
489 base::Bind(&DeliverMessageToScriptContext
, message
, target_port_id
));
493 void MessagingBindings::DispatchOnDisconnect(
494 const ScriptContextSet
& context_set
,
496 const std::string
& error_message
,
497 content::RenderFrame
* restrict_to_render_frame
) {
499 restrict_to_render_frame
,
500 base::Bind(&DispatchOnDisconnectToScriptContext
, port_id
, error_message
));
503 } // namespace extensions