Remove unused parameter.
[chromium-blink-merge.git] / extensions / renderer / messaging_bindings.cc
blobd379bacd1a77f43a69b8abaaae497dec3543165b
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"
7 #include <map>
8 #include <string>
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/WebLocalFrame.h"
30 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
31 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
32 #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h"
33 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
34 #include "v8/include/v8.h"
36 // Message passing API example (in a content script):
37 // var extension =
38 // new chrome.Extension('00123456789abcdef0123456789abcdef0123456');
39 // var port = runtime.connect();
40 // port.postMessage('Can you hear me now?');
41 // port.onmessage.addListener(function(msg, port) {
42 // alert('response=' + msg);
43 // port.postMessage('I got your reponse');
44 // });
46 using content::RenderThread;
47 using content::V8ValueConverter;
49 namespace extensions {
51 namespace {
53 struct ExtensionData {
54 struct PortData {
55 int ref_count; // how many contexts have a handle to this port
56 PortData() : ref_count(0) {}
58 std::map<int, PortData> ports; // port ID -> data
61 base::LazyInstance<ExtensionData> g_extension_data = LAZY_INSTANCE_INITIALIZER;
63 bool HasPortData(int port_id) {
64 return g_extension_data.Get().ports.find(port_id) !=
65 g_extension_data.Get().ports.end();
68 ExtensionData::PortData& GetPortData(int port_id) {
69 return g_extension_data.Get().ports[port_id];
72 void ClearPortData(int port_id) {
73 g_extension_data.Get().ports.erase(port_id);
76 const char kPortClosedError[] = "Attempting to use a disconnected port object";
77 const char kReceivingEndDoesntExistError[] =
78 "Could not establish connection. Receiving end does not exist.";
80 class ExtensionImpl : public ObjectBackedNativeHandler {
81 public:
82 ExtensionImpl(Dispatcher* dispatcher, ScriptContext* context)
83 : ObjectBackedNativeHandler(context), dispatcher_(dispatcher) {
84 RouteFunction(
85 "CloseChannel",
86 base::Bind(&ExtensionImpl::CloseChannel, base::Unretained(this)));
87 RouteFunction(
88 "PortAddRef",
89 base::Bind(&ExtensionImpl::PortAddRef, base::Unretained(this)));
90 RouteFunction(
91 "PortRelease",
92 base::Bind(&ExtensionImpl::PortRelease, base::Unretained(this)));
93 RouteFunction(
94 "PostMessage",
95 base::Bind(&ExtensionImpl::PostMessage, base::Unretained(this)));
96 // TODO(fsamuel, kalman): Move BindToGC out of messaging natives.
97 RouteFunction("BindToGC",
98 base::Bind(&ExtensionImpl::BindToGC, base::Unretained(this)));
101 ~ExtensionImpl() override {}
103 private:
104 void ClearPortDataAndNotifyDispatcher(int port_id) {
105 ClearPortData(port_id);
106 dispatcher_->ClearPortData(port_id);
109 // Sends a message along the given channel.
110 void PostMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
111 content::RenderFrame* renderframe = context()->GetRenderFrame();
112 if (!renderframe)
113 return;
115 // Arguments are (int32 port_id, string message).
116 CHECK(args.Length() == 2 && args[0]->IsInt32() && args[1]->IsString());
118 int port_id = args[0]->Int32Value();
119 if (!HasPortData(port_id)) {
120 args.GetIsolate()->ThrowException(v8::Exception::Error(
121 v8::String::NewFromUtf8(args.GetIsolate(), kPortClosedError)));
122 return;
125 renderframe->Send(new ExtensionHostMsg_PostMessage(
126 renderframe->GetRoutingID(), port_id,
127 Message(*v8::String::Utf8Value(args[1]),
128 blink::WebUserGestureIndicator::isProcessingUserGesture())));
131 // Forcefully disconnects a port.
132 void CloseChannel(const v8::FunctionCallbackInfo<v8::Value>& args) {
133 // Arguments are (int32 port_id, boolean notify_browser).
134 CHECK_EQ(2, args.Length());
135 CHECK(args[0]->IsInt32());
136 CHECK(args[1]->IsBoolean());
138 int port_id = args[0]->Int32Value();
139 if (!HasPortData(port_id))
140 return;
142 // Send via the RenderThread because the RenderFrame might be closing.
143 bool notify_browser = args[1]->BooleanValue();
144 if (notify_browser) {
145 content::RenderThread::Get()->Send(
146 new ExtensionHostMsg_CloseChannel(port_id, std::string()));
149 ClearPortDataAndNotifyDispatcher(port_id);
152 // A new port has been created for a context. This occurs both when script
153 // opens a connection, and when a connection is opened to this script.
154 void PortAddRef(const v8::FunctionCallbackInfo<v8::Value>& args) {
155 // Arguments are (int32 port_id).
156 CHECK_EQ(1, args.Length());
157 CHECK(args[0]->IsInt32());
159 int port_id = args[0]->Int32Value();
160 ++GetPortData(port_id).ref_count;
163 // The frame a port lived in has been destroyed. When there are no more
164 // frames with a reference to a given port, we will disconnect it and notify
165 // the other end of the channel.
166 void PortRelease(const v8::FunctionCallbackInfo<v8::Value>& args) {
167 // Arguments are (int32 port_id).
168 CHECK_EQ(1, args.Length());
169 CHECK(args[0]->IsInt32());
171 int port_id = args[0]->Int32Value();
172 if (HasPortData(port_id) && --GetPortData(port_id).ref_count == 0) {
173 // Send via the RenderThread because the RenderFrame might be closing.
174 content::RenderThread::Get()->Send(
175 new ExtensionHostMsg_CloseChannel(port_id, std::string()));
176 ClearPortDataAndNotifyDispatcher(port_id);
180 // Holds a |callback| to run sometime after |object| is GC'ed. |callback| will
181 // not be executed re-entrantly to avoid running JS in an unexpected state.
182 class GCCallback {
183 public:
184 static void Bind(v8::Handle<v8::Object> object,
185 v8::Handle<v8::Function> callback,
186 v8::Isolate* isolate) {
187 GCCallback* cb = new GCCallback(object, callback, isolate);
188 cb->object_.SetWeak(cb, NearDeathCallback);
191 private:
192 static void NearDeathCallback(
193 const v8::WeakCallbackData<v8::Object, GCCallback>& data) {
194 // v8 says we need to explicitly reset weak handles from their callbacks.
195 // It's not implicit as one might expect.
196 data.GetParameter()->object_.Reset();
197 base::MessageLoop::current()->PostTask(
198 FROM_HERE,
199 base::Bind(&GCCallback::RunCallback,
200 base::Owned(data.GetParameter())));
203 GCCallback(v8::Handle<v8::Object> object,
204 v8::Handle<v8::Function> callback,
205 v8::Isolate* isolate)
206 : object_(isolate, object),
207 callback_(isolate, callback),
208 isolate_(isolate) {}
210 void RunCallback() {
211 v8::HandleScope handle_scope(isolate_);
212 v8::Handle<v8::Function> callback =
213 v8::Local<v8::Function>::New(isolate_, callback_);
214 v8::Handle<v8::Context> context = callback->CreationContext();
215 if (context.IsEmpty())
216 return;
217 v8::Context::Scope context_scope(context);
218 blink::WebScopedMicrotaskSuppression suppression;
219 callback->Call(context->Global(), 0, NULL);
222 v8::Global<v8::Object> object_;
223 v8::Global<v8::Function> callback_;
224 v8::Isolate* isolate_;
226 DISALLOW_COPY_AND_ASSIGN(GCCallback);
229 // void BindToGC(object, callback)
231 // Binds |callback| to be invoked *sometime after* |object| is garbage
232 // collected. We don't call the method re-entrantly so as to avoid executing
233 // JS in some bizarro undefined mid-GC state.
234 void BindToGC(const v8::FunctionCallbackInfo<v8::Value>& args) {
235 CHECK(args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction());
236 GCCallback::Bind(args[0].As<v8::Object>(),
237 args[1].As<v8::Function>(),
238 args.GetIsolate());
241 // Dispatcher handle. Not owned.
242 Dispatcher* dispatcher_;
245 void DispatchOnConnectToScriptContext(
246 int target_port_id,
247 const std::string& channel_name,
248 const ExtensionMsg_TabConnectionInfo* source,
249 const ExtensionMsg_ExternalConnectionInfo& info,
250 const std::string& tls_channel_id,
251 bool* port_created,
252 ScriptContext* script_context) {
253 // Only dispatch the events if this is the requested target frame (0 = main
254 // frame; positive = child frame).
255 content::RenderFrame* renderframe = script_context->GetRenderFrame();
256 if (info.target_frame_id == 0 && renderframe->GetWebFrame()->parent() != NULL)
257 return;
258 if (info.target_frame_id > 0 &&
259 renderframe->GetRoutingID() != info.target_frame_id)
260 return;
261 v8::Isolate* isolate = script_context->isolate();
262 v8::HandleScope handle_scope(isolate);
264 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
266 const std::string& source_url_spec = info.source_url.spec();
267 std::string target_extension_id = script_context->GetExtensionID();
268 const Extension* extension = script_context->extension();
270 v8::Handle<v8::Value> tab = v8::Null(isolate);
271 v8::Handle<v8::Value> tls_channel_id_value = v8::Undefined(isolate);
272 v8::Handle<v8::Value> guest_process_id = v8::Undefined(isolate);
274 if (extension) {
275 if (!source->tab.empty() && !extension->is_platform_app())
276 tab = converter->ToV8Value(&source->tab, script_context->v8_context());
278 ExternallyConnectableInfo* externally_connectable =
279 ExternallyConnectableInfo::Get(extension);
280 if (externally_connectable &&
281 externally_connectable->accepts_tls_channel_id) {
282 tls_channel_id_value = v8::String::NewFromUtf8(isolate,
283 tls_channel_id.c_str(),
284 v8::String::kNormalString,
285 tls_channel_id.size());
288 if (info.guest_process_id != content::ChildProcessHost::kInvalidUniqueID)
289 guest_process_id = v8::Integer::New(isolate, info.guest_process_id);
292 v8::Handle<v8::Value> arguments[] = {
293 // portId
294 v8::Integer::New(isolate, target_port_id),
295 // channelName
296 v8::String::NewFromUtf8(isolate,
297 channel_name.c_str(),
298 v8::String::kNormalString,
299 channel_name.size()),
300 // sourceTab
301 tab,
302 // source_frame_id
303 v8::Integer::New(isolate, source->frame_id),
304 // guestProcessId
305 guest_process_id,
306 // sourceExtensionId
307 v8::String::NewFromUtf8(isolate,
308 info.source_id.c_str(),
309 v8::String::kNormalString,
310 info.source_id.size()),
311 // targetExtensionId
312 v8::String::NewFromUtf8(isolate,
313 target_extension_id.c_str(),
314 v8::String::kNormalString,
315 target_extension_id.size()),
316 // sourceUrl
317 v8::String::NewFromUtf8(isolate,
318 source_url_spec.c_str(),
319 v8::String::kNormalString,
320 source_url_spec.size()),
321 // tlsChannelId
322 tls_channel_id_value,
325 v8::Handle<v8::Value> retval =
326 script_context->module_system()->CallModuleMethod(
327 "messaging", "dispatchOnConnect", arraysize(arguments), arguments);
329 if (!retval.IsEmpty()) {
330 CHECK(retval->IsBoolean());
331 *port_created |= retval->BooleanValue();
332 } else {
333 LOG(ERROR) << "Empty return value from dispatchOnConnect.";
337 void DeliverMessageToScriptContext(const std::string& message_data,
338 int target_port_id,
339 ScriptContext* script_context) {
340 v8::Isolate* isolate = script_context->isolate();
341 v8::HandleScope handle_scope(isolate);
343 // Check to see whether the context has this port before bothering to create
344 // the message.
345 v8::Handle<v8::Value> port_id_handle =
346 v8::Integer::New(isolate, target_port_id);
347 v8::Handle<v8::Value> has_port =
348 script_context->module_system()->CallModuleMethod(
349 "messaging", "hasPort", 1, &port_id_handle);
351 CHECK(!has_port.IsEmpty());
352 if (!has_port->BooleanValue())
353 return;
355 std::vector<v8::Handle<v8::Value> > arguments;
356 arguments.push_back(v8::String::NewFromUtf8(isolate,
357 message_data.c_str(),
358 v8::String::kNormalString,
359 message_data.size()));
360 arguments.push_back(port_id_handle);
361 script_context->module_system()->CallModuleMethod(
362 "messaging", "dispatchOnMessage", &arguments);
365 void DispatchOnDisconnectToScriptContext(int port_id,
366 const std::string& error_message,
367 ScriptContext* script_context) {
368 v8::Isolate* isolate = script_context->isolate();
369 v8::HandleScope handle_scope(isolate);
371 std::vector<v8::Handle<v8::Value> > arguments;
372 arguments.push_back(v8::Integer::New(isolate, port_id));
373 if (!error_message.empty()) {
374 arguments.push_back(
375 v8::String::NewFromUtf8(isolate, error_message.c_str()));
376 } else {
377 arguments.push_back(v8::Null(isolate));
380 script_context->module_system()->CallModuleMethod(
381 "messaging", "dispatchOnDisconnect", &arguments);
384 } // namespace
386 ObjectBackedNativeHandler* MessagingBindings::Get(Dispatcher* dispatcher,
387 ScriptContext* context) {
388 return new ExtensionImpl(dispatcher, context);
391 // static
392 void MessagingBindings::DispatchOnConnect(
393 const ScriptContextSet& context_set,
394 int target_port_id,
395 const std::string& channel_name,
396 const ExtensionMsg_TabConnectionInfo& source,
397 const ExtensionMsg_ExternalConnectionInfo& info,
398 const std::string& tls_channel_id,
399 content::RenderFrame* restrict_to_render_frame) {
400 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
401 content::RenderView* restrict_to_render_view =
402 restrict_to_render_frame ? restrict_to_render_frame->GetRenderView()
403 : NULL;
404 bool port_created = false;
405 context_set.ForEach(
406 info.target_id, restrict_to_render_view,
407 base::Bind(&DispatchOnConnectToScriptContext, target_port_id,
408 channel_name, &source, info, tls_channel_id, &port_created));
410 // If we didn't create a port, notify the other end of the channel (treat it
411 // as a disconnect).
412 if (!port_created) {
413 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
414 target_port_id, kReceivingEndDoesntExistError));
418 // static
419 void MessagingBindings::DeliverMessage(
420 const ScriptContextSet& context_set,
421 int target_port_id,
422 const Message& message,
423 content::RenderFrame* restrict_to_render_frame) {
424 scoped_ptr<blink::WebScopedUserGesture> web_user_gesture;
425 scoped_ptr<blink::WebScopedWindowFocusAllowedIndicator> allow_window_focus;
426 if (message.user_gesture) {
427 web_user_gesture.reset(new blink::WebScopedUserGesture);
428 allow_window_focus.reset(new blink::WebScopedWindowFocusAllowedIndicator);
431 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
432 content::RenderView* restrict_to_render_view =
433 restrict_to_render_frame ? restrict_to_render_frame->GetRenderView()
434 : NULL;
435 context_set.ForEach(
436 restrict_to_render_view,
437 base::Bind(&DeliverMessageToScriptContext, message.data, target_port_id));
440 // static
441 void MessagingBindings::DispatchOnDisconnect(
442 const ScriptContextSet& context_set,
443 int port_id,
444 const std::string& error_message,
445 content::RenderFrame* restrict_to_render_frame) {
446 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
447 content::RenderView* restrict_to_render_view =
448 restrict_to_render_frame ? restrict_to_render_frame->GetRenderView()
449 : NULL;
450 context_set.ForEach(
451 restrict_to_render_view,
452 base::Bind(&DispatchOnDisconnectToScriptContext, port_id, error_message));
455 } // namespace extensions