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.
4
5 #include "ppapi/proxy/plugin_dispatcher.h"
6
7 #include <map>
8
9 #include "base/compiler_specific.h"
10 #include "base/debug/trace_event.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "ipc/ipc_message.h"
14 #include "ipc/ipc_sync_channel.h"
15 #include "ipc/ipc_sync_message_filter.h"
16 #include "ppapi/c/pp_errors.h"
17 #include "ppapi/c/ppp_instance.h"
18 #include "ppapi/proxy/flash_clipboard_resource.h"
19 #include "ppapi/proxy/flash_file_resource.h"
20 #include "ppapi/proxy/flash_resource.h"
21 #include "ppapi/proxy/gamepad_resource.h"
22 #include "ppapi/proxy/interface_list.h"
23 #include "ppapi/proxy/interface_proxy.h"
24 #include "ppapi/proxy/plugin_globals.h"
25 #include "ppapi/proxy/plugin_message_filter.h"
26 #include "ppapi/proxy/plugin_resource_tracker.h"
27 #include "ppapi/proxy/plugin_var_serialization_rules.h"
28 #include "ppapi/proxy/ppapi_messages.h"
29 #include "ppapi/proxy/ppb_instance_proxy.h"
30 #include "ppapi/proxy/ppp_class_proxy.h"
31 #include "ppapi/proxy/resource_creation_proxy.h"
32 #include "ppapi/proxy/resource_reply_thread_registrar.h"
33 #include "ppapi/shared_impl/ppapi_globals.h"
34 #include "ppapi/shared_impl/proxy_lock.h"
35 #include "ppapi/shared_impl/resource.h"
36
37 #if defined(OS_POSIX) && !defined(OS_NACL)
38 #include "ipc/ipc_channel_posix.h"
39 #endif
40
41 namespace ppapi {
42 namespace proxy {
43
44 namespace {
45
46 typedef std::map<PP_Instance, PluginDispatcher*> InstanceToDispatcherMap;
47 InstanceToDispatcherMap* g_instance_to_dispatcher = NULL;
48
49 typedef std::set<PluginDispatcher*> DispatcherSet;
50 DispatcherSet* g_live_dispatchers = NULL;
51
52 } // namespace
53
InstanceData()54 InstanceData::InstanceData()
55 : is_request_surrounding_text_pending(false),
56 should_do_request_surrounding_text(false) {
57 }
58
~InstanceData()59 InstanceData::~InstanceData() {
60 // Run any pending mouse lock callback to prevent leaks.
61 if (mouse_lock_callback.get())
62 mouse_lock_callback->Abort();
63 }
64
PluginDispatcher(PP_GetInterface_Func get_interface,const PpapiPermissions & permissions,bool incognito)65 PluginDispatcher::PluginDispatcher(PP_GetInterface_Func get_interface,
66 const PpapiPermissions& permissions,
67 bool incognito)
68 : Dispatcher(get_interface, permissions),
69 plugin_delegate_(NULL),
70 received_preferences_(false),
71 plugin_dispatcher_id_(0),
72 incognito_(incognito) {
73 SetSerializationRules(new PluginVarSerializationRules(AsWeakPtr()));
74
75 if (!g_live_dispatchers)
76 g_live_dispatchers = new DispatcherSet;
77 g_live_dispatchers->insert(this);
78 }
79
~PluginDispatcher()80 PluginDispatcher::~PluginDispatcher() {
81 PluginGlobals::Get()->plugin_var_tracker()->DidDeleteDispatcher(this);
82
83 if (plugin_delegate_)
84 plugin_delegate_->Unregister(plugin_dispatcher_id_);
85
86 g_live_dispatchers->erase(this);
87 if (g_live_dispatchers->empty()) {
88 delete g_live_dispatchers;
89 g_live_dispatchers = NULL;
90 }
91 }
92
93 // static
GetForInstance(PP_Instance instance)94 PluginDispatcher* PluginDispatcher::GetForInstance(PP_Instance instance) {
95 if (!g_instance_to_dispatcher)
96 return NULL;
97 InstanceToDispatcherMap::iterator found = g_instance_to_dispatcher->find(
98 instance);
99 if (found == g_instance_to_dispatcher->end())
100 return NULL;
101 return found->second;
102 }
103
104 // static
GetForResource(const Resource * resource)105 PluginDispatcher* PluginDispatcher::GetForResource(const Resource* resource) {
106 return GetForInstance(resource->pp_instance());
107 }
108
109 // static
GetBrowserInterface(const char * interface_name)110 const void* PluginDispatcher::GetBrowserInterface(const char* interface_name) {
111 if (!interface_name) {
112 DLOG(WARNING) << "|interface_name| is null. Did you forget to add "
113 "the |interface_name()| template function to the interface's C++ "
114 "wrapper?";
115 return NULL;
116 }
117
118 return InterfaceList::GetInstance()->GetInterfaceForPPB(interface_name);
119 }
120
121 // static
LogWithSource(PP_Instance instance,PP_LogLevel level,const std::string & source,const std::string & value)122 void PluginDispatcher::LogWithSource(PP_Instance instance,
123 PP_LogLevel level,
124 const std::string& source,
125 const std::string& value) {
126 if (!g_live_dispatchers || !g_instance_to_dispatcher)
127 return;
128
129 if (instance) {
130 InstanceToDispatcherMap::iterator found =
131 g_instance_to_dispatcher->find(instance);
132 if (found != g_instance_to_dispatcher->end()) {
133 // Send just to this specific dispatcher.
134 found->second->Send(new PpapiHostMsg_LogWithSource(
135 instance, static_cast<int>(level), source, value));
136 return;
137 }
138 }
139
140 // Instance 0 or invalid, send to all dispatchers.
141 for (DispatcherSet::iterator i = g_live_dispatchers->begin();
142 i != g_live_dispatchers->end(); ++i) {
143 (*i)->Send(new PpapiHostMsg_LogWithSource(
144 instance, static_cast<int>(level), source, value));
145 }
146 }
147
GetPluginInterface(const std::string & interface_name)148 const void* PluginDispatcher::GetPluginInterface(
149 const std::string& interface_name) {
150 InterfaceMap::iterator found = plugin_interfaces_.find(interface_name);
151 if (found == plugin_interfaces_.end()) {
152 const void* ret = local_get_interface()(interface_name.c_str());
153 plugin_interfaces_.insert(std::make_pair(interface_name, ret));
154 return ret;
155 }
156 return found->second;
157 }
158
InitPluginWithChannel(PluginDelegate * delegate,base::ProcessId peer_pid,const IPC::ChannelHandle & channel_handle,bool is_client)159 bool PluginDispatcher::InitPluginWithChannel(
160 PluginDelegate* delegate,
161 base::ProcessId peer_pid,
162 const IPC::ChannelHandle& channel_handle,
163 bool is_client) {
164 if (!Dispatcher::InitWithChannel(delegate, peer_pid, channel_handle,
165 is_client))
166 return false;
167 plugin_delegate_ = delegate;
168 plugin_dispatcher_id_ = plugin_delegate_->Register(this);
169
170 sync_filter_ = new IPC::SyncMessageFilter(delegate->GetShutdownEvent());
171 channel()->AddFilter(sync_filter_.get());
172
173 // The message filter will intercept and process certain messages directly
174 // on the I/O thread.
175 channel()->AddFilter(
176 new PluginMessageFilter(
177 delegate->GetGloballySeenInstanceIDSet(),
178 PluginGlobals::Get()->resource_reply_thread_registrar()));
179 return true;
180 }
181
IsPlugin() const182 bool PluginDispatcher::IsPlugin() const {
183 return true;
184 }
185
SendMessage(IPC::Message * msg)186 bool PluginDispatcher::SendMessage(IPC::Message* msg) {
187 // Currently we need to choose between two different mechanisms for sending.
188 // On the main thread we use the regular dispatch Send() method, on another
189 // thread we use SyncMessageFilter.
190 if (PpapiGlobals::Get()->GetMainThreadMessageLoop()->BelongsToCurrentThread())
191 return Dispatcher::Send(msg);
192 return sync_filter_->Send(msg);
193 }
194
Send(IPC::Message * msg)195 bool PluginDispatcher::Send(IPC::Message* msg) {
196 TRACE_EVENT2("ppapi proxy", "PluginDispatcher::Send",
197 "Class", IPC_MESSAGE_ID_CLASS(msg->type()),
198 "Line", IPC_MESSAGE_ID_LINE(msg->type()));
199 // We always want plugin->renderer messages to arrive in-order. If some sync
200 // and some async messages are sent in response to a synchronous
201 // renderer->plugin call, the sync reply will be processed before the async
202 // reply, and everything will be confused.
203 //
204 // Allowing all async messages to unblock the renderer means more reentrancy
205 // there but gives correct ordering.
206 //
207 // We don't want reply messages to unblock however, as they will potentially
208 // end up on the wrong queue - see crbug.com/122443
209 if (!msg->is_reply())
210 msg->set_unblock(true);
211 if (msg->is_sync()) {
212 // Synchronous messages might be re-entrant, so we need to drop the lock.
213 ProxyAutoUnlock unlock;
214 return SendMessage(msg);
215 }
216 return SendMessage(msg);
217 }
218
OnMessageReceived(const IPC::Message & msg)219 bool PluginDispatcher::OnMessageReceived(const IPC::Message& msg) {
220 // We need to grab the proxy lock to ensure that we don't collide with the
221 // plugin making pepper calls on a different thread.
222 ProxyAutoLock lock;
223 TRACE_EVENT2("ppapi proxy", "PluginDispatcher::OnMessageReceived",
224 "Class", IPC_MESSAGE_ID_CLASS(msg.type()),
225 "Line", IPC_MESSAGE_ID_LINE(msg.type()));
226
227 if (msg.routing_id() == MSG_ROUTING_CONTROL) {
228 // Handle some plugin-specific control messages.
229 bool handled = true;
230 IPC_BEGIN_MESSAGE_MAP(PluginDispatcher, msg)
231 IPC_MESSAGE_HANDLER(PpapiMsg_SupportsInterface, OnMsgSupportsInterface)
232 IPC_MESSAGE_HANDLER(PpapiMsg_SetPreferences, OnMsgSetPreferences)
233 IPC_MESSAGE_UNHANDLED(handled = false);
234 IPC_END_MESSAGE_MAP()
235 if (handled)
236 return true;
237 }
238 return Dispatcher::OnMessageReceived(msg);
239 }
240
OnChannelError()241 void PluginDispatcher::OnChannelError() {
242 Dispatcher::OnChannelError();
243
244 // The renderer has crashed or exited. This channel and all instances
245 // associated with it are no longer valid.
246 ForceFreeAllInstances();
247 // TODO(brettw) free resources too!
248 delete this;
249 }
250
DidCreateInstance(PP_Instance instance)251 void PluginDispatcher::DidCreateInstance(PP_Instance instance) {
252 if (!g_instance_to_dispatcher)
253 g_instance_to_dispatcher = new InstanceToDispatcherMap;
254 (*g_instance_to_dispatcher)[instance] = this;
255 instance_map_.set(instance, scoped_ptr<InstanceData>(new InstanceData()));
256 }
257
DidDestroyInstance(PP_Instance instance)258 void PluginDispatcher::DidDestroyInstance(PP_Instance instance) {
259 instance_map_.erase(instance);
260
261 if (g_instance_to_dispatcher) {
262 InstanceToDispatcherMap::iterator found = g_instance_to_dispatcher->find(
263 instance);
264 if (found != g_instance_to_dispatcher->end()) {
265 DCHECK(found->second == this);
266 g_instance_to_dispatcher->erase(found);
267 } else {
268 NOTREACHED();
269 }
270 }
271 }
272
GetInstanceData(PP_Instance instance)273 InstanceData* PluginDispatcher::GetInstanceData(PP_Instance instance) {
274 return instance_map_.get(instance);
275 }
276
GetInstanceAPI()277 thunk::PPB_Instance_API* PluginDispatcher::GetInstanceAPI() {
278 return static_cast<PPB_Instance_Proxy*>(
279 GetInterfaceProxy(API_ID_PPB_INSTANCE));
280 }
281
GetResourceCreationAPI()282 thunk::ResourceCreationAPI* PluginDispatcher::GetResourceCreationAPI() {
283 return static_cast<ResourceCreationProxy*>(
284 GetInterfaceProxy(API_ID_RESOURCE_CREATION));
285 }
286
ForceFreeAllInstances()287 void PluginDispatcher::ForceFreeAllInstances() {
288 if (!g_instance_to_dispatcher)
289 return;
290
291 // Iterating will remove each item from the map, so we need to make a copy
292 // to avoid things changing out from under is.
293 InstanceToDispatcherMap temp_map = *g_instance_to_dispatcher;
294 for (InstanceToDispatcherMap::iterator i = temp_map.begin();
295 i != temp_map.end(); ++i) {
296 if (i->second == this) {
297 // Synthesize an "instance destroyed" message, this will notify the
298 // plugin and also remove it from our list of tracked plugins.
299 PpapiMsg_PPPInstance_DidDestroy msg(API_ID_PPP_INSTANCE, i->first);
300 OnMessageReceived(msg);
301 }
302 }
303 }
304
OnMsgSupportsInterface(const std::string & interface_name,bool * result)305 void PluginDispatcher::OnMsgSupportsInterface(
306 const std::string& interface_name,
307 bool* result) {
308 *result = !!GetPluginInterface(interface_name);
309
310 // Do fallback for PPP_Instance. This is a hack here and if we have more
311 // cases like this it should be generalized. The PPP_Instance proxy always
312 // proxies the 1.1 interface, and then does fallback to 1.0 inside the
313 // plugin process (see PPP_Instance_Proxy). So here we return true for
314 // supporting the 1.1 interface if either 1.1 or 1.0 is supported.
315 if (!*result && interface_name == PPP_INSTANCE_INTERFACE)
316 *result = !!GetPluginInterface(PPP_INSTANCE_INTERFACE_1_0);
317 }
318
OnMsgSetPreferences(const Preferences & prefs)319 void PluginDispatcher::OnMsgSetPreferences(const Preferences& prefs) {
320 // The renderer may send us preferences more than once (currently this
321 // happens every time a new plugin instance is created). Since we don't have
322 // a way to signal to the plugin that the preferences have changed, changing
323 // the default fonts and such in the middle of a running plugin could be
324 // confusing to it. As a result, we never allow the preferences to be changed
325 // once they're set. The user will have to restart to get new font prefs
326 // propogated to plugins.
327 if (!received_preferences_) {
328 received_preferences_ = true;
329 preferences_ = prefs;
330 }
331 }
332
333 } // namespace proxy
334 } // namespace ppapi
335