Use UintToString() for unsigned values.
[chromium-blink-merge.git] / ipc / ipc_channel.h
blob4784a5cac2f80c491ef27ab01aae9c07431ae341
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_H_
6 #define IPC_IPC_CHANNEL_H_
8 #include <stdint.h>
10 #include <string>
12 #if defined(OS_POSIX)
13 #include <sys/types.h>
14 #endif
16 #include "base/compiler_specific.h"
17 #include "base/files/scoped_file.h"
18 #include "base/process/process.h"
19 #include "ipc/ipc_channel_handle.h"
20 #include "ipc/ipc_endpoint.h"
21 #include "ipc/ipc_message.h"
23 namespace IPC {
25 class AttachmentBroker;
26 class Listener;
28 //------------------------------------------------------------------------------
29 // See
30 // http://www.chromium.org/developers/design-documents/inter-process-communication
31 // for overview of IPC in Chromium.
33 // Channels are implemented using named pipes on Windows, and
34 // socket pairs (or in some special cases unix domain sockets) on POSIX.
35 // On Windows we access pipes in various processes by name.
36 // On POSIX we pass file descriptors to child processes and assign names to them
37 // in a lookup table.
38 // In general on POSIX we do not use unix domain sockets due to security
39 // concerns and the fact that they can leave garbage around the file system
40 // (MacOS does not support abstract named unix domain sockets).
41 // You can use unix domain sockets if you like on POSIX by constructing the
42 // the channel with the mode set to one of the NAMED modes. NAMED modes are
43 // currently used by automation and service processes.
45 class IPC_EXPORT Channel : public Endpoint {
46 // Security tests need access to the pipe handle.
47 friend class ChannelTest;
49 public:
50 // Flags to test modes
51 enum ModeFlags {
52 MODE_NO_FLAG = 0x0,
53 MODE_SERVER_FLAG = 0x1,
54 MODE_CLIENT_FLAG = 0x2,
55 MODE_NAMED_FLAG = 0x4,
56 #if defined(OS_POSIX)
57 MODE_OPEN_ACCESS_FLAG = 0x8, // Don't restrict access based on client UID.
58 #endif
61 // Some Standard Modes
62 // TODO(morrita): These are under deprecation work. You should use Create*()
63 // functions instead.
64 enum Mode {
65 MODE_NONE = MODE_NO_FLAG,
66 MODE_SERVER = MODE_SERVER_FLAG,
67 MODE_CLIENT = MODE_CLIENT_FLAG,
68 MODE_NAMED_SERVER = MODE_SERVER_FLAG | MODE_NAMED_FLAG,
69 MODE_NAMED_CLIENT = MODE_CLIENT_FLAG | MODE_NAMED_FLAG,
70 #if defined(OS_POSIX)
71 MODE_OPEN_NAMED_SERVER = MODE_OPEN_ACCESS_FLAG | MODE_SERVER_FLAG |
72 MODE_NAMED_FLAG
73 #endif
76 // Messages internal to the IPC implementation are defined here.
77 // Uses Maximum value of message type (uint16), to avoid conflicting
78 // with normal message types, which are enumeration constants starting from 0.
79 enum {
80 // The Hello message is sent by the peer when the channel is connected.
81 // The message contains just the process id (pid).
82 // The message has a special routing_id (MSG_ROUTING_NONE)
83 // and type (HELLO_MESSAGE_TYPE).
84 HELLO_MESSAGE_TYPE = UINT16_MAX,
85 // The CLOSE_FD_MESSAGE_TYPE is used in the IPC class to
86 // work around a bug in sendmsg() on Mac. When an FD is sent
87 // over the socket, a CLOSE_FD_MESSAGE is sent with hops = 2.
88 // The client will return the message with hops = 1, *after* it
89 // has received the message that contains the FD. When we
90 // receive it again on the sender side, we close the FD.
91 CLOSE_FD_MESSAGE_TYPE = HELLO_MESSAGE_TYPE - 1
94 // The maximum message size in bytes. Attempting to receive a message of this
95 // size or bigger results in a channel error.
96 static const size_t kMaximumMessageSize = 128 * 1024 * 1024;
98 // Amount of data to read at once from the pipe.
99 static const size_t kReadBufferSize = 4 * 1024;
101 // Initialize a Channel.
103 // |channel_handle| identifies the communication Channel. For POSIX, if
104 // the file descriptor in the channel handle is != -1, the channel takes
105 // ownership of the file descriptor and will close it appropriately, otherwise
106 // it will create a new descriptor internally.
107 // |listener| receives a callback on the current thread for each newly
108 // received message.
110 // There are four type of modes how channels operate:
112 // - Server and named server: In these modes, the Channel is
113 // responsible for settingb up the IPC object
114 // - An "open" named server: It accepts connections from ANY client.
115 // The caller must then implement their own access-control based on the
116 // client process' user Id.
117 // - Client and named client: In these mode, the Channel merely
118 // connects to the already established IPC object.
120 // Each mode has its own Create*() API to create the Channel object.
122 // TODO(morrita): Replace CreateByModeForProxy() with one of above Create*().
124 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
125 // make the upcoming refactor decomposable into smaller CLs.
126 // http://crbug.com/493414.
127 static scoped_ptr<Channel> Create(const IPC::ChannelHandle& channel_handle,
128 Mode mode,
129 Listener* listener,
130 AttachmentBroker* broker = nullptr);
132 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
133 // make the upcoming refactor decomposable into smaller CLs.
134 // http://crbug.com/493414.
135 static scoped_ptr<Channel> CreateClient(
136 const IPC::ChannelHandle& channel_handle,
137 Listener* listener,
138 AttachmentBroker* broker = nullptr);
140 // Channels on Windows are named by default and accessible from other
141 // processes. On POSIX channels are anonymous by default and not accessible
142 // from other processes. Named channels work via named unix domain sockets.
143 // On Windows MODE_NAMED_SERVER is equivalent to MODE_SERVER and
144 // MODE_NAMED_CLIENT is equivalent to MODE_CLIENT.
145 static scoped_ptr<Channel> CreateNamedServer(
146 const IPC::ChannelHandle& channel_handle,
147 Listener* listener,
148 AttachmentBroker* broker);
149 static scoped_ptr<Channel> CreateNamedClient(
150 const IPC::ChannelHandle& channel_handle,
151 Listener* listener,
152 AttachmentBroker* broker);
153 #if defined(OS_POSIX)
154 // An "open" named server accepts connections from ANY client.
155 // The caller must then implement their own access-control based on the
156 // client process' user Id.
157 static scoped_ptr<Channel> CreateOpenNamedServer(
158 const IPC::ChannelHandle& channel_handle,
159 Listener* listener,
160 AttachmentBroker* broker);
161 #endif
162 // TODO(erikchen): Remove default parameter for |broker|. It exists only to
163 // make the upcoming refactor decomposable into smaller CLs.
164 // http://crbug.com/493414.
165 static scoped_ptr<Channel> CreateServer(
166 const IPC::ChannelHandle& channel_handle,
167 Listener* listener,
168 AttachmentBroker* broker = nullptr);
170 ~Channel() override;
172 // Connect the pipe. On the server side, this will initiate
173 // waiting for connections. On the client, it attempts to
174 // connect to a pre-existing pipe. Note, calling Connect()
175 // will not block the calling thread and may complete
176 // asynchronously.
177 virtual bool Connect() WARN_UNUSED_RESULT = 0;
179 // Close this Channel explicitly. May be called multiple times.
180 // On POSIX calling close on an IPC channel that listens for connections will
181 // cause it to close any accepted connections, and it will stop listening for
182 // new connections. If you just want to close the currently accepted
183 // connection and listen for new ones, use ResetToAcceptingConnectionState.
184 virtual void Close() = 0;
186 // Get its own process id. This value is told to the peer.
187 virtual base::ProcessId GetSelfPID() const = 0;
189 // Overridden from ipc::Sender.
190 // Send a message over the Channel to the listener on the other end.
192 // |message| must be allocated using operator new. This object will be
193 // deleted once the contents of the Message have been sent.
194 bool Send(Message* message) override = 0;
196 // IsSendThreadSafe returns true iff it's safe to call |Send| from non-IO
197 // threads. This is constant for the lifetime of the |Channel|.
198 virtual bool IsSendThreadSafe() const;
200 // NaCl in Non-SFI mode runs on Linux directly, and the following functions
201 // compiled on Linux are also needed. Please see also comments in
202 // components/nacl_nonsfi.gyp for more details.
203 #if defined(OS_POSIX) && !defined(OS_NACL_SFI)
204 // On POSIX an IPC::Channel wraps a socketpair(), this method returns the
205 // FD # for the client end of the socket.
206 // This method may only be called on the server side of a channel.
207 // This method can be called on any thread.
208 virtual int GetClientFileDescriptor() const = 0;
210 // Same as GetClientFileDescriptor, but transfers the ownership of the
211 // file descriptor to the caller.
212 // This method can be called on any thread.
213 virtual base::ScopedFD TakeClientFileDescriptor() = 0;
214 #endif
216 // Returns true if a named server channel is initialized on the given channel
217 // ID. Even if true, the server may have already accepted a connection.
218 static bool IsNamedServerInitialized(const std::string& channel_id);
220 #if !defined(OS_NACL_SFI)
221 // Generates a channel ID that's non-predictable and unique.
222 static std::string GenerateUniqueRandomChannelID();
224 // Generates a channel ID that, if passed to the client as a shared secret,
225 // will validate that the client's authenticity. On platforms that do not
226 // require additional this is simply calls GenerateUniqueRandomChannelID().
227 // For portability the prefix should not include the \ character.
228 static std::string GenerateVerifiedChannelID(const std::string& prefix);
229 #endif
231 #if defined(OS_LINUX)
232 // Sandboxed processes live in a PID namespace, so when sending the IPC hello
233 // message from client to server we need to send the PID from the global
234 // PID namespace.
235 static void SetGlobalPid(int pid);
236 #endif
238 #if defined(OS_ANDROID)
239 // Most tests are single process and work the same on all platforms. However
240 // in some cases we want to test multi-process, and Android differs in that it
241 // can't 'exec' after forking. This callback resets any data in the forked
242 // process such that it acts similar to if it was exec'd, for tests.
243 static void NotifyProcessForkedForTesting();
244 #endif
246 protected:
247 // An OutputElement is a wrapper around a Message or raw buffer while it is
248 // waiting to be passed to the system's underlying IPC mechanism.
249 class OutputElement {
250 public:
251 // Takes ownership of message.
252 OutputElement(Message* message);
253 // Takes ownership of the buffer. |buffer| is freed via free(), so it
254 // must be malloced.
255 OutputElement(void* buffer, size_t length);
256 ~OutputElement();
257 size_t size() const { return message_ ? message_->size() : length_; }
258 const void* data() const { return message_ ? message_->data() : buffer_; }
259 const Message* get_message() const { return message_.get(); }
261 private:
262 scoped_ptr<const Message> message_;
263 void* buffer_;
264 size_t length_;
268 #if defined(OS_POSIX)
269 // SocketPair() creates a pair of socket FDs suitable for using with
270 // IPC::Channel.
271 IPC_EXPORT bool SocketPair(int* fd1, int* fd2);
272 #endif
274 } // namespace IPC
276 #endif // IPC_IPC_CHANNEL_H_