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_endpoint.h"
17 #include "ipc/ipc_listener.h"
18 #include "ipc/ipc_sender.h"
21 class SingleThreadTaskRunner
;
28 class MessageFilterRouter
;
29 class SendCallbackHelper
;
31 //-----------------------------------------------------------------------------
34 // This class is a helper class that is useful when you wish to run an IPC
35 // channel on a background thread. It provides you with the option of either
36 // handling IPC messages on that background thread or having them dispatched to
37 // your main thread (the thread on which the IPC::ChannelProxy is created).
39 // The API for an IPC::ChannelProxy is very similar to that of an IPC::Channel.
40 // When you send a message to an IPC::ChannelProxy, the message is routed to
41 // the background thread, where it is then passed to the IPC::Channel's Send
42 // method. This means that you can send a message from your thread and your
43 // message will be sent over the IPC channel when possible instead of being
44 // delayed until your thread returns to its message loop. (Often IPC messages
45 // will queue up on the IPC::Channel when there is a lot of traffic, and the
46 // channel will not get cycles to flush its message queue until the thread, on
47 // which it is running, returns to its message loop.)
49 // An IPC::ChannelProxy can have a MessageFilter associated with it, which will
50 // be notified of incoming messages on the IPC::Channel's thread. This gives
51 // the consumer of IPC::ChannelProxy the ability to respond to incoming
52 // messages on this background thread instead of on their own thread, which may
53 // be bogged down with other processing. The result can be greatly improved
54 // latency for messages that can be handled on a background thread.
56 // The consumer of IPC::ChannelProxy is responsible for allocating the Thread
57 // instance where the IPC::Channel will be created and operated.
61 // If a particular |Channel| implementation has a thread-safe |Send()| operation
62 // then ChannelProxy skips the inter-thread hop and calls |Send()| directly. In
63 // this case the |channel_| variable is touched by multiple threads so
64 // |channel_lifetime_lock_| is used to protect it. The locking overhead is only
65 // paid if the underlying channel supports thread-safe |Send|.
67 class IPC_EXPORT ChannelProxy
: public Endpoint
, public base::NonThreadSafe
{
69 #if defined(ENABLE_IPC_FUZZER)
70 // Interface for a filter to be imposed on outgoing messages which can
71 // re-write the message. Used for testing.
72 class OutgoingMessageFilter
{
74 virtual Message
* Rewrite(Message
* message
) = 0;
78 // Initializes a channel proxy. The channel_handle and mode parameters are
79 // passed directly to the underlying IPC::Channel. The listener is called on
80 // the thread that creates the ChannelProxy. The filter's OnMessageReceived
81 // method is called on the thread where the IPC::Channel is running. The
82 // filter may be null if the consumer is not interested in handling messages
83 // on the background thread. Any message not handled by the filter will be
84 // dispatched to the listener. The given task runner correspond to a thread
85 // on which IPC::Channel is created and used (e.g. IO thread).
86 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
87 // make the upcoming refactor decomposable into smaller CLs.
88 // http://crbug.com/493414.
89 static scoped_ptr
<ChannelProxy
> Create(
90 const IPC::ChannelHandle
& channel_handle
,
93 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
,
94 AttachmentBroker
* broker
= nullptr);
96 static scoped_ptr
<ChannelProxy
> Create(
97 scoped_ptr
<ChannelFactory
> factory
,
99 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
);
101 ~ChannelProxy() override
;
103 // Initializes the channel proxy. Only call this once to initialize a channel
104 // proxy that was not initialized in its constructor. If create_pipe_now is
105 // true, the pipe is created synchronously. Otherwise it's created on the IO
107 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
108 // make the upcoming refactor decomposable into smaller CLs.
109 // http://crbug.com/493414.
110 void Init(const IPC::ChannelHandle
& channel_handle
,
112 bool create_pipe_now
,
113 AttachmentBroker
* broker
= nullptr);
114 void Init(scoped_ptr
<ChannelFactory
> factory
, bool create_pipe_now
);
116 // Close the IPC::Channel. This operation completes asynchronously, once the
117 // background thread processes the command to close the channel. It is ok to
118 // call this method multiple times. Redundant calls are ignored.
120 // WARNING: MessageFilter objects held by the ChannelProxy is also
121 // released asynchronously, and it may in fact have its final reference
122 // released on the background thread. The caller should be careful to deal
123 // with / allow for this possibility.
126 // Send a message asynchronously. The message is routed to the background
127 // thread where it is passed to the IPC::Channel's Send method.
128 bool Send(Message
* message
) override
;
130 // Used to intercept messages as they are received on the background thread.
132 // Ordinarily, messages sent to the ChannelProxy are routed to the matching
133 // listener on the worker thread. This API allows code to intercept messages
134 // before they are sent to the worker thread.
135 // If you call this before the target process is launched, then you're
136 // guaranteed to not miss any messages. But if you call this anytime after,
137 // then some messages might be missed since the filter is added internally on
139 void AddFilter(MessageFilter
* filter
);
140 void RemoveFilter(MessageFilter
* filter
);
142 #if defined(ENABLE_IPC_FUZZER)
143 void set_outgoing_message_filter(OutgoingMessageFilter
* filter
) {
144 outgoing_message_filter_
= filter
;
148 // Called to clear the pointer to the IPC task runner when it's going away.
149 void ClearIPCTaskRunner();
151 // Endpoint overrides.
152 base::ProcessId
GetPeerPID() const override
;
153 void OnSetAttachmentBrokerEndpoint() override
;
155 #if defined(OS_POSIX) && !defined(OS_NACL_SFI)
156 // Calls through to the underlying channel's methods.
157 int GetClientFileDescriptor();
158 base::ScopedFD
TakeClientFileDescriptor();
163 // A subclass uses this constructor if it needs to add more information
164 // to the internal state.
165 ChannelProxy(Context
* context
);
169 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_task_runner
);
171 // Used internally to hold state that is referenced on the IPC thread.
172 class Context
: public base::RefCountedThreadSafe
<Context
>,
175 Context(Listener
* listener
,
176 const scoped_refptr
<base::SingleThreadTaskRunner
>& ipc_thread
);
177 void ClearIPCTaskRunner();
178 base::SingleThreadTaskRunner
* ipc_task_runner() const {
179 return ipc_task_runner_
.get();
181 const std::string
& channel_id() const { return channel_id_
; }
183 // Dispatches a message on the listener thread.
184 void OnDispatchMessage(const Message
& message
);
186 // Sends |message| from appropriate thread.
187 void Send(Message
* message
);
189 // Indicates if the underlying channel's Send is thread-safe.
190 bool IsChannelSendThreadSafe() const;
193 friend class base::RefCountedThreadSafe
<Context
>;
196 // IPC::Listener methods:
197 bool OnMessageReceived(const Message
& message
) override
;
198 void OnChannelConnected(int32_t peer_pid
) override
;
199 void OnChannelError() override
;
201 // Like OnMessageReceived but doesn't try the filters.
202 bool OnMessageReceivedNoFilter(const Message
& message
);
204 // Gives the filters a chance at processing |message|.
205 // Returns true if the message was processed, false otherwise.
206 bool TryFilters(const Message
& message
);
208 // Like Open and Close, but called on the IPC thread.
209 virtual void OnChannelOpened();
210 virtual void OnChannelClosed();
212 // Called on the consumers thread when the ChannelProxy is closed. At that
213 // point the consumer is telling us that they don't want to receive any
214 // more messages, so we honor that wish by forgetting them!
215 virtual void Clear();
218 friend class ChannelProxy
;
219 friend class IpcSecurityTestUtil
;
221 // Create the Channel
222 void CreateChannel(scoped_ptr
<ChannelFactory
> factory
);
224 void set_attachment_broker_endpoint(bool is_endpoint
) {
225 attachment_broker_endpoint_
= is_endpoint
;
228 // Methods called on the IO thread.
229 void OnSendMessage(scoped_ptr
<Message
> message_ptr
);
231 void OnRemoveFilter(MessageFilter
* filter
);
233 // Methods called on the listener thread.
234 void AddFilter(MessageFilter
* filter
);
235 void OnDispatchConnected();
236 void OnDispatchError();
237 void OnDispatchBadMessage(const Message
& message
);
239 void SendFromThisThread(Message
* message
);
242 scoped_refptr
<base::SingleThreadTaskRunner
> listener_task_runner_
;
245 // List of filters. This is only accessed on the IPC thread.
246 std::vector
<scoped_refptr
<MessageFilter
> > filters_
;
247 scoped_refptr
<base::SingleThreadTaskRunner
> ipc_task_runner_
;
249 // Note, channel_ may be set on the Listener thread or the IPC thread.
250 // But once it has been set, it must only be read or cleared on the IPC
252 // One exception is the thread-safe send. See the class comment.
253 scoped_ptr
<Channel
> channel_
;
254 std::string channel_id_
;
255 bool channel_connected_called_
;
257 // Lock for |channel_| value. This is only relevant in the context of
259 base::Lock channel_lifetime_lock_
;
260 // Indicates the thread-safe send availability. This is constant once
261 // |channel_| is set.
262 bool channel_send_thread_safe_
;
264 // Routes a given message to a proper subset of |filters_|, depending
265 // on which message classes a filter might support.
266 scoped_ptr
<MessageFilterRouter
> message_filter_router_
;
268 // Holds filters between the AddFilter call on the listerner thread and the
269 // IPC thread when they're added to filters_.
270 std::vector
<scoped_refptr
<MessageFilter
> > pending_filters_
;
271 // Lock for pending_filters_.
272 base::Lock pending_filters_lock_
;
274 // Cached copy of the peer process ID. Set on IPC but read on both IPC and
276 base::ProcessId peer_pid_
;
278 // Whether this channel is used as an endpoint for sending and receiving
279 // brokerable attachment messages to/from the broker process.
280 bool attachment_broker_endpoint_
;
283 Context
* context() { return context_
.get(); }
285 #if defined(ENABLE_IPC_FUZZER)
286 OutgoingMessageFilter
* outgoing_message_filter() const {
287 return outgoing_message_filter_
;
292 bool did_init() const { return did_init_
; }
295 friend class IpcSecurityTestUtil
;
297 // Always called once immediately after Init.
298 virtual void OnChannelInit();
300 // By maintaining this indirection (ref-counted) to our internal state, we
301 // can safely be destroyed while the background thread continues to do stuff
302 // that involves this data.
303 scoped_refptr
<Context
> context_
;
305 // Whether the channel has been initialized.
308 #if defined(ENABLE_IPC_FUZZER)
309 OutgoingMessageFilter
* outgoing_message_filter_
;
315 #endif // IPC_IPC_CHANNEL_PROXY_H_