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_
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"
20 class SingleThreadTaskRunner
;
25 class SendCallbackHelper
;
27 //-----------------------------------------------------------------------------
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).
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.)
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.
52 // The consumer of IPC::ChannelProxy is responsible for allocating the Thread
53 // instance where the IPC::Channel will be created and operated.
55 class IPC_EXPORT ChannelProxy
: public Sender
, public base::NonThreadSafe
{
57 struct MessageFilterTraits
;
59 // A class that receives messages on the thread where the IPC channel is
60 // running. It can choose to prevent the default action for an IPC message.
61 class IPC_EXPORT MessageFilter
62 : public base::RefCountedThreadSafe
<MessageFilter
, MessageFilterTraits
> {
66 // Called on the background thread to provide the filter with access to the
67 // channel. Called when the IPC channel is initialized or when AddFilter
68 // is called if the channel is already initialized.
69 virtual void OnFilterAdded(Channel
* channel
);
71 // Called on the background thread when the filter has been removed from
72 // the ChannelProxy and when the Channel is closing. After a filter is
73 // removed, it will not be called again.
74 virtual void OnFilterRemoved();
76 // Called to inform the filter that the IPC channel is connected and we
77 // have received the internal Hello message from the peer.
78 virtual void OnChannelConnected(int32 peer_pid
);
80 // Called when there is an error on the channel, typically that the channel
82 virtual void OnChannelError();
84 // Called to inform the filter that the IPC channel will be destroyed.
85 // OnFilterRemoved is called immediately after this.
86 virtual void OnChannelClosing();
88 // Return true to indicate that the message was handled, or false to let
89 // the message be handled in the default way.
90 virtual bool OnMessageReceived(const Message
& message
);
92 // Called when the message filter is about to be deleted. This gives
93 // derived classes the option of controlling which thread they're deleted
95 virtual void OnDestruct() const;
98 virtual ~MessageFilter();
101 friend class base::RefCountedThreadSafe
<MessageFilter
,
102 MessageFilterTraits
>;
105 struct MessageFilterTraits
{
106 static void Destruct(const MessageFilter
* filter
) {
107 filter
->OnDestruct();
112 // Interface for a filter to be imposed on outgoing messages which can
113 // re-write the message. Used mainly for testing.
114 class OutgoingMessageFilter
{
116 // Returns a re-written message, freeing the original, or simply the
117 // original unchanged if no rewrite indicated.
118 virtual Message
*Rewrite(Message
*message
) = 0;
121 // Initializes a channel proxy. The channel_handle and mode parameters are
122 // passed directly to the underlying IPC::Channel. The listener is called on
123 // the thread that creates the ChannelProxy. The filter's OnMessageReceived
124 // method is called on the thread where the IPC::Channel is running. The
125 // filter may be null if the consumer is not interested in handling messages
126 // on the background thread. Any message not handled by the filter will be
127 // dispatched to the listener. The given task runner correspond to a thread
128 // on which IPC::Channel is created and used (e.g. IO thread).
129 ChannelProxy(const IPC::ChannelHandle
& channel_handle
,
132 base::SingleThreadTaskRunner
* ipc_task_runner
);
134 virtual ~ChannelProxy();
136 // Initializes the channel proxy. Only call this once to initialize a channel
137 // proxy that was not initialized in its constructor. If create_pipe_now is
138 // true, the pipe is created synchronously. Otherwise it's created on the IO
140 void Init(const IPC::ChannelHandle
& channel_handle
, Channel::Mode mode
,
141 bool create_pipe_now
);
143 // Close the IPC::Channel. This operation completes asynchronously, once the
144 // background thread processes the command to close the channel. It is ok to
145 // call this method multiple times. Redundant calls are ignored.
147 // WARNING: The MessageFilter object held by the ChannelProxy is also
148 // released asynchronously, and it may in fact have its final reference
149 // released on the background thread. The caller should be careful to deal
150 // with / allow for this possibility.
153 // Send a message asynchronously. The message is routed to the background
154 // thread where it is passed to the IPC::Channel's Send method.
155 virtual bool Send(Message
* message
) OVERRIDE
;
157 // Used to intercept messages as they are received on the background thread.
159 // Ordinarily, messages sent to the ChannelProxy are routed to the matching
160 // listener on the worker thread. This API allows code to intercept messages
161 // before they are sent to the worker thread.
162 // If you call this before the target process is launched, then you're
163 // guaranteed to not miss any messages. But if you call this anytime after,
164 // then some messages might be missed since the filter is added internally on
166 void AddFilter(MessageFilter
* filter
);
167 void RemoveFilter(MessageFilter
* filter
);
169 void set_outgoing_message_filter(OutgoingMessageFilter
* filter
) {
170 outgoing_message_filter_
= filter
;
173 // Called to clear the pointer to the IPC task runner when it's going away.
174 void ClearIPCTaskRunner();
176 // Get the process ID for the connected peer.
177 // Returns base::kNullProcessId if the peer is not connected yet.
178 base::ProcessId
peer_pid() const { return context_
->peer_pid_
; }
180 #if defined(OS_POSIX) && !defined(OS_NACL)
181 // Calls through to the underlying channel's methods.
182 int GetClientFileDescriptor();
183 int TakeClientFileDescriptor();
184 bool GetPeerEuid(uid_t
* peer_euid
) const;
185 #endif // defined(OS_POSIX)
189 // A subclass uses this constructor if it needs to add more information
190 // to the internal state.
191 ChannelProxy(Context
* context
);
193 // Used internally to hold state that is referenced on the IPC thread.
194 class Context
: public base::RefCountedThreadSafe
<Context
>,
197 Context(Listener
* listener
, base::SingleThreadTaskRunner
* ipc_thread
);
198 void ClearIPCTaskRunner();
199 base::SingleThreadTaskRunner
* ipc_task_runner() const {
200 return ipc_task_runner_
;
202 const std::string
& channel_id() const { return channel_id_
; }
204 // Dispatches a message on the listener thread.
205 void OnDispatchMessage(const Message
& message
);
208 friend class base::RefCountedThreadSafe
<Context
>;
211 // IPC::Listener methods:
212 virtual bool OnMessageReceived(const Message
& message
) OVERRIDE
;
213 virtual void OnChannelConnected(int32 peer_pid
) OVERRIDE
;
214 virtual void OnChannelError() OVERRIDE
;
216 // Like OnMessageReceived but doesn't try the filters.
217 bool OnMessageReceivedNoFilter(const Message
& message
);
219 // Gives the filters a chance at processing |message|.
220 // Returns true if the message was processed, false otherwise.
221 bool TryFilters(const Message
& message
);
223 // Like Open and Close, but called on the IPC thread.
224 virtual void OnChannelOpened();
225 virtual void OnChannelClosed();
227 // Called on the consumers thread when the ChannelProxy is closed. At that
228 // point the consumer is telling us that they don't want to receive any
229 // more messages, so we honor that wish by forgetting them!
230 virtual void Clear();
233 friend class ChannelProxy
;
234 friend class SendCallbackHelper
;
236 // Create the Channel
237 void CreateChannel(const IPC::ChannelHandle
& channel_handle
,
238 const Channel::Mode
& mode
);
240 // Methods called on the IO thread.
241 void OnSendMessage(scoped_ptr
<Message
> message_ptr
);
243 void OnRemoveFilter(MessageFilter
* filter
);
245 // Methods called on the listener thread.
246 void AddFilter(MessageFilter
* filter
);
247 void OnDispatchConnected();
248 void OnDispatchError();
250 scoped_refptr
<base::SingleThreadTaskRunner
> listener_task_runner_
;
253 // List of filters. This is only accessed on the IPC thread.
254 std::vector
<scoped_refptr
<MessageFilter
> > filters_
;
255 scoped_refptr
<base::SingleThreadTaskRunner
> ipc_task_runner_
;
256 scoped_ptr
<Channel
> channel_
;
257 std::string channel_id_
;
258 bool channel_connected_called_
;
260 // Holds filters between the AddFilter call on the listerner thread and the
261 // IPC thread when they're added to filters_.
262 std::vector
<scoped_refptr
<MessageFilter
> > pending_filters_
;
263 // Lock for pending_filters_.
264 base::Lock pending_filters_lock_
;
266 // Cached copy of the peer process ID. Set on IPC but read on both IPC and
268 base::ProcessId peer_pid_
;
271 Context
* context() { return context_
; }
273 OutgoingMessageFilter
* outgoing_message_filter() {
274 return outgoing_message_filter_
;
278 friend class SendCallbackHelper
;
280 // By maintaining this indirection (ref-counted) to our internal state, we
281 // can safely be destroyed while the background thread continues to do stuff
282 // that involves this data.
283 scoped_refptr
<Context
> context_
;
285 OutgoingMessageFilter
* outgoing_message_filter_
;
287 // Whether the channel has been initialized.
293 #endif // IPC_IPC_CHANNEL_PROXY_H_