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(),
96 handle
.ToV8()->ToObject(instance
->GetIsolate()));
97 return message_channel
;
100 MessageChannel::~MessageChannel() {
101 UnregisterSyncMessageStatusObserver();
103 passthrough_object_
.Reset();
105 instance_
->MessageChannelDestroyed();
108 void MessageChannel::InstanceDeleted() {
109 UnregisterSyncMessageStatusObserver();
113 void MessageChannel::PostMessageToJavaScript(PP_Var message_data
) {
114 v8::HandleScope
scope(v8::Isolate::GetCurrent());
116 // Because V8 is probably not on the stack for Native->JS calls, we need to
117 // enter the appropriate context for the plugin.
118 v8::Local
<v8::Context
> context
= instance_
->GetMainWorldContext();
119 if (context
.IsEmpty())
122 v8::Context::Scope
context_scope(context
);
124 v8::Handle
<v8::Value
> v8_val
;
125 if (!var_converter_
.ToV8Value(message_data
, context
, &v8_val
)) {
126 PpapiGlobals::Get()->LogWithSource(instance_
->pp_instance(),
129 kVarToV8ConversionError
);
133 WebSerializedScriptValue serialized_val
=
134 WebSerializedScriptValue::serialize(v8_val
);
136 if (js_message_queue_state_
!= SEND_DIRECTLY
) {
137 // We can't just PostTask here; the messages would arrive out of
138 // order. Instead, we queue them up until we're ready to post
140 js_message_queue_
.push_back(serialized_val
);
142 // The proxy sent an asynchronous message, so the plugin is already
143 // unblocked. Therefore, there's no need to PostTask.
144 DCHECK(js_message_queue_
.empty());
145 PostMessageToJavaScriptImpl(serialized_val
);
149 void MessageChannel::Start() {
150 DCHECK_EQ(WAITING_TO_START
, js_message_queue_state_
);
151 DCHECK_EQ(WAITING_TO_START
, plugin_message_queue_state_
);
153 ppapi::proxy::HostDispatcher
* dispatcher
=
154 ppapi::proxy::HostDispatcher::GetForInstance(instance_
->pp_instance());
155 // The dispatcher is NULL for in-process.
157 unregister_observer_callback_
=
158 dispatcher
->AddSyncMessageStatusObserver(this);
161 // We can't drain the JS message queue directly since we haven't finished
162 // initializing the PepperWebPluginImpl yet, so the plugin isn't available in
164 DrainJSMessageQueueSoon();
166 plugin_message_queue_state_
= SEND_DIRECTLY
;
167 DrainCompletedPluginMessages();
170 void MessageChannel::SetPassthroughObject(v8::Handle
<v8::Object
> passthrough
) {
171 passthrough_object_
.Reset(instance_
->GetIsolate(), passthrough
);
174 void MessageChannel::SetReadOnlyProperty(PP_Var key
, PP_Var value
) {
175 StringVar
* key_string
= StringVar::FromPPVar(key
);
177 internal_named_properties_
[key_string
->value()] = ScopedPPVar(value
);
183 MessageChannel::MessageChannel(PepperPluginInstanceImpl
* instance
)
184 : gin::NamedPropertyInterceptor(instance
->GetIsolate(), this),
186 js_message_queue_state_(WAITING_TO_START
),
187 blocking_message_depth_(0),
188 plugin_message_queue_state_(WAITING_TO_START
),
189 var_converter_(instance
->pp_instance(),
190 V8VarConverter::kDisallowObjectVars
),
191 weak_ptr_factory_(this) {
194 gin::ObjectTemplateBuilder
MessageChannel::GetObjectTemplateBuilder(
195 v8::Isolate
* isolate
) {
196 return Wrappable
<MessageChannel
>::GetObjectTemplateBuilder(isolate
)
197 .AddNamedPropertyInterceptor();
200 void MessageChannel::BeginBlockOnSyncMessage() {
201 js_message_queue_state_
= QUEUE_MESSAGES
;
202 ++blocking_message_depth_
;
205 void MessageChannel::EndBlockOnSyncMessage() {
206 DCHECK_GT(blocking_message_depth_
, 0);
207 --blocking_message_depth_
;
208 if (!blocking_message_depth_
)
209 DrainJSMessageQueueSoon();
212 v8::Local
<v8::Value
> MessageChannel::GetNamedProperty(
213 v8::Isolate
* isolate
,
214 const std::string
& identifier
) {
216 return v8::Local
<v8::Value
>();
218 PepperTryCatchV8
try_catch(instance_
, &var_converter_
, isolate
);
219 if (identifier
== kPostMessage
) {
220 return gin::CreateFunctionTemplate(isolate
,
221 base::Bind(&MessageChannel::PostMessageToNative
,
222 weak_ptr_factory_
.GetWeakPtr()))->GetFunction();
223 } else if (identifier
== kPostMessageAndAwaitResponse
) {
224 return gin::CreateFunctionTemplate(isolate
,
225 base::Bind(&MessageChannel::PostBlockingMessageToNative
,
226 weak_ptr_factory_
.GetWeakPtr()))->GetFunction();
229 std::map
<std::string
, ScopedPPVar
>::const_iterator it
=
230 internal_named_properties_
.find(identifier
);
231 if (it
!= internal_named_properties_
.end()) {
232 v8::Handle
<v8::Value
> result
= try_catch
.ToV8(it
->second
.get());
233 if (try_catch
.ThrowException())
234 return v8::Local
<v8::Value
>();
238 PluginObject
* plugin_object
= GetPluginObject(isolate
);
240 return plugin_object
->GetNamedProperty(isolate
, identifier
);
241 return v8::Local
<v8::Value
>();
244 bool MessageChannel::SetNamedProperty(v8::Isolate
* isolate
,
245 const std::string
& identifier
,
246 v8::Local
<v8::Value
> value
) {
249 PepperTryCatchV8
try_catch(instance_
, &var_converter_
, isolate
);
250 if (identifier
== kPostMessage
||
251 identifier
== kPostMessageAndAwaitResponse
) {
252 try_catch
.ThrowException("Cannot set properties with the name postMessage"
253 "or postMessageAndAwaitResponse");
257 // TODO(raymes): This is only used by the gTalk plugin which is deprecated.
258 // Remove passthrough of SetProperty calls as soon as it is removed.
259 PluginObject
* plugin_object
= GetPluginObject(isolate
);
261 return plugin_object
->SetNamedProperty(isolate
, identifier
, value
);
266 std::vector
<std::string
> MessageChannel::EnumerateNamedProperties(
267 v8::Isolate
* isolate
) {
268 std::vector
<std::string
> result
;
269 PluginObject
* plugin_object
= GetPluginObject(isolate
);
271 result
= plugin_object
->EnumerateNamedProperties(isolate
);
272 result
.push_back(kPostMessage
);
273 result
.push_back(kPostMessageAndAwaitResponse
);
277 void MessageChannel::PostMessageToNative(gin::Arguments
* args
) {
280 if (args
->Length() != 1) {
281 // TODO(raymes): Consider throwing an exception here. We don't now for
282 // backward compatibility.
286 v8::Handle
<v8::Value
> message_data
;
287 if (!args
->GetNext(&message_data
)) {
291 EnqueuePluginMessage(message_data
);
292 DrainCompletedPluginMessages();
295 void MessageChannel::PostBlockingMessageToNative(gin::Arguments
* args
) {
298 PepperTryCatchV8
try_catch(instance_
, &var_converter_
, args
->isolate());
299 if (args
->Length() != 1) {
300 try_catch
.ThrowException(
301 "postMessageAndAwaitResponse requires one argument");
305 v8::Handle
<v8::Value
> message_data
;
306 if (!args
->GetNext(&message_data
)) {
310 if (plugin_message_queue_state_
== WAITING_TO_START
) {
311 try_catch
.ThrowException(
312 "Attempted to call a synchronous method on a plugin that was not "
317 // If the queue of messages to the plugin is non-empty, we're still waiting on
318 // pending Var conversions. This means at some point in the past, JavaScript
319 // called postMessage (the async one) and passed us something with a browser-
320 // side host (e.g., FileSystem) and we haven't gotten a response from the
321 // browser yet. We can't currently support sending a sync message if the
322 // plugin does this, because it will break the ordering of the messages
323 // arriving at the plugin.
324 // TODO(dmichael): Fix this.
325 // See https://code.google.com/p/chromium/issues/detail?id=367896#c4
326 if (!plugin_message_queue_
.empty()) {
327 try_catch
.ThrowException(
328 "Failed to convert parameter synchronously, because a prior "
329 "call to postMessage contained a type which required asynchronous "
330 "transfer which has not completed. Not all types are supported yet by "
331 "postMessageAndAwaitResponse. See crbug.com/367896.");
334 ScopedPPVar param
= try_catch
.FromV8(message_data
);
335 if (try_catch
.ThrowException())
338 ScopedPPVar pp_result
;
339 bool was_handled
= instance_
->HandleBlockingMessage(param
, &pp_result
);
341 try_catch
.ThrowException(
342 "The plugin has not registered a handler for synchronous messages. "
343 "See the documentation for PPB_Messaging::RegisterMessageHandler "
344 "and PPP_MessageHandler.");
347 v8::Handle
<v8::Value
> v8_result
= try_catch
.ToV8(pp_result
.get());
348 if (try_catch
.ThrowException())
351 args
->Return(v8_result
);
354 void MessageChannel::PostMessageToJavaScriptImpl(
355 const WebSerializedScriptValue
& message_data
) {
358 WebPluginContainer
* container
= instance_
->container();
359 // It's possible that container() is NULL if the plugin has been removed from
360 // the DOM (but the PluginInstance is not destroyed yet).
365 container
->element().document().createEvent("MessageEvent");
366 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
367 msg_event
.initMessageEvent("message", // type
370 message_data
, // data
374 // [*] Note that the |origin| is only specified for cross-document and server-
375 // sent messages, while |source| is only specified for cross-document
377 // http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html
378 // This currently behaves like Web Workers. On Firefox, Chrome, and Safari
379 // at least, postMessage on Workers does not provide the origin or source.
380 // TODO(dmichael): Add origin if we change to a more iframe-like origin
381 // policy (see crbug.com/81537)
382 container
->element().dispatchEvent(msg_event
);
385 PluginObject
* MessageChannel::GetPluginObject(v8::Isolate
* isolate
) {
386 return PluginObject::FromV8Object(isolate
,
387 v8::Local
<v8::Object
>::New(isolate
, passthrough_object_
));
390 void MessageChannel::EnqueuePluginMessage(v8::Handle
<v8::Value
> v8_value
) {
391 plugin_message_queue_
.push_back(VarConversionResult());
392 // Convert the v8 value in to an appropriate PP_Var like Dictionary,
393 // Array, etc. (We explicitly don't want an "Object" PP_Var, which we don't
394 // support for Messaging.)
395 // TODO(raymes): Possibly change this to use TryCatch to do the conversion and
396 // throw an exception if necessary.
397 V8VarConverter::VarResult conversion_result
=
398 var_converter_
.FromV8Value(
400 v8::Isolate::GetCurrent()->GetCurrentContext(),
401 base::Bind(&MessageChannel::FromV8ValueComplete
,
402 weak_ptr_factory_
.GetWeakPtr(),
403 &plugin_message_queue_
.back()));
404 if (conversion_result
.completed_synchronously
) {
405 plugin_message_queue_
.back().ConversionCompleted(
406 conversion_result
.var
,
407 conversion_result
.success
);
411 void MessageChannel::FromV8ValueComplete(VarConversionResult
* result_holder
,
412 const ScopedPPVar
& result
,
416 result_holder
->ConversionCompleted(result
, success
);
417 DrainCompletedPluginMessages();
420 void MessageChannel::DrainCompletedPluginMessages() {
422 if (plugin_message_queue_state_
== WAITING_TO_START
)
425 while (!plugin_message_queue_
.empty() &&
426 plugin_message_queue_
.front().conversion_completed()) {
427 const VarConversionResult
& front
= plugin_message_queue_
.front();
428 if (front
.success()) {
429 instance_
->HandleMessage(front
.var());
431 PpapiGlobals::Get()->LogWithSource(instance()->pp_instance(),
434 kV8ToVarConversionError
);
436 plugin_message_queue_
.pop_front();
440 void MessageChannel::DrainJSMessageQueue() {
443 if (js_message_queue_state_
== SEND_DIRECTLY
)
446 // Take a reference on the PluginInstance. This is because JavaScript code
447 // may delete the plugin, which would destroy the PluginInstance and its
448 // corresponding MessageChannel.
449 scoped_refptr
<PepperPluginInstanceImpl
> instance_ref(instance_
);
450 while (!js_message_queue_
.empty()) {
451 PostMessageToJavaScriptImpl(js_message_queue_
.front());
452 js_message_queue_
.pop_front();
454 js_message_queue_state_
= SEND_DIRECTLY
;
457 void MessageChannel::DrainJSMessageQueueSoon() {
458 base::MessageLoop::current()->PostTask(
460 base::Bind(&MessageChannel::DrainJSMessageQueue
,
461 weak_ptr_factory_
.GetWeakPtr()));
464 void MessageChannel::UnregisterSyncMessageStatusObserver() {
465 if (!unregister_observer_callback_
.is_null()) {
466 unregister_observer_callback_
.Run();
467 unregister_observer_callback_
.Reset();
471 } // namespace content