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/public/common/content_client.h"
14 #include "content/public/renderer/content_renderer_client.h"
15 #include "content/renderer/pepper/host_array_buffer_var.h"
16 #include "content/renderer/pepper/npapi_glue.h"
17 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
18 #include "content/renderer/pepper/plugin_module.h"
19 #include "content/renderer/pepper/v8_var_converter.h"
20 #include "ppapi/shared_impl/ppapi_globals.h"
21 #include "ppapi/shared_impl/scoped_pp_var.h"
22 #include "ppapi/shared_impl/var.h"
23 #include "ppapi/shared_impl/var_tracker.h"
24 #include "third_party/WebKit/public/web/WebBindings.h"
25 #include "third_party/WebKit/public/web/WebDocument.h"
26 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
27 #include "third_party/WebKit/public/web/WebElement.h"
28 #include "third_party/WebKit/public/web/WebLocalFrame.h"
29 #include "third_party/WebKit/public/web/WebNode.h"
30 #include "third_party/WebKit/public/web/WebPluginContainer.h"
31 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
32 #include "v8/include/v8.h"
34 using ppapi::ArrayBufferVar
;
35 using ppapi::PpapiGlobals
;
36 using ppapi::ScopedPPVar
;
37 using ppapi::StringVar
;
38 using blink::WebBindings
;
39 using blink::WebElement
;
40 using blink::WebDOMEvent
;
41 using blink::WebDOMMessageEvent
;
42 using blink::WebPluginContainer
;
43 using blink::WebSerializedScriptValue
;
49 const char kPostMessage
[] = "postMessage";
50 const char kPostMessageAndAwaitResponse
[] = "postMessageAndAwaitResponse";
51 const char kV8ToVarConversionError
[] =
52 "Failed to convert a PostMessage "
53 "argument from a JavaScript value to a PP_Var. It may have cycles or be of "
54 "an unsupported type.";
55 const char kVarToV8ConversionError
[] =
56 "Failed to convert a PostMessage "
57 "argument from a PP_Var to a Javascript value. It may have cycles or be of "
58 "an unsupported type.";
60 // Helper function to get the MessageChannel that is associated with an
62 MessageChannel
* ToMessageChannel(NPObject
* object
) {
63 return static_cast<MessageChannel::MessageChannelNPObject
*>(object
)
64 ->message_channel
.get();
67 NPObject
* ToPassThroughObject(NPObject
* object
) {
68 MessageChannel
* channel
= ToMessageChannel(object
);
69 return channel
? channel
->passthrough_object() : NULL
;
72 // Return true iff |identifier| is equal to |string|.
73 bool IdentifierIs(NPIdentifier identifier
, const char string
[]) {
74 return WebBindings::getStringIdentifier(string
) == identifier
;
77 bool HasDevChannelPermission(NPObject
* channel_object
) {
78 MessageChannel
* channel
= ToMessageChannel(channel_object
);
81 return GetContentClient()->renderer()->IsPluginAllowedToUseDevChannelAPIs();
84 //------------------------------------------------------------------------------
85 // Implementations of NPClass functions. These are here to:
86 // - Implement postMessage behavior.
87 // - Forward calls to the 'passthrough' object to allow backwards-compatibility
88 // with GetInstanceObject() objects.
89 //------------------------------------------------------------------------------
90 NPObject
* MessageChannelAllocate(NPP npp
, NPClass
* the_class
) {
91 return new MessageChannel::MessageChannelNPObject
;
94 void MessageChannelDeallocate(NPObject
* object
) {
95 MessageChannel::MessageChannelNPObject
* instance
=
96 static_cast<MessageChannel::MessageChannelNPObject
*>(object
);
100 bool MessageChannelHasMethod(NPObject
* np_obj
, NPIdentifier name
) {
104 if (IdentifierIs(name
, kPostMessage
))
106 if (IdentifierIs(name
, kPostMessageAndAwaitResponse
) &&
107 HasDevChannelPermission(np_obj
)) {
110 // Other method names we will pass to the passthrough object, if we have one.
111 NPObject
* passthrough
= ToPassThroughObject(np_obj
);
113 return WebBindings::hasMethod(NULL
, passthrough
, name
);
117 bool MessageChannelInvoke(NPObject
* np_obj
,
119 const NPVariant
* args
,
125 MessageChannel
* message_channel
= ToMessageChannel(np_obj
);
126 if (!message_channel
)
129 // Check to see if we should handle this function ourselves.
130 if (IdentifierIs(name
, kPostMessage
) && (arg_count
== 1)) {
131 message_channel
->PostMessageToNative(&args
[0]);
133 } else if (IdentifierIs(name
, kPostMessageAndAwaitResponse
) &&
135 HasDevChannelPermission(np_obj
)) {
136 message_channel
->PostBlockingMessageToNative(&args
[0], result
);
140 // Other method calls we will pass to the passthrough object, if we have one.
141 NPObject
* passthrough
= ToPassThroughObject(np_obj
);
143 return WebBindings::invoke(
144 NULL
, passthrough
, name
, args
, arg_count
, result
);
149 bool MessageChannelInvokeDefault(NPObject
* np_obj
,
150 const NPVariant
* args
,
156 // Invoke on the passthrough object, if we have one.
157 NPObject
* passthrough
= ToPassThroughObject(np_obj
);
159 return WebBindings::invokeDefault(
160 NULL
, passthrough
, args
, arg_count
, result
);
165 bool MessageChannelHasProperty(NPObject
* np_obj
, NPIdentifier name
) {
169 MessageChannel
* message_channel
= ToMessageChannel(np_obj
);
170 if (message_channel
) {
171 if (message_channel
->GetReadOnlyProperty(name
, NULL
))
175 // Invoke on the passthrough object, if we have one.
176 NPObject
* passthrough
= ToPassThroughObject(np_obj
);
178 return WebBindings::hasProperty(NULL
, passthrough
, name
);
182 bool MessageChannelGetProperty(NPObject
* np_obj
,
188 // Don't allow getting the postMessage functions.
189 if (IdentifierIs(name
, kPostMessage
))
191 if (IdentifierIs(name
, kPostMessageAndAwaitResponse
) &&
192 HasDevChannelPermission(np_obj
)) {
195 MessageChannel
* message_channel
= ToMessageChannel(np_obj
);
196 if (message_channel
) {
197 if (message_channel
->GetReadOnlyProperty(name
, result
))
201 // Invoke on the passthrough object, if we have one.
202 NPObject
* passthrough
= ToPassThroughObject(np_obj
);
204 return WebBindings::getProperty(NULL
, passthrough
, name
, result
);
208 bool MessageChannelSetProperty(NPObject
* np_obj
,
210 const NPVariant
* variant
) {
214 // Don't allow setting the postMessage functions.
215 if (IdentifierIs(name
, kPostMessage
))
217 if (IdentifierIs(name
, kPostMessageAndAwaitResponse
) &&
218 HasDevChannelPermission(np_obj
)) {
221 // Invoke on the passthrough object, if we have one.
222 NPObject
* passthrough
= ToPassThroughObject(np_obj
);
224 return WebBindings::setProperty(NULL
, passthrough
, name
, variant
);
228 bool MessageChannelEnumerate(NPObject
* np_obj
,
229 NPIdentifier
** value
,
234 // Invoke on the passthrough object, if we have one, to enumerate its
236 NPObject
* passthrough
= ToPassThroughObject(np_obj
);
238 bool success
= WebBindings::enumerate(NULL
, passthrough
, value
, count
);
240 // Add postMessage to the list and return it.
241 if (std::numeric_limits
<size_t>::max() / sizeof(NPIdentifier
) <=
242 static_cast<size_t>(*count
) + 1) // Else, "always false" x64 warning.
244 NPIdentifier
* new_array
= static_cast<NPIdentifier
*>(
245 std::malloc(sizeof(NPIdentifier
) * (*count
+ 1)));
246 std::memcpy(new_array
, *value
, sizeof(NPIdentifier
) * (*count
));
247 new_array
[*count
] = WebBindings::getStringIdentifier(kPostMessage
);
255 // Otherwise, build an array that includes only postMessage.
256 *value
= static_cast<NPIdentifier
*>(malloc(sizeof(NPIdentifier
)));
257 (*value
)[0] = WebBindings::getStringIdentifier(kPostMessage
);
262 NPClass message_channel_class
= {
263 NP_CLASS_STRUCT_VERSION
, &MessageChannelAllocate
,
264 &MessageChannelDeallocate
, NULL
,
265 &MessageChannelHasMethod
, &MessageChannelInvoke
,
266 &MessageChannelInvokeDefault
, &MessageChannelHasProperty
,
267 &MessageChannelGetProperty
, &MessageChannelSetProperty
,
268 NULL
, &MessageChannelEnumerate
, };
272 // MessageChannel --------------------------------------------------------------
273 struct MessageChannel::VarConversionResult
{
274 VarConversionResult() : success_(false), conversion_completed_(false) {}
275 void ConversionCompleted(const ScopedPPVar
& var
,
277 conversion_completed_
= true;
281 const ScopedPPVar
& var() const { return var_
; }
282 bool success() const { return success_
; }
283 bool conversion_completed() const { return conversion_completed_
; }
288 bool conversion_completed_
;
291 MessageChannel::MessageChannelNPObject::MessageChannelNPObject() {}
293 MessageChannel::MessageChannelNPObject::~MessageChannelNPObject() {}
295 MessageChannel::MessageChannel(PepperPluginInstanceImpl
* instance
)
296 : instance_(instance
),
297 passthrough_object_(NULL
),
299 early_message_queue_state_(QUEUE_MESSAGES
),
300 weak_ptr_factory_(this) {
301 // Now create an NPObject for receiving calls to postMessage. This sets the
302 // reference count to 1. We release it in the destructor.
303 NPObject
* obj
= WebBindings::createObject(instance_
->instanceNPP(),
304 &message_channel_class
);
306 np_object_
= static_cast<MessageChannel::MessageChannelNPObject
*>(obj
);
307 np_object_
->message_channel
= weak_ptr_factory_
.GetWeakPtr();
310 MessageChannel::~MessageChannel() {
311 WebBindings::releaseObject(np_object_
);
312 if (passthrough_object_
)
313 WebBindings::releaseObject(passthrough_object_
);
316 void MessageChannel::Start() {
317 // We PostTask here instead of draining the message queue directly
318 // since we haven't finished initializing the PepperWebPluginImpl yet, so
319 // the plugin isn't available in the DOM.
320 base::MessageLoop::current()->PostTask(
322 base::Bind(&MessageChannel::DrainEarlyMessageQueue
,
323 weak_ptr_factory_
.GetWeakPtr()));
326 void MessageChannel::SetPassthroughObject(NPObject
* passthrough
) {
327 // Retain the passthrough object; We need to ensure it lives as long as this
330 WebBindings::retainObject(passthrough
);
332 // If we had a passthrough set already, release it. Note that we retain the
333 // incoming passthrough object first, so that we behave correctly if anyone
335 // SetPassthroughObject(passthrough_object());
336 if (passthrough_object_
)
337 WebBindings::releaseObject(passthrough_object_
);
339 passthrough_object_
= passthrough
;
342 bool MessageChannel::GetReadOnlyProperty(NPIdentifier key
,
343 NPVariant
* value
) const {
344 std::map
<NPIdentifier
, ScopedPPVar
>::const_iterator it
=
345 internal_properties_
.find(key
);
346 if (it
!= internal_properties_
.end()) {
348 return PPVarToNPVariant(it
->second
.get(), value
);
354 void MessageChannel::SetReadOnlyProperty(PP_Var key
, PP_Var value
) {
355 internal_properties_
[PPVarToNPIdentifier(key
)] = ScopedPPVar(value
);
358 void MessageChannel::PostMessageToJavaScript(PP_Var message_data
) {
359 v8::HandleScope
scope(v8::Isolate::GetCurrent());
361 // Because V8 is probably not on the stack for Native->JS calls, we need to
362 // enter the appropriate context for the plugin.
363 WebPluginContainer
* container
= instance_
->container();
364 // It's possible that container() is NULL if the plugin has been removed from
365 // the DOM (but the PluginInstance is not destroyed yet).
369 v8::Local
<v8::Context
> context
=
370 container
->element().document().frame()->mainWorldScriptContext();
371 // If the page is being destroyed, the context may be empty.
372 if (context
.IsEmpty())
374 v8::Context::Scope
context_scope(context
);
376 v8::Handle
<v8::Value
> v8_val
;
377 if (!V8VarConverter(instance_
->pp_instance())
378 .ToV8Value(message_data
, context
, &v8_val
)) {
379 PpapiGlobals::Get()->LogWithSource(instance_
->pp_instance(),
382 kVarToV8ConversionError
);
386 WebSerializedScriptValue serialized_val
=
387 WebSerializedScriptValue::serialize(v8_val
);
389 if (early_message_queue_state_
!= SEND_DIRECTLY
) {
390 // We can't just PostTask here; the messages would arrive out of
391 // order. Instead, we queue them up until we're ready to post
393 early_message_queue_
.push_back(serialized_val
);
395 // The proxy sent an asynchronous message, so the plugin is already
396 // unblocked. Therefore, there's no need to PostTask.
397 DCHECK(early_message_queue_
.empty());
398 PostMessageToJavaScriptImpl(serialized_val
);
402 void MessageChannel::PostMessageToNative(const NPVariant
* message_data
) {
403 EnqueuePluginMessage(message_data
);
404 DrainCompletedPluginMessages();
407 void MessageChannel::PostBlockingMessageToNative(const NPVariant
* message_data
,
408 NPVariant
* np_result
) {
409 if (early_message_queue_state_
== QUEUE_MESSAGES
) {
410 WebBindings::setException(
412 "Attempted to call a synchronous method on a plugin that was not "
417 // If the queue of messages to the plugin is non-empty, we're still waiting on
418 // pending Var conversions. This means at some point in the past, JavaScript
419 // called postMessage (the async one) and passed us something with a browser-
420 // side host (e.g., FileSystem) and we haven't gotten a response from the
421 // browser yet. We can't currently support sending a sync message if the
422 // plugin does this, because it will break the ordering of the messages
423 // arriving at the plugin.
424 // TODO(dmichael): Fix this.
425 // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
426 if (!plugin_message_queue_
.empty()) {
427 WebBindings::setException(
429 "Failed to convert parameter synchronously, because a prior "
430 "call to postMessage contained a type which required asynchronous "
431 "transfer which has not completed. Not all types are supported yet by "
432 "postMessageAndAwaitResponse. See crbug.com/367896.");
436 if (message_data
->type
== NPVariantType_Object
) {
437 // Convert NPVariantType_Object in to an appropriate PP_Var like Dictionary,
438 // Array, etc. Note NPVariantToVar would convert to an "Object" PP_Var,
439 // which we don't support for Messaging.
440 v8::Handle
<v8::Value
> v8_value
= WebBindings::toV8Value(message_data
);
441 V8VarConverter
v8_var_converter(instance_
->pp_instance());
442 bool success
= v8_var_converter
.FromV8ValueSync(
444 v8::Isolate::GetCurrent()->GetCurrentContext(),
447 WebBindings::setException(
449 "Failed to convert the given parameter to a PP_Var to send to "
454 param
= ScopedPPVar(ScopedPPVar::PassRef(),
455 NPVariantToPPVar(instance(), message_data
));
457 ScopedPPVar pp_result
;
458 bool was_handled
= instance_
->HandleBlockingMessage(param
, &pp_result
);
460 WebBindings::setException(
462 "The plugin has not registered a handler for synchronous messages. "
463 "See the documentation for PPB_Messaging::RegisterMessageHandler "
464 "and PPP_MessageHandler.");
467 v8::Handle
<v8::Value
> v8_val
;
468 if (!V8VarConverter(instance_
->pp_instance()).ToV8Value(
470 v8::Isolate::GetCurrent()->GetCurrentContext(),
472 WebBindings::setException(
474 "Failed to convert the plugin's result to a JavaScript type.");
477 // Success! Convert the result to an NPVariant.
478 WebBindings::toNPVariant(v8_val
, NULL
, np_result
);
481 void MessageChannel::PostMessageToJavaScriptImpl(
482 const WebSerializedScriptValue
& message_data
) {
485 WebPluginContainer
* container
= instance_
->container();
486 // It's possible that container() is NULL if the plugin has been removed from
487 // the DOM (but the PluginInstance is not destroyed yet).
492 container
->element().document().createEvent("MessageEvent");
493 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
494 msg_event
.initMessageEvent("message", // type
497 message_data
, // data
501 // [*] Note that the |origin| is only specified for cross-document and server-
502 // sent messages, while |source| is only specified for cross-document
504 // http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
505 // This currently behaves like Web Workers. On Firefox, Chrome, and Safari
506 // at least, postMessage on Workers does not provide the origin or source.
507 // TODO(dmichael): Add origin if we change to a more iframe-like origin
508 // policy (see crbug.com/81537)
509 container
->element().dispatchEvent(msg_event
);
512 void MessageChannel::EnqueuePluginMessage(const NPVariant
* variant
) {
513 plugin_message_queue_
.push_back(VarConversionResult());
514 if (variant
->type
== NPVariantType_Object
) {
515 // Convert NPVariantType_Object in to an appropriate PP_Var like Dictionary,
516 // Array, etc. Note NPVariantToVar would convert to an "Object" PP_Var,
517 // which we don't support for Messaging.
519 // Calling WebBindings::toV8Value creates a wrapper around NPVariant so it
520 // won't result in a deep copy.
521 v8::Handle
<v8::Value
> v8_value
= WebBindings::toV8Value(variant
);
522 V8VarConverter
v8_var_converter(instance_
->pp_instance());
523 V8VarConverter::VarResult conversion_result
=
524 v8_var_converter
.FromV8Value(
526 v8::Isolate::GetCurrent()->GetCurrentContext(),
527 base::Bind(&MessageChannel::FromV8ValueComplete
,
528 weak_ptr_factory_
.GetWeakPtr(),
529 &plugin_message_queue_
.back()));
530 if (conversion_result
.completed_synchronously
) {
531 plugin_message_queue_
.back().ConversionCompleted(
532 conversion_result
.var
,
533 conversion_result
.success
);
536 plugin_message_queue_
.back().ConversionCompleted(
537 ScopedPPVar(ScopedPPVar::PassRef(),
538 NPVariantToPPVar(instance(), variant
)),
540 DCHECK(plugin_message_queue_
.back().var().get().type
!= PP_VARTYPE_OBJECT
);
544 void MessageChannel::FromV8ValueComplete(VarConversionResult
* result_holder
,
545 const ScopedPPVar
& result
,
547 result_holder
->ConversionCompleted(result
, success
);
548 DrainCompletedPluginMessages();
551 void MessageChannel::DrainCompletedPluginMessages() {
552 if (early_message_queue_state_
== QUEUE_MESSAGES
)
555 while (!plugin_message_queue_
.empty() &&
556 plugin_message_queue_
.front().conversion_completed()) {
557 const VarConversionResult
& front
= plugin_message_queue_
.front();
558 if (front
.success()) {
559 instance_
->HandleMessage(front
.var());
561 PpapiGlobals::Get()->LogWithSource(instance()->pp_instance(),
564 kV8ToVarConversionError
);
566 plugin_message_queue_
.pop_front();
570 void MessageChannel::DrainEarlyMessageQueue() {
571 DCHECK(early_message_queue_state_
== QUEUE_MESSAGES
);
573 // Take a reference on the PluginInstance. This is because JavaScript code
574 // may delete the plugin, which would destroy the PluginInstance and its
575 // corresponding MessageChannel.
576 scoped_refptr
<PepperPluginInstanceImpl
> instance_ref(instance_
);
577 while (!early_message_queue_
.empty()) {
578 PostMessageToJavaScriptImpl(early_message_queue_
.front());
579 early_message_queue_
.pop_front();
581 early_message_queue_state_
= SEND_DIRECTLY
;
583 DrainCompletedPluginMessages();
586 } // namespace content