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 "content/renderer/pepper/v8_var_converter.h"
19 #include "gin/arguments.h"
20 #include "gin/converter.h"
21 #include "gin/function_template.h"
22 #include "gin/object_template_builder.h"
23 #include "gin/public/gin_embedders.h"
24 #include "ppapi/shared_impl/ppapi_globals.h"
25 #include "ppapi/shared_impl/scoped_pp_var.h"
26 #include "ppapi/shared_impl/var.h"
27 #include "ppapi/shared_impl/var_tracker.h"
28 #include "third_party/WebKit/public/web/WebBindings.h"
29 #include "third_party/WebKit/public/web/WebDocument.h"
30 #include "third_party/WebKit/public/web/WebDOMMessageEvent.h"
31 #include "third_party/WebKit/public/web/WebElement.h"
32 #include "third_party/WebKit/public/web/WebLocalFrame.h"
33 #include "third_party/WebKit/public/web/WebNode.h"
34 #include "third_party/WebKit/public/web/WebPluginContainer.h"
35 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
36 #include "v8/include/v8.h"
38 using ppapi::ArrayBufferVar
;
39 using ppapi::PpapiGlobals
;
40 using ppapi::ScopedPPVar
;
41 using ppapi::StringVar
;
42 using blink::WebBindings
;
43 using blink::WebElement
;
44 using blink::WebDOMEvent
;
45 using blink::WebDOMMessageEvent
;
46 using blink::WebPluginContainer
;
47 using blink::WebSerializedScriptValue
;
53 const char kPostMessage
[] = "postMessage";
54 const char kPostMessageAndAwaitResponse
[] = "postMessageAndAwaitResponse";
55 const char kV8ToVarConversionError
[] =
56 "Failed to convert a PostMessage "
57 "argument from a JavaScript value to a PP_Var. It may have cycles or be of "
58 "an unsupported type.";
59 const char kVarToV8ConversionError
[] =
60 "Failed to convert a PostMessage "
61 "argument from a PP_Var to a Javascript value. It may have cycles or be of "
62 "an unsupported type.";
66 // MessageChannel --------------------------------------------------------------
67 struct MessageChannel::VarConversionResult
{
68 VarConversionResult() : success_(false), conversion_completed_(false) {}
69 void ConversionCompleted(const ScopedPPVar
& var
,
71 conversion_completed_
= true;
75 const ScopedPPVar
& var() const { return var_
; }
76 bool success() const { return success_
; }
77 bool conversion_completed() const { return conversion_completed_
; }
82 bool conversion_completed_
;
86 gin::WrapperInfo
MessageChannel::kWrapperInfo
= {gin::kEmbedderNativeGin
};
89 MessageChannel
* MessageChannel::Create(PepperPluginInstanceImpl
* instance
,
90 v8::Persistent
<v8::Object
>* result
) {
91 MessageChannel
* message_channel
= new MessageChannel(instance
);
92 v8::HandleScope
handle_scope(instance
->GetIsolate());
93 v8::Context::Scope
context_scope(instance
->GetContext());
94 gin::Handle
<MessageChannel
> handle
=
95 gin::CreateHandle(instance
->GetIsolate(), message_channel
);
96 result
->Reset(instance
->GetIsolate(), handle
.ToV8()->ToObject());
97 return message_channel
;
100 MessageChannel::~MessageChannel() {
101 passthrough_object_
.Reset();
103 instance_
->MessageChannelDestroyed();
106 void MessageChannel::InstanceDeleted() {
110 void MessageChannel::PostMessageToJavaScript(PP_Var message_data
) {
111 v8::HandleScope
scope(v8::Isolate::GetCurrent());
113 // Because V8 is probably not on the stack for Native->JS calls, we need to
114 // enter the appropriate context for the plugin.
115 v8::Local
<v8::Context
> context
= instance_
->GetContext();
116 if (context
.IsEmpty())
119 v8::Context::Scope
context_scope(context
);
121 v8::Handle
<v8::Value
> v8_val
;
122 if (!V8VarConverter(instance_
->pp_instance())
123 .ToV8Value(message_data
, context
, &v8_val
)) {
124 PpapiGlobals::Get()->LogWithSource(instance_
->pp_instance(),
127 kVarToV8ConversionError
);
131 WebSerializedScriptValue serialized_val
=
132 WebSerializedScriptValue::serialize(v8_val
);
134 if (early_message_queue_state_
!= SEND_DIRECTLY
) {
135 // We can't just PostTask here; the messages would arrive out of
136 // order. Instead, we queue them up until we're ready to post
138 early_message_queue_
.push_back(serialized_val
);
140 // The proxy sent an asynchronous message, so the plugin is already
141 // unblocked. Therefore, there's no need to PostTask.
142 DCHECK(early_message_queue_
.empty());
143 PostMessageToJavaScriptImpl(serialized_val
);
147 void MessageChannel::Start() {
148 // We PostTask here instead of draining the message queue directly
149 // since we haven't finished initializing the PepperWebPluginImpl yet, so
150 // the plugin isn't available in the DOM.
151 base::MessageLoop::current()->PostTask(
153 base::Bind(&MessageChannel::DrainEarlyMessageQueue
,
154 weak_ptr_factory_
.GetWeakPtr()));
157 void MessageChannel::SetPassthroughObject(v8::Handle
<v8::Object
> passthrough
) {
158 passthrough_object_
.Reset(instance_
->GetIsolate(), passthrough
);
161 void MessageChannel::SetReadOnlyProperty(PP_Var key
, PP_Var value
) {
162 StringVar
* key_string
= StringVar::FromPPVar(key
);
164 internal_named_properties_
[key_string
->value()] = ScopedPPVar(value
);
170 MessageChannel::MessageChannel(PepperPluginInstanceImpl
* instance
)
171 : gin::NamedPropertyInterceptor(instance
->GetIsolate(), this),
173 early_message_queue_state_(QUEUE_MESSAGES
),
174 weak_ptr_factory_(this) {
177 gin::ObjectTemplateBuilder
MessageChannel::GetObjectTemplateBuilder(
178 v8::Isolate
* isolate
) {
179 return Wrappable
<MessageChannel
>::GetObjectTemplateBuilder(isolate
)
180 .AddNamedPropertyInterceptor();
183 v8::Local
<v8::Value
> MessageChannel::GetNamedProperty(
184 v8::Isolate
* isolate
,
185 const std::string
& identifier
) {
187 return v8::Local
<v8::Value
>();
189 PepperTryCatchV8
try_catch(instance_
, V8VarConverter::kDisallowObjectVars
,
191 if (identifier
== kPostMessage
) {
192 return gin::CreateFunctionTemplate(isolate
,
193 base::Bind(&MessageChannel::PostMessageToNative
,
194 weak_ptr_factory_
.GetWeakPtr()))->GetFunction();
195 } else if (identifier
== kPostMessageAndAwaitResponse
) {
196 return gin::CreateFunctionTemplate(isolate
,
197 base::Bind(&MessageChannel::PostBlockingMessageToNative
,
198 weak_ptr_factory_
.GetWeakPtr()))->GetFunction();
201 std::map
<std::string
, ScopedPPVar
>::const_iterator it
=
202 internal_named_properties_
.find(identifier
);
203 if (it
!= internal_named_properties_
.end()) {
204 v8::Handle
<v8::Value
> result
= try_catch
.ToV8(it
->second
.get());
205 if (try_catch
.ThrowException())
206 return v8::Local
<v8::Value
>();
210 PluginObject
* plugin_object
= GetPluginObject(isolate
);
212 return plugin_object
->GetNamedProperty(isolate
, identifier
);
213 return v8::Local
<v8::Value
>();
216 bool MessageChannel::SetNamedProperty(v8::Isolate
* isolate
,
217 const std::string
& identifier
,
218 v8::Local
<v8::Value
> value
) {
221 PepperTryCatchV8
try_catch(instance_
, V8VarConverter::kDisallowObjectVars
,
223 if (identifier
== kPostMessage
||
224 (identifier
== kPostMessageAndAwaitResponse
)) {
225 try_catch
.ThrowException("Cannot set properties with the name postMessage"
226 "or postMessageAndAwaitResponse");
230 // We don't forward this to the passthrough object; no plugins use that
232 // TODO(raymes): Remove SetProperty support from PPP_Class.
237 std::vector
<std::string
> MessageChannel::EnumerateNamedProperties(
238 v8::Isolate
* isolate
) {
239 std::vector
<std::string
> result
;
240 PluginObject
* plugin_object
= GetPluginObject(isolate
);
242 result
= plugin_object
->EnumerateNamedProperties(isolate
);
243 result
.push_back(kPostMessage
);
244 result
.push_back(kPostMessageAndAwaitResponse
);
248 void MessageChannel::PostMessageToNative(gin::Arguments
* args
) {
251 if (args
->Length() != 1) {
252 // TODO(raymes): Consider throwing an exception here. We don't now for
253 // backward compatibility.
257 v8::Handle
<v8::Value
> message_data
;
258 if (!args
->GetNext(&message_data
)) {
262 EnqueuePluginMessage(message_data
);
263 DrainCompletedPluginMessages();
266 void MessageChannel::PostBlockingMessageToNative(gin::Arguments
* args
) {
269 PepperTryCatchV8
try_catch(instance_
, V8VarConverter::kDisallowObjectVars
,
271 if (args
->Length() != 1) {
272 try_catch
.ThrowException(
273 "postMessageAndAwaitResponse requires one argument");
277 v8::Handle
<v8::Value
> message_data
;
278 if (!args
->GetNext(&message_data
)) {
282 if (early_message_queue_state_
== QUEUE_MESSAGES
) {
283 try_catch
.ThrowException(
284 "Attempted to call a synchronous method on a plugin that was not "
289 // If the queue of messages to the plugin is non-empty, we're still waiting on
290 // pending Var conversions. This means at some point in the past, JavaScript
291 // called postMessage (the async one) and passed us something with a browser-
292 // side host (e.g., FileSystem) and we haven't gotten a response from the
293 // browser yet. We can't currently support sending a sync message if the
294 // plugin does this, because it will break the ordering of the messages
295 // arriving at the plugin.
296 // TODO(dmichael): Fix this.
297 // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
298 if (!plugin_message_queue_
.empty()) {
299 try_catch
.ThrowException(
300 "Failed to convert parameter synchronously, because a prior "
301 "call to postMessage contained a type which required asynchronous "
302 "transfer which has not completed. Not all types are supported yet by "
303 "postMessageAndAwaitResponse. See crbug.com/367896.");
306 ScopedPPVar param
= try_catch
.FromV8(message_data
);
307 if (try_catch
.ThrowException())
310 ScopedPPVar pp_result
;
311 bool was_handled
= instance_
->HandleBlockingMessage(param
, &pp_result
);
313 try_catch
.ThrowException(
314 "The plugin has not registered a handler for synchronous messages. "
315 "See the documentation for PPB_Messaging::RegisterMessageHandler "
316 "and PPP_MessageHandler.");
319 v8::Handle
<v8::Value
> v8_result
= try_catch
.ToV8(pp_result
.get());
320 if (try_catch
.ThrowException())
323 args
->Return(v8_result
);
326 void MessageChannel::PostMessageToJavaScriptImpl(
327 const WebSerializedScriptValue
& message_data
) {
330 WebPluginContainer
* container
= instance_
->container();
331 // It's possible that container() is NULL if the plugin has been removed from
332 // the DOM (but the PluginInstance is not destroyed yet).
337 container
->element().document().createEvent("MessageEvent");
338 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
339 msg_event
.initMessageEvent("message", // type
342 message_data
, // data
346 // [*] Note that the |origin| is only specified for cross-document and server-
347 // sent messages, while |source| is only specified for cross-document
349 // http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
350 // This currently behaves like Web Workers. On Firefox, Chrome, and Safari
351 // at least, postMessage on Workers does not provide the origin or source.
352 // TODO(dmichael): Add origin if we change to a more iframe-like origin
353 // policy (see crbug.com/81537)
354 container
->element().dispatchEvent(msg_event
);
357 PluginObject
* MessageChannel::GetPluginObject(v8::Isolate
* isolate
) {
358 return PluginObject::FromV8Object(isolate
,
359 v8::Local
<v8::Object
>::New(isolate
, passthrough_object_
));
362 void MessageChannel::EnqueuePluginMessage(v8::Handle
<v8::Value
> v8_value
) {
363 plugin_message_queue_
.push_back(VarConversionResult());
364 // Convert NPVariantType_Object in to an appropriate PP_Var like Dictionary,
365 // Array, etc. Note NPVariantToVar would convert to an "Object" PP_Var,
366 // which we don't support for Messaging.
367 // TODO(raymes): Possibly change this to use TryCatch to do the conversion and
368 // throw an exception if necessary.
369 V8VarConverter
v8_var_converter(instance_
->pp_instance());
370 V8VarConverter::VarResult conversion_result
=
371 v8_var_converter
.FromV8Value(
373 v8::Isolate::GetCurrent()->GetCurrentContext(),
374 base::Bind(&MessageChannel::FromV8ValueComplete
,
375 weak_ptr_factory_
.GetWeakPtr(),
376 &plugin_message_queue_
.back()));
377 if (conversion_result
.completed_synchronously
) {
378 plugin_message_queue_
.back().ConversionCompleted(
379 conversion_result
.var
,
380 conversion_result
.success
);
384 void MessageChannel::FromV8ValueComplete(VarConversionResult
* result_holder
,
385 const ScopedPPVar
& result
,
389 result_holder
->ConversionCompleted(result
, success
);
390 DrainCompletedPluginMessages();
393 void MessageChannel::DrainCompletedPluginMessages() {
395 if (early_message_queue_state_
== QUEUE_MESSAGES
)
398 while (!plugin_message_queue_
.empty() &&
399 plugin_message_queue_
.front().conversion_completed()) {
400 const VarConversionResult
& front
= plugin_message_queue_
.front();
401 if (front
.success()) {
402 instance_
->HandleMessage(front
.var());
404 PpapiGlobals::Get()->LogWithSource(instance()->pp_instance(),
407 kV8ToVarConversionError
);
409 plugin_message_queue_
.pop_front();
413 void MessageChannel::DrainEarlyMessageQueue() {
416 DCHECK(early_message_queue_state_
== QUEUE_MESSAGES
);
418 // Take a reference on the PluginInstance. This is because JavaScript code
419 // may delete the plugin, which would destroy the PluginInstance and its
420 // corresponding MessageChannel.
421 scoped_refptr
<PepperPluginInstanceImpl
> instance_ref(instance_
);
422 while (!early_message_queue_
.empty()) {
423 PostMessageToJavaScriptImpl(early_message_queue_
.front());
424 early_message_queue_
.pop_front();
426 early_message_queue_state_
= SEND_DIRECTLY
;
428 DrainCompletedPluginMessages();
431 } // namespace content