Home | History | Annotate | Download | only in ipc
      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 #ifndef IPC_IPC_CHANNEL_PROXY_H_
      6 #define IPC_IPC_CHANNEL_PROXY_H_
      7 
      8 #include <vector>
      9 
     10 #include "base/memory/ref_counted.h"
     11 #include "base/memory/scoped_ptr.h"
     12 #include "base/synchronization/lock.h"
     13 #include "base/threading/non_thread_safe.h"
     14 #include "ipc/ipc_channel.h"
     15 #include "ipc/ipc_channel_handle.h"
     16 #include "ipc/ipc_listener.h"
     17 #include "ipc/ipc_sender.h"
     18 
     19 namespace base {
     20 class SingleThreadTaskRunner;
     21 }
     22 
     23 namespace IPC {
     24 
     25 class ChannelFactory;
     26 class MessageFilter;
     27 class MessageFilterRouter;
     28 class SendCallbackHelper;
     29 
     30 //-----------------------------------------------------------------------------
     31 // IPC::ChannelProxy
     32 //
     33 // This class is a helper class that is useful when you wish to run an IPC
     34 // channel on a background thread.  It provides you with the option of either
     35 // handling IPC messages on that background thread or having them dispatched to
     36 // your main thread (the thread on which the IPC::ChannelProxy is created).
     37 //
     38 // The API for an IPC::ChannelProxy is very similar to that of an IPC::Channel.
     39 // When you send a message to an IPC::ChannelProxy, the message is routed to
     40 // the background thread, where it is then passed to the IPC::Channel's Send
     41 // method.  This means that you can send a message from your thread and your
     42 // message will be sent over the IPC channel when possible instead of being
     43 // delayed until your thread returns to its message loop.  (Often IPC messages
     44 // will queue up on the IPC::Channel when there is a lot of traffic, and the
     45 // channel will not get cycles to flush its message queue until the thread, on
     46 // which it is running, returns to its message loop.)
     47 //
     48 // An IPC::ChannelProxy can have a MessageFilter associated with it, which will
     49 // be notified of incoming messages on the IPC::Channel's thread.  This gives
     50 // the consumer of IPC::ChannelProxy the ability to respond to incoming
     51 // messages on this background thread instead of on their own thread, which may
     52 // be bogged down with other processing.  The result can be greatly improved
     53 // latency for messages that can be handled on a background thread.
     54 //
     55 // The consumer of IPC::ChannelProxy is responsible for allocating the Thread
     56 // instance where the IPC::Channel will be created and operated.
     57 //
     58 class IPC_EXPORT ChannelProxy : public Sender, public base::NonThreadSafe {
     59  public:
     60   // Initializes a channel proxy.  The channel_handle and mode parameters are
     61   // passed directly to the underlying IPC::Channel.  The listener is called on
     62   // the thread that creates the ChannelProxy.  The filter's OnMessageReceived
     63   // method is called on the thread where the IPC::Channel is running.  The
     64   // filter may be null if the consumer is not interested in handling messages
     65   // on the background thread.  Any message not handled by the filter will be
     66   // dispatched to the listener.  The given task runner correspond to a thread
     67   // on which IPC::Channel is created and used (e.g. IO thread).
     68   static scoped_ptr<ChannelProxy> Create(
     69       const IPC::ChannelHandle& channel_handle,
     70       Channel::Mode mode,
     71       Listener* listener,
     72       const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
     73 
     74   static scoped_ptr<ChannelProxy> Create(
     75       scoped_ptr<ChannelFactory> factory,
     76       Listener* listener,
     77       const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
     78 
     79   virtual ~ChannelProxy();
     80 
     81   // Initializes the channel proxy. Only call this once to initialize a channel
     82   // proxy that was not initialized in its constructor. If create_pipe_now is
     83   // true, the pipe is created synchronously. Otherwise it's created on the IO
     84   // thread.
     85   void Init(const IPC::ChannelHandle& channel_handle, Channel::Mode mode,
     86             bool create_pipe_now);
     87   void Init(scoped_ptr<ChannelFactory> factory, bool create_pipe_now);
     88 
     89   // Close the IPC::Channel.  This operation completes asynchronously, once the
     90   // background thread processes the command to close the channel.  It is ok to
     91   // call this method multiple times.  Redundant calls are ignored.
     92   //
     93   // WARNING: MessageFilter objects held by the ChannelProxy is also
     94   // released asynchronously, and it may in fact have its final reference
     95   // released on the background thread.  The caller should be careful to deal
     96   // with / allow for this possibility.
     97   void Close();
     98 
     99   // Send a message asynchronously.  The message is routed to the background
    100   // thread where it is passed to the IPC::Channel's Send method.
    101   virtual bool Send(Message* message) OVERRIDE;
    102 
    103   // Used to intercept messages as they are received on the background thread.
    104   //
    105   // Ordinarily, messages sent to the ChannelProxy are routed to the matching
    106   // listener on the worker thread.  This API allows code to intercept messages
    107   // before they are sent to the worker thread.
    108   // If you call this before the target process is launched, then you're
    109   // guaranteed to not miss any messages.  But if you call this anytime after,
    110   // then some messages might be missed since the filter is added internally on
    111   // the IO thread.
    112   void AddFilter(MessageFilter* filter);
    113   void RemoveFilter(MessageFilter* filter);
    114 
    115   // Called to clear the pointer to the IPC task runner when it's going away.
    116   void ClearIPCTaskRunner();
    117 
    118   // Get the process ID for the connected peer.
    119   // Returns base::kNullProcessId if the peer is not connected yet.
    120   base::ProcessId GetPeerPID() const { return context_->peer_pid_; }
    121 
    122 #if defined(OS_POSIX) && !defined(OS_NACL)
    123   // Calls through to the underlying channel's methods.
    124   int GetClientFileDescriptor();
    125   int TakeClientFileDescriptor();
    126 #endif  // defined(OS_POSIX)
    127 
    128  protected:
    129   class Context;
    130   // A subclass uses this constructor if it needs to add more information
    131   // to the internal state.
    132   ChannelProxy(Context* context);
    133 
    134   ChannelProxy(
    135       Listener* listener,
    136       const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
    137 
    138   // Used internally to hold state that is referenced on the IPC thread.
    139   class Context : public base::RefCountedThreadSafe<Context>,
    140                   public Listener {
    141    public:
    142     Context(Listener* listener,
    143             const scoped_refptr<base::SingleThreadTaskRunner>& ipc_thread);
    144     void ClearIPCTaskRunner();
    145     base::SingleThreadTaskRunner* ipc_task_runner() const {
    146       return ipc_task_runner_.get();
    147     }
    148     const std::string& channel_id() const { return channel_id_; }
    149 
    150     // Dispatches a message on the listener thread.
    151     void OnDispatchMessage(const Message& message);
    152 
    153    protected:
    154     friend class base::RefCountedThreadSafe<Context>;
    155     virtual ~Context();
    156 
    157     // IPC::Listener methods:
    158     virtual bool OnMessageReceived(const Message& message) OVERRIDE;
    159     virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
    160     virtual void OnChannelError() OVERRIDE;
    161 
    162     // Like OnMessageReceived but doesn't try the filters.
    163     bool OnMessageReceivedNoFilter(const Message& message);
    164 
    165     // Gives the filters a chance at processing |message|.
    166     // Returns true if the message was processed, false otherwise.
    167     bool TryFilters(const Message& message);
    168 
    169     // Like Open and Close, but called on the IPC thread.
    170     virtual void OnChannelOpened();
    171     virtual void OnChannelClosed();
    172 
    173     // Called on the consumers thread when the ChannelProxy is closed.  At that
    174     // point the consumer is telling us that they don't want to receive any
    175     // more messages, so we honor that wish by forgetting them!
    176     virtual void Clear();
    177 
    178    private:
    179     friend class ChannelProxy;
    180     friend class SendCallbackHelper;
    181 
    182     // Create the Channel
    183     void CreateChannel(scoped_ptr<ChannelFactory> factory);
    184 
    185     // Methods called on the IO thread.
    186     void OnSendMessage(scoped_ptr<Message> message_ptr);
    187     void OnAddFilter();
    188     void OnRemoveFilter(MessageFilter* filter);
    189 
    190     // Methods called on the listener thread.
    191     void AddFilter(MessageFilter* filter);
    192     void OnDispatchConnected();
    193     void OnDispatchError();
    194     void OnDispatchBadMessage(const Message& message);
    195 
    196     scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner_;
    197     Listener* listener_;
    198 
    199     // List of filters.  This is only accessed on the IPC thread.
    200     std::vector<scoped_refptr<MessageFilter> > filters_;
    201     scoped_refptr<base::SingleThreadTaskRunner> ipc_task_runner_;
    202 
    203     // Note, channel_ may be set on the Listener thread or the IPC thread.
    204     // But once it has been set, it must only be read or cleared on the IPC
    205     // thread.
    206     scoped_ptr<Channel> channel_;
    207     std::string channel_id_;
    208     bool channel_connected_called_;
    209 
    210     // Routes a given message to a proper subset of |filters_|, depending
    211     // on which message classes a filter might support.
    212     scoped_ptr<MessageFilterRouter> message_filter_router_;
    213 
    214     // Holds filters between the AddFilter call on the listerner thread and the
    215     // IPC thread when they're added to filters_.
    216     std::vector<scoped_refptr<MessageFilter> > pending_filters_;
    217     // Lock for pending_filters_.
    218     base::Lock pending_filters_lock_;
    219 
    220     // Cached copy of the peer process ID. Set on IPC but read on both IPC and
    221     // listener threads.
    222     base::ProcessId peer_pid_;
    223   };
    224 
    225   Context* context() { return context_.get(); }
    226 
    227  private:
    228   friend class SendCallbackHelper;
    229 
    230   // By maintaining this indirection (ref-counted) to our internal state, we
    231   // can safely be destroyed while the background thread continues to do stuff
    232   // that involves this data.
    233   scoped_refptr<Context> context_;
    234 
    235   // Whether the channel has been initialized.
    236   bool did_init_;
    237 };
    238 
    239 }  // namespace IPC
    240 
    241 #endif  // IPC_IPC_CHANNEL_PROXY_H_
    242