ExtensionInstallDialogView: fix scrolling behavior on Views (Win,Linux)
[chromium-blink-merge.git] / ipc / ipc_channel_proxy.h
blob73cb7e023ee79a2332eff7285348effd40d863f0
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_
8 #include <vector>
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"
19 namespace base {
20 class SingleThreadTaskRunner;
23 namespace IPC {
25 class ChannelFactory;
26 class MessageFilter;
27 class MessageFilterRouter;
28 class SendCallbackHelper;
30 //-----------------------------------------------------------------------------
31 // IPC::ChannelProxy
33 // This class is a helper class that is useful when you wish to run an IPC
34 // channel on a background thread. It provides you with the option of either
35 // handling IPC messages on that background thread or having them dispatched to
36 // your main thread (the thread on which the IPC::ChannelProxy is created).
38 // The API for an IPC::ChannelProxy is very similar to that of an IPC::Channel.
39 // When you send a message to an IPC::ChannelProxy, the message is routed to
40 // the background thread, where it is then passed to the IPC::Channel's Send
41 // method. This means that you can send a message from your thread and your
42 // message will be sent over the IPC channel when possible instead of being
43 // delayed until your thread returns to its message loop. (Often IPC messages
44 // will queue up on the IPC::Channel when there is a lot of traffic, and the
45 // channel will not get cycles to flush its message queue until the thread, on
46 // which it is running, returns to its message loop.)
48 // An IPC::ChannelProxy can have a MessageFilter associated with it, which will
49 // be notified of incoming messages on the IPC::Channel's thread. This gives
50 // the consumer of IPC::ChannelProxy the ability to respond to incoming
51 // messages on this background thread instead of on their own thread, which may
52 // be bogged down with other processing. The result can be greatly improved
53 // latency for messages that can be handled on a background thread.
55 // The consumer of IPC::ChannelProxy is responsible for allocating the Thread
56 // instance where the IPC::Channel will be created and operated.
58 // Thread-safe send
60 // If a particular |Channel| implementation has a thread-safe |Send()| operation
61 // then ChannelProxy skips the inter-thread hop and calls |Send()| directly. In
62 // this case the |channel_| variable is touched by multiple threads so
63 // |channel_lifetime_lock_| is used to protect it. The locking overhead is only
64 // paid if the underlying channel supports thread-safe |Send|.
66 class IPC_EXPORT ChannelProxy : public Sender, public base::NonThreadSafe {
67 public:
68 #if defined(ENABLE_IPC_FUZZER)
69 // Interface for a filter to be imposed on outgoing messages which can
70 // re-write the message. Used for testing.
71 class OutgoingMessageFilter {
72 public:
73 virtual Message* Rewrite(Message* message) = 0;
75 #endif
77 // Initializes a channel proxy. The channel_handle and mode parameters are
78 // passed directly to the underlying IPC::Channel. The listener is called on
79 // the thread that creates the ChannelProxy. The filter's OnMessageReceived
80 // method is called on the thread where the IPC::Channel is running. The
81 // filter may be null if the consumer is not interested in handling messages
82 // on the background thread. Any message not handled by the filter will be
83 // dispatched to the listener. The given task runner correspond to a thread
84 // on which IPC::Channel is created and used (e.g. IO thread).
85 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
86 // make the upcoming refactor decomposable into smaller CLs.
87 // http://crbug.com/493414.
88 static scoped_ptr<ChannelProxy> Create(
89 const IPC::ChannelHandle& channel_handle,
90 Channel::Mode mode,
91 Listener* listener,
92 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner,
93 AttachmentBroker* broker = nullptr);
95 static scoped_ptr<ChannelProxy> Create(
96 scoped_ptr<ChannelFactory> factory,
97 Listener* listener,
98 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
100 ~ChannelProxy() override;
102 // Initializes the channel proxy. Only call this once to initialize a channel
103 // proxy that was not initialized in its constructor. If create_pipe_now is
104 // true, the pipe is created synchronously. Otherwise it's created on the IO
105 // thread.
106 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
107 // make the upcoming refactor decomposable into smaller CLs.
108 // http://crbug.com/493414.
109 void Init(const IPC::ChannelHandle& channel_handle,
110 Channel::Mode mode,
111 bool create_pipe_now,
112 AttachmentBroker* broker = nullptr);
113 void Init(scoped_ptr<ChannelFactory> factory, bool create_pipe_now);
115 // Close the IPC::Channel. This operation completes asynchronously, once the
116 // background thread processes the command to close the channel. It is ok to
117 // call this method multiple times. Redundant calls are ignored.
119 // WARNING: MessageFilter objects held by the ChannelProxy is also
120 // released asynchronously, and it may in fact have its final reference
121 // released on the background thread. The caller should be careful to deal
122 // with / allow for this possibility.
123 void Close();
125 // Send a message asynchronously. The message is routed to the background
126 // thread where it is passed to the IPC::Channel's Send method.
127 bool Send(Message* message) override;
129 // Used to intercept messages as they are received on the background thread.
131 // Ordinarily, messages sent to the ChannelProxy are routed to the matching
132 // listener on the worker thread. This API allows code to intercept messages
133 // before they are sent to the worker thread.
134 // If you call this before the target process is launched, then you're
135 // guaranteed to not miss any messages. But if you call this anytime after,
136 // then some messages might be missed since the filter is added internally on
137 // the IO thread.
138 void AddFilter(MessageFilter* filter);
139 void RemoveFilter(MessageFilter* filter);
141 #if defined(ENABLE_IPC_FUZZER)
142 void set_outgoing_message_filter(OutgoingMessageFilter* filter) {
143 outgoing_message_filter_ = filter;
145 #endif
147 // Set the task runner on which dispatched messages are posted. Both the new
148 // task runner and the existing task runner must run on the same thread, and
149 // must belong to the calling thread.
150 void SetListenerTaskRunner(
151 scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner);
153 // Called to clear the pointer to the IPC task runner when it's going away.
154 void ClearIPCTaskRunner();
156 // Get the process ID for the connected peer.
157 // Returns base::kNullProcessId if the peer is not connected yet.
158 base::ProcessId GetPeerPID() const { return context_->peer_pid_; }
160 #if defined(OS_POSIX) && !defined(OS_NACL_SFI)
161 // Calls through to the underlying channel's methods.
162 int GetClientFileDescriptor();
163 base::ScopedFD TakeClientFileDescriptor();
164 #endif
166 protected:
167 class Context;
168 // A subclass uses this constructor if it needs to add more information
169 // to the internal state.
170 ChannelProxy(Context* context);
172 ChannelProxy(
173 Listener* listener,
174 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
176 // Used internally to hold state that is referenced on the IPC thread.
177 class Context : public base::RefCountedThreadSafe<Context>,
178 public Listener {
179 public:
180 Context(Listener* listener,
181 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_thread);
182 void ClearIPCTaskRunner();
183 void SetListenerTaskRunner(
184 scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner);
185 base::SingleThreadTaskRunner* ipc_task_runner() const {
186 return ipc_task_runner_.get();
188 const std::string& channel_id() const { return channel_id_; }
190 // Dispatches a message on the listener thread.
191 void OnDispatchMessage(const Message& message);
193 // Sends |message| from appropriate thread.
194 void Send(Message* message);
196 protected:
197 friend class base::RefCountedThreadSafe<Context>;
198 ~Context() override;
200 // IPC::Listener methods:
201 bool OnMessageReceived(const Message& message) override;
202 void OnChannelConnected(int32 peer_pid) override;
203 void OnChannelError() override;
205 // Like OnMessageReceived but doesn't try the filters.
206 bool OnMessageReceivedNoFilter(const Message& message);
208 // Gives the filters a chance at processing |message|.
209 // Returns true if the message was processed, false otherwise.
210 bool TryFilters(const Message& message);
212 // Like Open and Close, but called on the IPC thread.
213 virtual void OnChannelOpened();
214 virtual void OnChannelClosed();
216 // Called on the consumers thread when the ChannelProxy is closed. At that
217 // point the consumer is telling us that they don't want to receive any
218 // more messages, so we honor that wish by forgetting them!
219 virtual void Clear();
221 private:
222 friend class ChannelProxy;
223 friend class IpcSecurityTestUtil;
225 // Create the Channel
226 void CreateChannel(scoped_ptr<ChannelFactory> factory);
228 // Methods called on the IO thread.
229 void OnSendMessage(scoped_ptr<Message> message_ptr);
230 void OnAddFilter();
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);
240 void ClearChannel();
242 scoped_refptr<base::SingleThreadTaskRunner> listener_task_runner_;
243 Listener* listener_;
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
251 // thread.
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
258 // thread-safe send.
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
275 // listener threads.
276 base::ProcessId peer_pid_;
279 Context* context() { return context_.get(); }
281 #if defined(ENABLE_IPC_FUZZER)
282 OutgoingMessageFilter* outgoing_message_filter() const {
283 return outgoing_message_filter_;
285 #endif
287 private:
288 friend class IpcSecurityTestUtil;
290 // By maintaining this indirection (ref-counted) to our internal state, we
291 // can safely be destroyed while the background thread continues to do stuff
292 // that involves this data.
293 scoped_refptr<Context> context_;
295 // Whether the channel has been initialized.
296 bool did_init_;
298 #if defined(ENABLE_IPC_FUZZER)
299 OutgoingMessageFilter* outgoing_message_filter_;
300 #endif
303 } // namespace IPC
305 #endif // IPC_IPC_CHANNEL_PROXY_H_