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