Home | History | Annotate | Download | only in proxy
      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 
     54 InstanceData::InstanceData()
     55     : is_request_surrounding_text_pending(false),
     56       should_do_request_surrounding_text(false) {
     57 }
     58 
     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 
     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 
     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
     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
    105 PluginDispatcher* PluginDispatcher::GetForResource(const Resource* resource) {
    106   return GetForInstance(resource->pp_instance());
    107 }
    108 
    109 // static
    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
    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 
    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 
    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 
    182 bool PluginDispatcher::IsPlugin() const {
    183   return true;
    184 }
    185 
    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 
    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 
    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 
    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 
    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 
    256   instance_map_[instance] = InstanceData();
    257 }
    258 
    259 void PluginDispatcher::DidDestroyInstance(PP_Instance instance) {
    260   InstanceDataMap::iterator it = instance_map_.find(instance);
    261   if (it != instance_map_.end())
    262     instance_map_.erase(it);
    263 
    264   if (g_instance_to_dispatcher) {
    265     InstanceToDispatcherMap::iterator found = g_instance_to_dispatcher->find(
    266         instance);
    267     if (found != g_instance_to_dispatcher->end()) {
    268       DCHECK(found->second == this);
    269       g_instance_to_dispatcher->erase(found);
    270     } else {
    271       NOTREACHED();
    272     }
    273   }
    274 }
    275 
    276 InstanceData* PluginDispatcher::GetInstanceData(PP_Instance instance) {
    277   InstanceDataMap::iterator it = instance_map_.find(instance);
    278   return (it == instance_map_.end()) ? NULL : &it->second;
    279 }
    280 
    281 thunk::PPB_Instance_API* PluginDispatcher::GetInstanceAPI() {
    282   return static_cast<PPB_Instance_Proxy*>(
    283       GetInterfaceProxy(API_ID_PPB_INSTANCE));
    284 }
    285 
    286 thunk::ResourceCreationAPI* PluginDispatcher::GetResourceCreationAPI() {
    287   return static_cast<ResourceCreationProxy*>(
    288       GetInterfaceProxy(API_ID_RESOURCE_CREATION));
    289 }
    290 
    291 void PluginDispatcher::ForceFreeAllInstances() {
    292   if (!g_instance_to_dispatcher)
    293     return;
    294 
    295   // Iterating will remove each item from the map, so we need to make a copy
    296   // to avoid things changing out from under is.
    297   InstanceToDispatcherMap temp_map = *g_instance_to_dispatcher;
    298   for (InstanceToDispatcherMap::iterator i = temp_map.begin();
    299        i != temp_map.end(); ++i) {
    300     if (i->second == this) {
    301       // Synthesize an "instance destroyed" message, this will notify the
    302       // plugin and also remove it from our list of tracked plugins.
    303       PpapiMsg_PPPInstance_DidDestroy msg(API_ID_PPP_INSTANCE, i->first);
    304       OnMessageReceived(msg);
    305     }
    306   }
    307 }
    308 
    309 void PluginDispatcher::OnMsgSupportsInterface(
    310     const std::string& interface_name,
    311     bool* result) {
    312   *result = !!GetPluginInterface(interface_name);
    313 
    314   // Do fallback for PPP_Instance. This is a hack here and if we have more
    315   // cases like this it should be generalized. The PPP_Instance proxy always
    316   // proxies the 1.1 interface, and then does fallback to 1.0 inside the
    317   // plugin process (see PPP_Instance_Proxy). So here we return true for
    318   // supporting the 1.1 interface if either 1.1 or 1.0 is supported.
    319   if (!*result && interface_name == PPP_INSTANCE_INTERFACE)
    320     *result = !!GetPluginInterface(PPP_INSTANCE_INTERFACE_1_0);
    321 }
    322 
    323 void PluginDispatcher::OnMsgSetPreferences(const Preferences& prefs) {
    324   // The renderer may send us preferences more than once (currently this
    325   // happens every time a new plugin instance is created). Since we don't have
    326   // a way to signal to the plugin that the preferences have changed, changing
    327   // the default fonts and such in the middle of a running plugin could be
    328   // confusing to it. As a result, we never allow the preferences to be changed
    329   // once they're set. The user will have to restart to get new font prefs
    330   // propogated to plugins.
    331   if (!received_preferences_) {
    332     received_preferences_ = true;
    333     preferences_ = prefs;
    334   }
    335 }
    336 
    337 }  // namespace proxy
    338 }  // namespace ppapi
    339