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