1 // Copyright (c) 2012 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 "content/renderer/pepper/message_channel.h"
10 #include "base/bind.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "content/renderer/pepper/host_array_buffer_var.h"
14 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
15 #include "content/renderer/pepper/pepper_try_catch.h"
16 #include "content/renderer/pepper/plugin_module.h"
17 #include "content/renderer/pepper/plugin_object.h"
18 #include "gin/arguments.h"
19 #include "gin/converter.h"
20 #include "gin/function_template.h"
21 #include "gin/object_template_builder.h"
22 #include "gin/public/gin_embedders.h"
23 #include "ppapi/shared_impl/ppapi_globals.h"
24 #include "ppapi/shared_impl/scoped_pp_var.h"
25 #include "ppapi/shared_impl/var.h"
26 #include "ppapi/shared_impl/var_tracker.h"
27 #include "third_party/WebKit/public/web/WebBindings.h"
28 #include "third_party/WebKit/public/web/WebDocument.h"
29 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
30 #include "third_party/WebKit/public/web/WebElement.h"
31 #include "third_party/WebKit/public/web/WebLocalFrame.h"
32 #include "third_party/WebKit/public/web/WebNode.h"
33 #include "third_party/WebKit/public/web/WebPluginContainer.h"
34 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
35 #include "v8/include/v8.h"
37 using ppapi::ArrayBufferVar
;
38 using ppapi::PpapiGlobals
;
39 using ppapi::ScopedPPVar
;
40 using ppapi::StringVar
;
41 using blink::WebBindings
;
42 using blink::WebElement
;
43 using blink::WebDOMEvent
;
44 using blink::WebDOMMessageEvent
;
45 using blink::WebPluginContainer
;
46 using blink::WebSerializedScriptValue
;
52 const char kPostMessage
[] = "postMessage";
53 const char kPostMessageAndAwaitResponse
[] = "postMessageAndAwaitResponse";
54 const char kV8ToVarConversionError
[] =
55 "Failed to convert a PostMessage "
56 "argument from a JavaScript value to a PP_Var. It may have cycles or be of "
57 "an unsupported type.";
58 const char kVarToV8ConversionError
[] =
59 "Failed to convert a PostMessage "
60 "argument from a PP_Var to a Javascript value. It may have cycles or be of "
61 "an unsupported type.";
65 // MessageChannel --------------------------------------------------------------
66 struct MessageChannel::VarConversionResult
{
67 VarConversionResult() : success_(false), conversion_completed_(false) {}
68 void ConversionCompleted(const ScopedPPVar
& var
,
70 conversion_completed_
= true;
74 const ScopedPPVar
& var() const { return var_
; }
75 bool success() const { return success_
; }
76 bool conversion_completed() const { return conversion_completed_
; }
81 bool conversion_completed_
;
85 gin::WrapperInfo
MessageChannel::kWrapperInfo
= {gin::kEmbedderNativeGin
};
88 MessageChannel
* MessageChannel::Create(PepperPluginInstanceImpl
* instance
,
89 v8::Persistent
<v8::Object
>* result
) {
90 MessageChannel
* message_channel
= new MessageChannel(instance
);
91 v8::HandleScope
handle_scope(instance
->GetIsolate());
92 v8::Context::Scope
context_scope(instance
->GetMainWorldContext());
93 gin::Handle
<MessageChannel
> handle
=
94 gin::CreateHandle(instance
->GetIsolate(), message_channel
);
95 result
->Reset(instance
->GetIsolate(), handle
.ToV8()->ToObject());
96 return message_channel
;
99 MessageChannel::~MessageChannel() {
100 UnregisterSyncMessageStatusObserver();
102 passthrough_object_
.Reset();
104 instance_
->MessageChannelDestroyed();
107 void MessageChannel::InstanceDeleted() {
108 UnregisterSyncMessageStatusObserver();
112 void MessageChannel::PostMessageToJavaScript(PP_Var message_data
) {
113 v8::HandleScope
scope(v8::Isolate::GetCurrent());
115 // Because V8 is probably not on the stack for Native->JS calls, we need to
116 // enter the appropriate context for the plugin.
117 v8::Local
<v8::Context
> context
= instance_
->GetMainWorldContext();
118 if (context
.IsEmpty())
121 v8::Context::Scope
context_scope(context
);
123 v8::Handle
<v8::Value
> v8_val
;
124 if (!var_converter_
.ToV8Value(message_data
, context
, &v8_val
)) {
125 PpapiGlobals::Get()->LogWithSource(instance_
->pp_instance(),
128 kVarToV8ConversionError
);
132 WebSerializedScriptValue serialized_val
=
133 WebSerializedScriptValue::serialize(v8_val
);
135 if (js_message_queue_state_
!= SEND_DIRECTLY
) {
136 // We can't just PostTask here; the messages would arrive out of
137 // order. Instead, we queue them up until we're ready to post
139 js_message_queue_
.push_back(serialized_val
);
141 // The proxy sent an asynchronous message, so the plugin is already
142 // unblocked. Therefore, there's no need to PostTask.
143 DCHECK(js_message_queue_
.empty());
144 PostMessageToJavaScriptImpl(serialized_val
);
148 void MessageChannel::Start() {
149 DCHECK_EQ(WAITING_TO_START
, js_message_queue_state_
);
150 DCHECK_EQ(WAITING_TO_START
, plugin_message_queue_state_
);
152 ppapi::proxy::HostDispatcher
* dispatcher
=
153 ppapi::proxy::HostDispatcher::GetForInstance(instance_
->pp_instance());
154 // The dispatcher is NULL for in-process.
156 unregister_observer_callback_
=
157 dispatcher
->AddSyncMessageStatusObserver(this);
160 // We can't drain the JS message queue directly since we haven't finished
161 // initializing the PepperWebPluginImpl yet, so the plugin isn't available in
163 DrainJSMessageQueueSoon();
165 plugin_message_queue_state_
= SEND_DIRECTLY
;
166 DrainCompletedPluginMessages();
169 void MessageChannel::SetPassthroughObject(v8::Handle
<v8::Object
> passthrough
) {
170 passthrough_object_
.Reset(instance_
->GetIsolate(), passthrough
);
173 void MessageChannel::SetReadOnlyProperty(PP_Var key
, PP_Var value
) {
174 StringVar
* key_string
= StringVar::FromPPVar(key
);
176 internal_named_properties_
[key_string
->value()] = ScopedPPVar(value
);
182 MessageChannel::MessageChannel(PepperPluginInstanceImpl
* instance
)
183 : gin::NamedPropertyInterceptor(instance
->GetIsolate(), this),
185 js_message_queue_state_(WAITING_TO_START
),
186 blocking_message_depth_(0),
187 plugin_message_queue_state_(WAITING_TO_START
),
188 var_converter_(instance
->pp_instance(),
189 V8VarConverter::kDisallowObjectVars
),
190 weak_ptr_factory_(this) {
193 gin::ObjectTemplateBuilder
MessageChannel::GetObjectTemplateBuilder(
194 v8::Isolate
* isolate
) {
195 return Wrappable
<MessageChannel
>::GetObjectTemplateBuilder(isolate
)
196 .AddNamedPropertyInterceptor();
199 void MessageChannel::BeginBlockOnSyncMessage() {
200 js_message_queue_state_
= QUEUE_MESSAGES
;
201 ++blocking_message_depth_
;
204 void MessageChannel::EndBlockOnSyncMessage() {
205 DCHECK_GT(blocking_message_depth_
, 0);
206 --blocking_message_depth_
;
207 if (!blocking_message_depth_
)
208 DrainJSMessageQueueSoon();
211 v8::Local
<v8::Value
> MessageChannel::GetNamedProperty(
212 v8::Isolate
* isolate
,
213 const std::string
& identifier
) {
215 return v8::Local
<v8::Value
>();
217 PepperTryCatchV8
try_catch(instance_
, &var_converter_
, isolate
);
218 if (identifier
== kPostMessage
) {
219 return gin::CreateFunctionTemplate(isolate
,
220 base::Bind(&MessageChannel::PostMessageToNative
,
221 weak_ptr_factory_
.GetWeakPtr()))->GetFunction();
222 } else if (identifier
== kPostMessageAndAwaitResponse
) {
223 return gin::CreateFunctionTemplate(isolate
,
224 base::Bind(&MessageChannel::PostBlockingMessageToNative
,
225 weak_ptr_factory_
.GetWeakPtr()))->GetFunction();
228 std::map
<std::string
, ScopedPPVar
>::const_iterator it
=
229 internal_named_properties_
.find(identifier
);
230 if (it
!= internal_named_properties_
.end()) {
231 v8::Handle
<v8::Value
> result
= try_catch
.ToV8(it
->second
.get());
232 if (try_catch
.ThrowException())
233 return v8::Local
<v8::Value
>();
237 PluginObject
* plugin_object
= GetPluginObject(isolate
);
239 return plugin_object
->GetNamedProperty(isolate
, identifier
);
240 return v8::Local
<v8::Value
>();
243 bool MessageChannel::SetNamedProperty(v8::Isolate
* isolate
,
244 const std::string
& identifier
,
245 v8::Local
<v8::Value
> value
) {
248 PepperTryCatchV8
try_catch(instance_
, &var_converter_
, isolate
);
249 if (identifier
== kPostMessage
||
250 identifier
== kPostMessageAndAwaitResponse
) {
251 try_catch
.ThrowException("Cannot set properties with the name postMessage"
252 "or postMessageAndAwaitResponse");
256 // TODO(raymes): This is only used by the gTalk plugin which is deprecated.
257 // Remove passthrough of SetProperty calls as soon as it is removed.
258 PluginObject
* plugin_object
= GetPluginObject(isolate
);
260 return plugin_object
->SetNamedProperty(isolate
, identifier
, value
);
265 std::vector
<std::string
> MessageChannel::EnumerateNamedProperties(
266 v8::Isolate
* isolate
) {
267 std::vector
<std::string
> result
;
268 PluginObject
* plugin_object
= GetPluginObject(isolate
);
270 result
= plugin_object
->EnumerateNamedProperties(isolate
);
271 result
.push_back(kPostMessage
);
272 result
.push_back(kPostMessageAndAwaitResponse
);
276 void MessageChannel::PostMessageToNative(gin::Arguments
* args
) {
279 if (args
->Length() != 1) {
280 // TODO(raymes): Consider throwing an exception here. We don't now for
281 // backward compatibility.
285 v8::Handle
<v8::Value
> message_data
;
286 if (!args
->GetNext(&message_data
)) {
290 EnqueuePluginMessage(message_data
);
291 DrainCompletedPluginMessages();
294 void MessageChannel::PostBlockingMessageToNative(gin::Arguments
* args
) {
297 PepperTryCatchV8
try_catch(instance_
, &var_converter_
, args
->isolate());
298 if (args
->Length() != 1) {
299 try_catch
.ThrowException(
300 "postMessageAndAwaitResponse requires one argument");
304 v8::Handle
<v8::Value
> message_data
;
305 if (!args
->GetNext(&message_data
)) {
309 if (plugin_message_queue_state_
== WAITING_TO_START
) {
310 try_catch
.ThrowException(
311 "Attempted to call a synchronous method on a plugin that was not "
316 // If the queue of messages to the plugin is non-empty, we're still waiting on
317 // pending Var conversions. This means at some point in the past, JavaScript
318 // called postMessage (the async one) and passed us something with a browser-
319 // side host (e.g., FileSystem) and we haven't gotten a response from the
320 // browser yet. We can't currently support sending a sync message if the
321 // plugin does this, because it will break the ordering of the messages
322 // arriving at the plugin.
323 // TODO(dmichael): Fix this.
324 // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
325 if (!plugin_message_queue_
.empty()) {
326 try_catch
.ThrowException(
327 "Failed to convert parameter synchronously, because a prior "
328 "call to postMessage contained a type which required asynchronous "
329 "transfer which has not completed. Not all types are supported yet by "
330 "postMessageAndAwaitResponse. See crbug.com/367896.");
333 ScopedPPVar param
= try_catch
.FromV8(message_data
);
334 if (try_catch
.ThrowException())
337 ScopedPPVar pp_result
;
338 bool was_handled
= instance_
->HandleBlockingMessage(param
, &pp_result
);
340 try_catch
.ThrowException(
341 "The plugin has not registered a handler for synchronous messages. "
342 "See the documentation for PPB_Messaging::RegisterMessageHandler "
343 "and PPP_MessageHandler.");
346 v8::Handle
<v8::Value
> v8_result
= try_catch
.ToV8(pp_result
.get());
347 if (try_catch
.ThrowException())
350 args
->Return(v8_result
);
353 void MessageChannel::PostMessageToJavaScriptImpl(
354 const WebSerializedScriptValue
& message_data
) {
357 WebPluginContainer
* container
= instance_
->container();
358 // It's possible that container() is NULL if the plugin has been removed from
359 // the DOM (but the PluginInstance is not destroyed yet).
364 container
->element().document().createEvent("MessageEvent");
365 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
366 msg_event
.initMessageEvent("message", // type
369 message_data
, // data
373 // [*] Note that the |origin| is only specified for cross-document and server-
374 // sent messages, while |source| is only specified for cross-document
376 // http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
377 // This currently behaves like Web Workers. On Firefox, Chrome, and Safari
378 // at least, postMessage on Workers does not provide the origin or source.
379 // TODO(dmichael): Add origin if we change to a more iframe-like origin
380 // policy (see crbug.com/81537)
381 container
->element().dispatchEvent(msg_event
);
384 PluginObject
* MessageChannel::GetPluginObject(v8::Isolate
* isolate
) {
385 return PluginObject::FromV8Object(isolate
,
386 v8::Local
<v8::Object
>::New(isolate
, passthrough_object_
));
389 void MessageChannel::EnqueuePluginMessage(v8::Handle
<v8::Value
> v8_value
) {
390 plugin_message_queue_
.push_back(VarConversionResult());
391 // Convert the v8 value in to an appropriate PP_Var like Dictionary,
392 // Array, etc. (We explicitly don't want an "Object" PP_Var, which we don't
393 // support for Messaging.)
394 // TODO(raymes): Possibly change this to use TryCatch to do the conversion and
395 // throw an exception if necessary.
396 V8VarConverter::VarResult conversion_result
=
397 var_converter_
.FromV8Value(
399 v8::Isolate::GetCurrent()->GetCurrentContext(),
400 base::Bind(&MessageChannel::FromV8ValueComplete
,
401 weak_ptr_factory_
.GetWeakPtr(),
402 &plugin_message_queue_
.back()));
403 if (conversion_result
.completed_synchronously
) {
404 plugin_message_queue_
.back().ConversionCompleted(
405 conversion_result
.var
,
406 conversion_result
.success
);
410 void MessageChannel::FromV8ValueComplete(VarConversionResult
* result_holder
,
411 const ScopedPPVar
& result
,
415 result_holder
->ConversionCompleted(result
, success
);
416 DrainCompletedPluginMessages();
419 void MessageChannel::DrainCompletedPluginMessages() {
421 if (plugin_message_queue_state_
== WAITING_TO_START
)
424 while (!plugin_message_queue_
.empty() &&
425 plugin_message_queue_
.front().conversion_completed()) {
426 const VarConversionResult
& front
= plugin_message_queue_
.front();
427 if (front
.success()) {
428 instance_
->HandleMessage(front
.var());
430 PpapiGlobals::Get()->LogWithSource(instance()->pp_instance(),
433 kV8ToVarConversionError
);
435 plugin_message_queue_
.pop_front();
439 void MessageChannel::DrainJSMessageQueue() {
442 if (js_message_queue_state_
== SEND_DIRECTLY
)
445 // Take a reference on the PluginInstance. This is because JavaScript code
446 // may delete the plugin, which would destroy the PluginInstance and its
447 // corresponding MessageChannel.
448 scoped_refptr
<PepperPluginInstanceImpl
> instance_ref(instance_
);
449 while (!js_message_queue_
.empty()) {
450 PostMessageToJavaScriptImpl(js_message_queue_
.front());
451 js_message_queue_
.pop_front();
453 js_message_queue_state_
= SEND_DIRECTLY
;
456 void MessageChannel::DrainJSMessageQueueSoon() {
457 base::MessageLoop::current()->PostTask(
459 base::Bind(&MessageChannel::DrainJSMessageQueue
,
460 weak_ptr_factory_
.GetWeakPtr()));
463 void MessageChannel::UnregisterSyncMessageStatusObserver() {
464 if (!unregister_observer_callback_
.is_null()) {
465 unregister_observer_callback_
.Run();
466 unregister_observer_callback_
.Reset();
470 } // namespace content