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.
4
5 #ifndef IPC_IPC_CHANNEL_H_
6 #define IPC_IPC_CHANNEL_H_
7
8 #include <stddef.h>
9 #include <stdint.h>
10
11 #include <memory>
12 #include <string>
13
14 #include "base/compiler_specific.h"
15 #include "base/component_export.h"
16 #include "base/files/scoped_file.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/process/process.h"
19 #include "base/single_thread_task_runner.h"
20 #include "base/threading/thread_task_runner_handle.h"
21 #include "build/build_config.h"
22 #include "ipc/ipc.mojom.h"
23 #include "ipc/ipc_channel_handle.h"
24 #include "ipc/ipc_message.h"
25 #include "ipc/ipc_sender.h"
26 #include "mojo/public/cpp/bindings/associated_interface_ptr.h"
27 #include "mojo/public/cpp/bindings/associated_interface_request.h"
28 #include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h"
29 #include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h"
30
31 #if defined(OS_POSIX)
32 #include <sys/types.h>
33 #endif
34
35 namespace IPC {
36
37 class Listener;
38
39 //------------------------------------------------------------------------------
40 // See
41 // http://www.chromium.org/developers/design-documents/inter-process-communication
42 // for overview of IPC in Chromium.
43
44 // Channels are implemented using mojo message pipes on all platforms other
45 // than NaCl.
46
COMPONENT_EXPORT(IPC)47 class COMPONENT_EXPORT(IPC) Channel : public Sender {
48 // Security tests need access to the pipe handle.
49 friend class ChannelTest;
50
51 public:
52 // Flags to test modes
53 enum ModeFlags {
54 MODE_NO_FLAG = 0x0,
55 MODE_SERVER_FLAG = 0x1,
56 MODE_CLIENT_FLAG = 0x2,
57 };
58
59 // Some Standard Modes
60 // TODO(morrita): These are under deprecation work. You should use Create*()
61 // functions instead.
62 enum Mode {
63 MODE_NONE = MODE_NO_FLAG,
64 MODE_SERVER = MODE_SERVER_FLAG,
65 MODE_CLIENT = MODE_CLIENT_FLAG,
66 };
67
68 // Messages internal to the IPC implementation are defined here.
69 // Uses Maximum value of message type (uint16_t), to avoid conflicting
70 // with normal message types, which are enumeration constants starting from 0.
71 enum {
72 // The Hello message is sent by the peer when the channel is connected.
73 // The message contains just the process id (pid).
74 // The message has a special routing_id (MSG_ROUTING_NONE)
75 // and type (HELLO_MESSAGE_TYPE).
76 HELLO_MESSAGE_TYPE = UINT16_MAX,
77 // The CLOSE_FD_MESSAGE_TYPE is used in the IPC class to
78 // work around a bug in sendmsg() on Mac. When an FD is sent
79 // over the socket, a CLOSE_FD_MESSAGE is sent with hops = 2.
80 // The client will return the message with hops = 1, *after* it
81 // has received the message that contains the FD. When we
82 // receive it again on the sender side, we close the FD.
83 CLOSE_FD_MESSAGE_TYPE = HELLO_MESSAGE_TYPE - 1
84 };
85
86 // Helper interface a Channel may implement to expose support for associated
87 // Mojo interfaces.
88 class COMPONENT_EXPORT(IPC) AssociatedInterfaceSupport {
89 public:
90 using GenericAssociatedInterfaceFactory =
91 base::Callback<void(mojo::ScopedInterfaceEndpointHandle)>;
92
93 virtual ~AssociatedInterfaceSupport() {}
94
95 // Returns a ThreadSafeForwarded for this channel which can be used to
96 // safely send mojom::Channel requests from arbitrary threads.
97 virtual std::unique_ptr<mojo::ThreadSafeForwarder<mojom::Channel>>
98 CreateThreadSafeChannel() = 0;
99
100 // Adds an interface factory to this channel for interface |name|. Must be
101 // safe to call from any thread.
102 virtual void AddGenericAssociatedInterface(
103 const std::string& name,
104 const GenericAssociatedInterfaceFactory& factory) = 0;
105
106 // Requests an associated interface from the remote endpoint.
107 virtual void GetGenericRemoteAssociatedInterface(
108 const std::string& name,
109 mojo::ScopedInterfaceEndpointHandle handle) = 0;
110
111 // Template helper to add an interface factory to this channel.
112 template <typename Interface>
113 using AssociatedInterfaceFactory =
114 base::Callback<void(mojo::AssociatedInterfaceRequest<Interface>)>;
115 template <typename Interface>
116 void AddAssociatedInterface(
117 const AssociatedInterfaceFactory<Interface>& factory) {
118 AddGenericAssociatedInterface(
119 Interface::Name_,
120 base::Bind(&BindAssociatedInterfaceRequest<Interface>, factory));
121 }
122
123 // Template helper to request a remote associated interface.
124 template <typename Interface>
125 void GetRemoteAssociatedInterface(
126 mojo::AssociatedInterfacePtr<Interface>* proxy) {
127 auto request = mojo::MakeRequest(proxy);
128 GetGenericRemoteAssociatedInterface(
129 Interface::Name_, request.PassHandle());
130 }
131
132 private:
133 template <typename Interface>
134 static void BindAssociatedInterfaceRequest(
135 const AssociatedInterfaceFactory<Interface>& factory,
136 mojo::ScopedInterfaceEndpointHandle handle) {
137 factory.Run(
138 mojo::AssociatedInterfaceRequest<Interface>(std::move(handle)));
139 }
140 };
141
142 // The maximum message size in bytes. Attempting to receive a message of this
143 // size or bigger results in a channel error.
144 static constexpr size_t kMaximumMessageSize = 128 * 1024 * 1024;
145
146 // Amount of data to read at once from the pipe.
147 static const size_t kReadBufferSize = 4 * 1024;
148
149 // Maximum persistent read buffer size. Read buffer can grow larger to
150 // accommodate large messages, but it's recommended to shrink back to this
151 // value because it fits 99.9% of all messages (see issue 529940 for data).
152 static const size_t kMaximumReadBufferSize = 64 * 1024;
153
154 // Initialize a Channel.
155 //
156 // |channel_handle| identifies the communication Channel. For POSIX, if
157 // the file descriptor in the channel handle is != -1, the channel takes
158 // ownership of the file descriptor and will close it appropriately, otherwise
159 // it will create a new descriptor internally.
160 // |listener| receives a callback on the current thread for each newly
161 // received message.
162 //
163 // There are four type of modes how channels operate:
164 //
165 // - Server and named server: In these modes, the Channel is
166 // responsible for settingb up the IPC object
167 // - An "open" named server: It accepts connections from ANY client.
168 // The caller must then implement their own access-control based on the
169 // client process' user Id.
170 // - Client and named client: In these mode, the Channel merely
171 // connects to the already established IPC object.
172 //
173 // Each mode has its own Create*() API to create the Channel object.
174 static std::unique_ptr<Channel> Create(
175 const IPC::ChannelHandle& channel_handle,
176 Mode mode,
177 Listener* listener);
178
179 static std::unique_ptr<Channel> CreateClient(
180 const IPC::ChannelHandle& channel_handle,
181 Listener* listener,
182 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
183
184 static std::unique_ptr<Channel> CreateServer(
185 const IPC::ChannelHandle& channel_handle,
186 Listener* listener,
187 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
188
189 ~Channel() override;
190
191 // Connect the pipe. On the server side, this will initiate
192 // waiting for connections. On the client, it attempts to
193 // connect to a pre-existing pipe. Note, calling Connect()
194 // will not block the calling thread and may complete
195 // asynchronously.
196 //
197 // The subclass implementation must call WillConnect() at the beginning of its
198 // implementation.
199 virtual bool Connect() WARN_UNUSED_RESULT = 0;
200
201 // Pause the channel. Subsequent sends will be queued internally until
202 // Unpause() is called and the channel is flushed either by Unpause() or a
203 // subsequent call to Flush().
204 virtual void Pause();
205
206 // Unpause the channel. This allows subsequent Send() calls to transmit
207 // messages immediately, without queueing. If |flush| is true, any messages
208 // queued while paused will be flushed immediately upon unpausing. Otherwise
209 // you must call Flush() explicitly.
210 //
211 // Not all implementations support Unpause(). See ConnectPaused() above for
212 // details.
213 virtual void Unpause(bool flush);
214
215 // Manually flush the pipe. This is only useful exactly once, and only after
216 // a call to Unpause(false), in order to explicitly flush out any
217 // messages which were queued prior to unpausing.
218 //
219 // Not all implementations support Flush(). See ConnectPaused() above for
220 // details.
221 virtual void Flush();
222
223 // Close this Channel explicitly. May be called multiple times.
224 // On POSIX calling close on an IPC channel that listens for connections will
225 // cause it to close any accepted connections, and it will stop listening for
226 // new connections. If you just want to close the currently accepted
227 // connection and listen for new ones, use ResetToAcceptingConnectionState.
228 virtual void Close() = 0;
229
230 // Gets a helper for associating Mojo interfaces with this Channel.
231 //
232 // NOTE: Not all implementations support this.
233 virtual AssociatedInterfaceSupport* GetAssociatedInterfaceSupport();
234
235 // Overridden from ipc::Sender.
236 // Send a message over the Channel to the listener on the other end.
237 //
238 // |message| must be allocated using operator new. This object will be
239 // deleted once the contents of the Message have been sent.
240 bool Send(Message* message) override = 0;
241
242 #if !defined(OS_NACL_SFI)
243 // Generates a channel ID that's non-predictable and unique.
244 static std::string GenerateUniqueRandomChannelID();
245 #endif
246
247 #if defined(OS_LINUX)
248 // Sandboxed processes live in a PID namespace, so when sending the IPC hello
249 // message from client to server we need to send the PID from the global
250 // PID namespace.
251 static void SetGlobalPid(int pid);
252 static int GetGlobalPid();
253 #endif
254
255 protected:
256 // Subclasses must call this method at the beginning of their implementation
257 // of Connect().
258 void WillConnect();
259
260 private:
261 bool did_start_connect_ = false;
262 };
263
264 } // namespace IPC
265
266 #endif // IPC_IPC_CHANNEL_H_
267