Tizen 2.1 base
[platform/upstream/chromium.git] / ipc / ipc_channel_proxy.h
1 // Copyright (c) 2011 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 #pragma once
8
9 #include <vector>
10
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"
17
18 namespace IPC {
19
20 class SendTask;
21
22 //-----------------------------------------------------------------------------
23 // IPC::ChannelProxy
24 //
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).
29 //
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.)
39 //
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.
46 //
47 // The consumer of IPC::ChannelProxy is responsible for allocating the Thread
48 // instance where the IPC::Channel will be created and operated.
49 //
50 class IPC_EXPORT ChannelProxy : public Message::Sender {
51  public:
52
53   struct MessageFilterTraits;
54
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> {
59    public:
60     MessageFilter();
61     virtual ~MessageFilter();
62
63     // Called on the background thread to provide the filter with access to the
64     // channel.  Called when the IPC channel is initialized or when AddFilter
65     // is called if the channel is already initialized.
66     virtual void OnFilterAdded(Channel* channel);
67
68     // Called on the background thread when the filter has been removed from
69     // the ChannelProxy and when the Channel is closing.  After a filter is
70     // removed, it will not be called again.
71     virtual void OnFilterRemoved();
72
73     // Called to inform the filter that the IPC channel is connected and we
74     // have received the internal Hello message from the peer.
75     virtual void OnChannelConnected(int32 peer_pid);
76
77     // Called when there is an error on the channel, typically that the channel
78     // has been closed.
79     virtual void OnChannelError();
80
81     // Called to inform the filter that the IPC channel will be destroyed.
82     // OnFilterRemoved is called immediately after this.
83     virtual void OnChannelClosing();
84
85     // Return true to indicate that the message was handled, or false to let
86     // the message be handled in the default way.
87     virtual bool OnMessageReceived(const Message& message);
88
89     // Called when the message filter is about to be deleted.  This gives
90     // derived classes the option of controlling which thread they're deleted
91     // on etc.
92     virtual void OnDestruct() const;
93   };
94
95   struct MessageFilterTraits {
96     static void Destruct(const MessageFilter* filter) {
97       filter->OnDestruct();
98     }
99   };
100
101   // Interface for a filter to be imposed on outgoing messages which can
102   // re-write the message.  Used mainly for testing.
103   class OutgoingMessageFilter {
104    public:
105     // Returns a re-written message, freeing the original, or simply the
106     // original unchanged if no rewrite indicated.
107     virtual Message *Rewrite(Message *message) = 0;
108   };
109
110   // Initializes a channel proxy.  The channel_handle and mode parameters are
111   // passed directly to the underlying IPC::Channel.  The listener is called on
112   // the thread that creates the ChannelProxy.  The filter's OnMessageReceived
113   // method is called on the thread where the IPC::Channel is running.  The
114   // filter may be null if the consumer is not interested in handling messages
115   // on the background thread.  Any message not handled by the filter will be
116   // dispatched to the listener.  The given message loop indicates where the
117   // IPC::Channel should be created.
118   ChannelProxy(const IPC::ChannelHandle& channel_handle,
119                Channel::Mode mode,
120                Channel::Listener* listener,
121                base::MessageLoopProxy* ipc_thread_loop);
122
123   virtual ~ChannelProxy();
124
125   // Close the IPC::Channel.  This operation completes asynchronously, once the
126   // background thread processes the command to close the channel.  It is ok to
127   // call this method multiple times.  Redundant calls are ignored.
128   //
129   // WARNING: The MessageFilter object held by the ChannelProxy is also
130   // released asynchronously, and it may in fact have its final reference
131   // released on the background thread.  The caller should be careful to deal
132   // with / allow for this possibility.
133   void Close();
134
135   // Send a message asynchronously.  The message is routed to the background
136   // thread where it is passed to the IPC::Channel's Send method.
137   virtual bool Send(Message* message);
138
139   // Used to intercept messages as they are received on the background thread.
140   //
141   // Ordinarily, messages sent to the ChannelProxy are routed to the matching
142   // listener on the worker thread.  This API allows code to intercept messages
143   // before they are sent to the worker thread.
144   // If you call this before the target process is launched, then you're
145   // guaranteed to not miss any messages.  But if you call this anytime after,
146   // then some messages might be missed since the filter is added internally on
147   // the IO thread.
148   void AddFilter(MessageFilter* filter);
149   void RemoveFilter(MessageFilter* filter);
150
151   void set_outgoing_message_filter(OutgoingMessageFilter* filter) {
152     outgoing_message_filter_ = filter;
153   }
154
155   // Called to clear the pointer to the IPC message loop when it's going away.
156   void ClearIPCMessageLoop();
157
158 #if defined(OS_POSIX)
159   // Calls through to the underlying channel's methods.
160   int GetClientFileDescriptor() const;
161   bool GetClientEuid(uid_t* client_euid) const;
162 #endif  // defined(OS_POSIX)
163
164  protected:
165   class Context;
166   // A subclass uses this constructor if it needs to add more information
167   // to the internal state.  If create_pipe_now is true, the pipe is created
168   // immediately.  Otherwise it's created on the IO thread.
169   ChannelProxy(const IPC::ChannelHandle& channel_handle,
170                Channel::Mode mode,
171                base::MessageLoopProxy* ipc_thread_loop,
172                Context* context,
173                bool create_pipe_now);
174
175   // Used internally to hold state that is referenced on the IPC thread.
176   class Context : public base::RefCountedThreadSafe<Context>,
177                   public Channel::Listener {
178    public:
179     Context(Channel::Listener* listener, base::MessageLoopProxy* ipc_thread);
180     void ClearIPCMessageLoop() { ipc_message_loop_ = NULL; }
181     base::MessageLoopProxy* ipc_message_loop() const {
182       return ipc_message_loop_.get();
183     }
184     const std::string& channel_id() const { return channel_id_; }
185
186     // Dispatches a message on the listener thread.
187     void OnDispatchMessage(const Message& message);
188
189    protected:
190     friend class base::RefCountedThreadSafe<Context>;
191     virtual ~Context();
192
193     // IPC::Channel::Listener methods:
194     virtual bool OnMessageReceived(const Message& message) OVERRIDE;
195     virtual void OnChannelConnected(int32 peer_pid) OVERRIDE;
196     virtual void OnChannelError() OVERRIDE;
197
198     // Like OnMessageReceived but doesn't try the filters.
199     bool OnMessageReceivedNoFilter(const Message& message);
200
201     // Gives the filters a chance at processing |message|.
202     // Returns true if the message was processed, false otherwise.
203     bool TryFilters(const Message& message);
204
205     // Like Open and Close, but called on the IPC thread.
206     virtual void OnChannelOpened();
207     virtual void OnChannelClosed();
208
209     // Called on the consumers thread when the ChannelProxy is closed.  At that
210     // point the consumer is telling us that they don't want to receive any
211     // more messages, so we honor that wish by forgetting them!
212     virtual void Clear() { listener_ = NULL; }
213
214    private:
215     friend class ChannelProxy;
216     friend class SendTask;
217
218     // Create the Channel
219     void CreateChannel(const IPC::ChannelHandle& channel_handle,
220                        const Channel::Mode& mode);
221
222     // Methods called on the IO thread.
223     void OnSendMessage(Message* message_ptr);
224     void OnAddFilter();
225     void OnRemoveFilter(MessageFilter* filter);
226
227     // Methods called on the listener thread.
228     void AddFilter(MessageFilter* filter);
229     void OnDispatchConnected();
230     void OnDispatchError();
231
232     scoped_refptr<base::MessageLoopProxy> listener_message_loop_;
233     Channel::Listener* listener_;
234
235     // List of filters.  This is only accessed on the IPC thread.
236     std::vector<scoped_refptr<MessageFilter> > filters_;
237     scoped_refptr<base::MessageLoopProxy> ipc_message_loop_;
238     scoped_ptr<Channel> channel_;
239     std::string channel_id_;
240     int peer_pid_;
241     bool channel_connected_called_;
242
243     // Holds filters between the AddFilter call on the listerner thread and the
244     // IPC thread when they're added to filters_.
245     std::vector<scoped_refptr<MessageFilter> > pending_filters_;
246     // Lock for pending_filters_.
247     base::Lock pending_filters_lock_;
248   };
249
250   Context* context() { return context_; }
251
252   OutgoingMessageFilter* outgoing_message_filter() {
253     return outgoing_message_filter_;
254   }
255
256  private:
257   friend class SendTask;
258
259   void Init(const IPC::ChannelHandle& channel_handle, Channel::Mode mode,
260             base::MessageLoopProxy* ipc_thread_loop, bool create_pipe_now);
261
262   // By maintaining this indirection (ref-counted) to our internal state, we
263   // can safely be destroyed while the background thread continues to do stuff
264   // that involves this data.
265   scoped_refptr<Context> context_;
266
267   OutgoingMessageFilter* outgoing_message_filter_;
268 };
269
270 }  // namespace IPC
271
272 #endif  // IPC_IPC_CHANNEL_PROXY_H_