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