Reland the ULONG -> SIZE_T change from 317177
[chromium-blink-merge.git] / extensions / renderer / messaging_bindings.cc
blob452f2e71ed175d7c49f5f32bc973b2ac2ebb6b4f
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/scoped_persistent.h"
28 #include "extensions/renderer/script_context.h"
29 #include "extensions/renderer/script_context_set.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):
38 // var extension =
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');
45 // });
47 using content::RenderThread;
48 using content::V8ValueConverter;
50 namespace extensions {
52 namespace {
54 struct ExtensionData {
55 struct PortData {
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 {
82 public:
83 ExtensionImpl(Dispatcher* dispatcher, ScriptContext* context)
84 : ObjectBackedNativeHandler(context), dispatcher_(dispatcher) {
85 RouteFunction(
86 "CloseChannel",
87 base::Bind(&ExtensionImpl::CloseChannel, base::Unretained(this)));
88 RouteFunction(
89 "PortAddRef",
90 base::Bind(&ExtensionImpl::PortAddRef, base::Unretained(this)));
91 RouteFunction(
92 "PortRelease",
93 base::Bind(&ExtensionImpl::PortRelease, base::Unretained(this)));
94 RouteFunction(
95 "PostMessage",
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 {}
104 private:
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();
113 if (!renderframe)
114 return;
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)));
123 return;
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))
141 return;
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.
183 class GCCallback {
184 public:
185 static void Bind(v8::Handle<v8::Object> object,
186 v8::Handle<v8::Function> callback,
187 v8::Isolate* isolate) {
188 GCCallback* cb = new GCCallback(object, callback, isolate);
189 cb->object_.SetWeak(cb, NearDeathCallback);
192 private:
193 static void NearDeathCallback(
194 const v8::WeakCallbackData<v8::Object, GCCallback>& data) {
195 // v8 says we need to explicitly reset weak handles from their callbacks.
196 // It's not implicit as one might expect.
197 data.GetParameter()->object_.reset();
198 base::MessageLoop::current()->PostTask(
199 FROM_HERE,
200 base::Bind(&GCCallback::RunCallback,
201 base::Owned(data.GetParameter())));
204 GCCallback(v8::Handle<v8::Object> object,
205 v8::Handle<v8::Function> callback,
206 v8::Isolate* isolate)
207 : object_(object), callback_(callback), isolate_(isolate) {}
209 void RunCallback() {
210 v8::HandleScope handle_scope(isolate_);
211 v8::Handle<v8::Function> callback = callback_.NewHandle(isolate_);
212 v8::Handle<v8::Context> context = callback->CreationContext();
213 if (context.IsEmpty())
214 return;
215 v8::Context::Scope context_scope(context);
216 blink::WebScopedMicrotaskSuppression suppression;
217 callback->Call(context->Global(), 0, NULL);
220 ScopedPersistent<v8::Object> object_;
221 ScopedPersistent<v8::Function> callback_;
222 v8::Isolate* isolate_;
224 DISALLOW_COPY_AND_ASSIGN(GCCallback);
227 // void BindToGC(object, callback)
229 // Binds |callback| to be invoked *sometime after* |object| is garbage
230 // collected. We don't call the method re-entrantly so as to avoid executing
231 // JS in some bizarro undefined mid-GC state.
232 void BindToGC(const v8::FunctionCallbackInfo<v8::Value>& args) {
233 CHECK(args.Length() == 2 && args[0]->IsObject() && args[1]->IsFunction());
234 GCCallback::Bind(args[0].As<v8::Object>(),
235 args[1].As<v8::Function>(),
236 args.GetIsolate());
239 // Dispatcher handle. Not owned.
240 Dispatcher* dispatcher_;
243 void DispatchOnConnectToScriptContext(
244 int target_port_id,
245 const std::string& channel_name,
246 const ExtensionMsg_TabConnectionInfo* source,
247 const ExtensionMsg_ExternalConnectionInfo& info,
248 const std::string& tls_channel_id,
249 bool* port_created,
250 ScriptContext* script_context) {
251 // Only dispatch the events if this is the requested target frame (0 = main
252 // frame; positive = child frame).
253 content::RenderFrame* renderframe = script_context->GetRenderFrame();
254 if (info.target_frame_id == 0 && renderframe->GetWebFrame()->parent() != NULL)
255 return;
256 if (info.target_frame_id > 0 &&
257 renderframe->GetRoutingID() != info.target_frame_id)
258 return;
259 v8::Isolate* isolate = script_context->isolate();
260 v8::HandleScope handle_scope(isolate);
262 scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
264 const std::string& source_url_spec = info.source_url.spec();
265 std::string target_extension_id = script_context->GetExtensionID();
266 const Extension* extension = script_context->extension();
268 v8::Handle<v8::Value> tab = v8::Null(isolate);
269 v8::Handle<v8::Value> tls_channel_id_value = v8::Undefined(isolate);
270 v8::Handle<v8::Value> guest_process_id = v8::Undefined(isolate);
272 if (extension) {
273 if (!source->tab.empty() && !extension->is_platform_app())
274 tab = converter->ToV8Value(&source->tab, script_context->v8_context());
276 ExternallyConnectableInfo* externally_connectable =
277 ExternallyConnectableInfo::Get(extension);
278 if (externally_connectable &&
279 externally_connectable->accepts_tls_channel_id) {
280 tls_channel_id_value = v8::String::NewFromUtf8(isolate,
281 tls_channel_id.c_str(),
282 v8::String::kNormalString,
283 tls_channel_id.size());
286 if (info.guest_process_id != content::ChildProcessHost::kInvalidUniqueID)
287 guest_process_id = v8::Integer::New(isolate, info.guest_process_id);
290 v8::Handle<v8::Value> arguments[] = {
291 // portId
292 v8::Integer::New(isolate, target_port_id),
293 // channelName
294 v8::String::NewFromUtf8(isolate,
295 channel_name.c_str(),
296 v8::String::kNormalString,
297 channel_name.size()),
298 // sourceTab
299 tab,
300 // source_frame_id
301 v8::Integer::New(isolate, source->frame_id),
302 // guestProcessId
303 guest_process_id,
304 // sourceExtensionId
305 v8::String::NewFromUtf8(isolate,
306 info.source_id.c_str(),
307 v8::String::kNormalString,
308 info.source_id.size()),
309 // targetExtensionId
310 v8::String::NewFromUtf8(isolate,
311 target_extension_id.c_str(),
312 v8::String::kNormalString,
313 target_extension_id.size()),
314 // sourceUrl
315 v8::String::NewFromUtf8(isolate,
316 source_url_spec.c_str(),
317 v8::String::kNormalString,
318 source_url_spec.size()),
319 // tlsChannelId
320 tls_channel_id_value,
323 v8::Handle<v8::Value> retval =
324 script_context->module_system()->CallModuleMethod(
325 "messaging", "dispatchOnConnect", arraysize(arguments), arguments);
327 if (!retval.IsEmpty()) {
328 CHECK(retval->IsBoolean());
329 *port_created |= retval->BooleanValue();
330 } else {
331 LOG(ERROR) << "Empty return value from dispatchOnConnect.";
335 void DeliverMessageToScriptContext(const std::string& message_data,
336 int target_port_id,
337 ScriptContext* script_context) {
338 v8::Isolate* isolate = script_context->isolate();
339 v8::HandleScope handle_scope(isolate);
341 // Check to see whether the context has this port before bothering to create
342 // the message.
343 v8::Handle<v8::Value> port_id_handle =
344 v8::Integer::New(isolate, target_port_id);
345 v8::Handle<v8::Value> has_port =
346 script_context->module_system()->CallModuleMethod(
347 "messaging", "hasPort", 1, &port_id_handle);
349 CHECK(!has_port.IsEmpty());
350 if (!has_port->BooleanValue())
351 return;
353 std::vector<v8::Handle<v8::Value> > arguments;
354 arguments.push_back(v8::String::NewFromUtf8(isolate,
355 message_data.c_str(),
356 v8::String::kNormalString,
357 message_data.size()));
358 arguments.push_back(port_id_handle);
359 script_context->module_system()->CallModuleMethod(
360 "messaging", "dispatchOnMessage", &arguments);
363 void DispatchOnDisconnectToScriptContext(int port_id,
364 const std::string& error_message,
365 ScriptContext* script_context) {
366 v8::Isolate* isolate = script_context->isolate();
367 v8::HandleScope handle_scope(isolate);
369 std::vector<v8::Handle<v8::Value> > arguments;
370 arguments.push_back(v8::Integer::New(isolate, port_id));
371 if (!error_message.empty()) {
372 arguments.push_back(
373 v8::String::NewFromUtf8(isolate, error_message.c_str()));
374 } else {
375 arguments.push_back(v8::Null(isolate));
378 script_context->module_system()->CallModuleMethod(
379 "messaging", "dispatchOnDisconnect", &arguments);
382 } // namespace
384 ObjectBackedNativeHandler* MessagingBindings::Get(Dispatcher* dispatcher,
385 ScriptContext* context) {
386 return new ExtensionImpl(dispatcher, context);
389 // static
390 void MessagingBindings::DispatchOnConnect(
391 const ScriptContextSet& context_set,
392 int target_port_id,
393 const std::string& channel_name,
394 const ExtensionMsg_TabConnectionInfo& source,
395 const ExtensionMsg_ExternalConnectionInfo& info,
396 const std::string& tls_channel_id,
397 content::RenderFrame* restrict_to_render_frame) {
398 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
399 content::RenderView* restrict_to_render_view =
400 restrict_to_render_frame ? restrict_to_render_frame->GetRenderView()
401 : NULL;
402 bool port_created = false;
403 context_set.ForEach(
404 info.target_id, restrict_to_render_view,
405 base::Bind(&DispatchOnConnectToScriptContext, target_port_id,
406 channel_name, &source, info, tls_channel_id, &port_created));
408 // If we didn't create a port, notify the other end of the channel (treat it
409 // as a disconnect).
410 if (!port_created) {
411 content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseChannel(
412 target_port_id, kReceivingEndDoesntExistError));
416 // static
417 void MessagingBindings::DeliverMessage(
418 const ScriptContextSet& context_set,
419 int target_port_id,
420 const Message& message,
421 content::RenderFrame* restrict_to_render_frame) {
422 scoped_ptr<blink::WebScopedUserGesture> web_user_gesture;
423 scoped_ptr<blink::WebScopedWindowFocusAllowedIndicator> allow_window_focus;
424 if (message.user_gesture) {
425 web_user_gesture.reset(new blink::WebScopedUserGesture);
426 allow_window_focus.reset(new blink::WebScopedWindowFocusAllowedIndicator);
429 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
430 content::RenderView* restrict_to_render_view =
431 restrict_to_render_frame ? restrict_to_render_frame->GetRenderView()
432 : NULL;
433 context_set.ForEach(
434 restrict_to_render_view,
435 base::Bind(&DeliverMessageToScriptContext, message.data, target_port_id));
438 // static
439 void MessagingBindings::DispatchOnDisconnect(
440 const ScriptContextSet& context_set,
441 int port_id,
442 const std::string& error_message,
443 content::RenderFrame* restrict_to_render_frame) {
444 // TODO(robwu): ScriptContextSet.ForEach should accept RenderFrame*.
445 content::RenderView* restrict_to_render_view =
446 restrict_to_render_frame ? restrict_to_render_frame->GetRenderView()
447 : NULL;
448 context_set.ForEach(
449 restrict_to_render_view,
450 base::Bind(&DispatchOnDisconnectToScriptContext, port_id, error_message));
453 } // namespace extensions