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.
5 #ifndef IPC_IPC_CHANNEL_PROXY_H_
6 #define IPC_IPC_CHANNEL_PROXY_H_
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/message_loop_proxy.h"
14 #include "base/synchronization/lock.h"
15 #include "ipc/ipc_channel.h"
16 #include "ipc/ipc_channel_handle.h"
20 class SendCallbackHelper
;
22 //-----------------------------------------------------------------------------
25 // This class is a helper class that is useful when you wish to run an IPC
26 // channel on a background thread. It provides you with the option of either
27 // handling IPC messages on that background thread or having them dispatched to
28 // your main thread (the thread on which the IPC::ChannelProxy is created).
30 // The API for an IPC::ChannelProxy is very similar to that of an IPC::Channel.
31 // When you send a message to an IPC::ChannelProxy, the message is routed to
32 // the background thread, where it is then passed to the IPC::Channel's Send
33 // method. This means that you can send a message from your thread and your
34 // message will be sent over the IPC channel when possible instead of being
35 // delayed until your thread returns to its message loop. (Often IPC messages
36 // will queue up on the IPC::Channel when there is a lot of traffic, and the
37 // channel will not get cycles to flush its message queue until the thread, on
38 // which it is running, returns to its message loop.)
40 // An IPC::ChannelProxy can have a MessageFilter associated with it, which will
41 // be notified of incoming messages on the IPC::Channel's thread. This gives
42 // the consumer of IPC::ChannelProxy the ability to respond to incoming
43 // messages on this background thread instead of on their own thread, which may
44 // be bogged down with other processing. The result can be greatly improved
45 // latency for messages that can be handled on a background thread.
47 // The consumer of IPC::ChannelProxy is responsible for allocating the Thread
48 // instance where the IPC::Channel will be created and operated.
50 class IPC_EXPORT ChannelProxy
: public Message::Sender
{
53 struct MessageFilterTraits
;
55 // A class that receives messages on the thread where the IPC channel is
56 // running. It can choose to prevent the default action for an IPC message.
57 class IPC_EXPORT MessageFilter
58 : public base::RefCountedThreadSafe
<MessageFilter
, MessageFilterTraits
> {
62 // Called on the background thread to provide the filter with access to the
63 // channel. Called when the IPC channel is initialized or when AddFilter
64 // is called if the channel is already initialized.
65 virtual void OnFilterAdded(Channel
* channel
);
67 // Called on the background thread when the filter has been removed from
68 // the ChannelProxy and when the Channel is closing. After a filter is
69 // removed, it will not be called again.
70 virtual void OnFilterRemoved();
72 // Called to inform the filter that the IPC channel is connected and we
73 // have received the internal Hello message from the peer.
74 virtual void OnChannelConnected(int32 peer_pid
);
76 // Called when there is an error on the channel, typically that the channel
78 virtual void OnChannelError();
80 // Called to inform the filter that the IPC channel will be destroyed.
81 // OnFilterRemoved is called immediately after this.
82 virtual void OnChannelClosing();
84 // Return true to indicate that the message was handled, or false to let
85 // the message be handled in the default way.
86 virtual bool OnMessageReceived(const Message
& message
);
88 // Called when the message filter is about to be deleted. This gives
89 // derived classes the option of controlling which thread they're deleted
91 virtual void OnDestruct() const;
94 virtual ~MessageFilter();
97 friend class base::RefCountedThreadSafe
<MessageFilter
,
101 struct MessageFilterTraits
{
102 static void Destruct(const MessageFilter
* filter
) {
103 filter
->OnDestruct();
108 // Interface for a filter to be imposed on outgoing messages which can
109 // re-write the message. Used mainly for testing.
110 class OutgoingMessageFilter
{
112 // Returns a re-written message, freeing the original, or simply the
113 // original unchanged if no rewrite indicated.
114 virtual Message
*Rewrite(Message
*message
) = 0;
117 // Initializes a channel proxy. The channel_handle and mode parameters are
118 // passed directly to the underlying IPC::Channel. The listener is called on
119 // the thread that creates the ChannelProxy. The filter's OnMessageReceived
120 // method is called on the thread where the IPC::Channel is running. The
121 // filter may be null if the consumer is not interested in handling messages
122 // on the background thread. Any message not handled by the filter will be
123 // dispatched to the listener. The given message loop indicates where the
124 // IPC::Channel should be created.
125 ChannelProxy(const IPC::ChannelHandle
& channel_handle
,
127 Channel::Listener
* listener
,
128 base::MessageLoopProxy
* ipc_thread_loop
);
130 // Creates an uninitialized channel proxy. Init must be called to receive
131 // or send any messages. This two-step setup allows message filters to be
132 // added before any messages are sent or received.
133 ChannelProxy(Channel::Listener
* listener
,
134 base::MessageLoopProxy
* ipc_thread_loop
);
136 virtual ~ChannelProxy();
138 // Initializes the channel proxy. Only call this once to initialize a channel
139 // proxy that was not initialized in its constructor. If create_pipe_now is
140 // true, the pipe is created synchronously. Otherwise it's created on the IO
142 void Init(const IPC::ChannelHandle
& channel_handle
, Channel::Mode mode
,
143 bool create_pipe_now
);
145 // Close the IPC::Channel. This operation completes asynchronously, once the
146 // background thread processes the command to close the channel. It is ok to
147 // call this method multiple times. Redundant calls are ignored.
149 // WARNING: The MessageFilter object held by the ChannelProxy is also
150 // released asynchronously, and it may in fact have its final reference
151 // released on the background thread. The caller should be careful to deal
152 // with / allow for this possibility.
155 // Send a message asynchronously. The message is routed to the background
156 // thread where it is passed to the IPC::Channel's Send method.
157 virtual bool Send(Message
* message
) OVERRIDE
;
159 // Used to intercept messages as they are received on the background thread.
161 // Ordinarily, messages sent to the ChannelProxy are routed to the matching
162 // listener on the worker thread. This API allows code to intercept messages
163 // before they are sent to the worker thread.
164 // If you call this before the target process is launched, then you're
165 // guaranteed to not miss any messages. But if you call this anytime after,
166 // then some messages might be missed since the filter is added internally on
168 void AddFilter(MessageFilter
* filter
);
169 void RemoveFilter(MessageFilter
* filter
);
171 void set_outgoing_message_filter(OutgoingMessageFilter
* filter
) {
172 outgoing_message_filter_
= filter
;
175 // Called to clear the pointer to the IPC message loop when it's going away.
176 void ClearIPCMessageLoop();
178 // Get the process ID for the connected peer.
179 // Returns base::kNullProcessId if the peer is not connected yet.
180 base::ProcessId
peer_pid() const { return context_
->peer_pid_
; }
182 #if defined(OS_POSIX) && !defined(OS_NACL)
183 // Calls through to the underlying channel's methods.
184 int GetClientFileDescriptor();
185 int TakeClientFileDescriptor();
186 bool GetClientEuid(uid_t
* client_euid
) const;
187 #endif // defined(OS_POSIX)
191 // A subclass uses this constructor if it needs to add more information
192 // to the internal state.
193 ChannelProxy(Context
* context
);
195 // Used internally to hold state that is referenced on the IPC thread.
196 class Context
: public base::RefCountedThreadSafe
<Context
>,
197 public Channel::Listener
{
199 Context(Channel::Listener
* listener
, base::MessageLoopProxy
* ipc_thread
);
200 void ClearIPCMessageLoop() { ipc_message_loop_
= NULL
; }
201 base::MessageLoopProxy
* ipc_message_loop() const {
202 return ipc_message_loop_
.get();
204 const std::string
& channel_id() const { return channel_id_
; }
206 // Dispatches a message on the listener thread.
207 void OnDispatchMessage(const Message
& message
);
210 friend class base::RefCountedThreadSafe
<Context
>;
213 // IPC::Channel::Listener methods:
214 virtual bool OnMessageReceived(const Message
& message
) OVERRIDE
;
215 virtual void OnChannelConnected(int32 peer_pid
) OVERRIDE
;
216 virtual void OnChannelError() OVERRIDE
;
218 // Like OnMessageReceived but doesn't try the filters.
219 bool OnMessageReceivedNoFilter(const Message
& message
);
221 // Gives the filters a chance at processing |message|.
222 // Returns true if the message was processed, false otherwise.
223 bool TryFilters(const Message
& message
);
225 // Like Open and Close, but called on the IPC thread.
226 virtual void OnChannelOpened();
227 virtual void OnChannelClosed();
229 // Called on the consumers thread when the ChannelProxy is closed. At that
230 // point the consumer is telling us that they don't want to receive any
231 // more messages, so we honor that wish by forgetting them!
232 virtual void Clear() { listener_
= NULL
; }
235 friend class ChannelProxy
;
236 friend class SendCallbackHelper
;
238 // Create the Channel
239 void CreateChannel(const IPC::ChannelHandle
& channel_handle
,
240 const Channel::Mode
& mode
);
242 // Methods called on the IO thread.
243 void OnSendMessage(scoped_ptr
<Message
> message_ptr
);
245 void OnRemoveFilter(MessageFilter
* filter
);
247 // Methods called on the listener thread.
248 void AddFilter(MessageFilter
* filter
);
249 void OnDispatchConnected();
250 void OnDispatchError();
252 scoped_refptr
<base::MessageLoopProxy
> listener_message_loop_
;
253 Channel::Listener
* listener_
;
255 // List of filters. This is only accessed on the IPC thread.
256 std::vector
<scoped_refptr
<MessageFilter
> > filters_
;
257 scoped_refptr
<base::MessageLoopProxy
> ipc_message_loop_
;
258 scoped_ptr
<Channel
> channel_
;
259 std::string channel_id_
;
260 bool channel_connected_called_
;
262 // Holds filters between the AddFilter call on the listerner thread and the
263 // IPC thread when they're added to filters_.
264 std::vector
<scoped_refptr
<MessageFilter
> > pending_filters_
;
265 // Lock for pending_filters_.
266 base::Lock pending_filters_lock_
;
268 // Cached copy of the peer process ID. Set on IPC but read on both IPC and
270 base::ProcessId peer_pid_
;
273 Context
* context() { return context_
; }
275 OutgoingMessageFilter
* outgoing_message_filter() {
276 return outgoing_message_filter_
;
280 friend class SendCallbackHelper
;
282 // By maintaining this indirection (ref-counted) to our internal state, we
283 // can safely be destroyed while the background thread continues to do stuff
284 // that involves this data.
285 scoped_refptr
<Context
> context_
;
287 OutgoingMessageFilter
* outgoing_message_filter_
;
289 // Whether the channel has been initialized.
295 #endif // IPC_IPC_CHANNEL_PROXY_H_