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
110 // The maximum message size in bytes. Attempting to receive a message of this
111 // size or bigger results in a channel error.
112 static constexpr size_t kMaximumMessageSize = 128 * 1024 * 1024;
113
114 // Amount of data to read at once from the pipe.
115 static const size_t kReadBufferSize = 4 * 1024;
116
117 // Maximum persistent read buffer size. Read buffer can grow larger to
118 // accommodate large messages, but it's recommended to shrink back to this
119 // value because it fits 99.9% of all messages (see issue 529940 for data).
120 static const size_t kMaximumReadBufferSize = 64 * 1024;
121
122 // Initialize a Channel.
123 //
124 // |channel_handle| identifies the communication Channel. For POSIX, if
125 // the file descriptor in the channel handle is != -1, the channel takes
126 // ownership of the file descriptor and will close it appropriately, otherwise
127 // it will create a new descriptor internally.
128 // |listener| receives a callback on the current thread for each newly
129 // received message.
130 //
131 // There are four type of modes how channels operate:
132 //
133 // - Server and named server: In these modes, the Channel is
134 // responsible for setting up the IPC object.
135 // - An "open" named server: It accepts connections from ANY client.
136 // The caller must then implement their own access-control based on the
137 // client process' user Id.
138 // - Client and named client: In these mode, the Channel merely
139 // connects to the already established IPC object.
140 //
141 // Each mode has its own Create*() API to create the Channel object.
142 static std::unique_ptr<Channel> Create(
143 const IPC::ChannelHandle& channel_handle,
144 Mode mode,
145 Listener* listener);
146
147 static std::unique_ptr<Channel> CreateClient(
148 const IPC::ChannelHandle& channel_handle,
149 Listener* listener,
150 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
151
152 static std::unique_ptr<Channel> CreateServer(
153 const IPC::ChannelHandle& channel_handle,
154 Listener* listener,
155 const scoped_refptr<base::SingleThreadTaskRunner>& ipc_task_runner);
156
157 ~Channel() override;
158
159 // Connect the pipe. On the server side, this will initiate
160 // waiting for connections. On the client, it attempts to
161 // connect to a pre-existing pipe. Note, calling Connect()
162 // will not block the calling thread and may complete
163 // asynchronously.
164 //
165 // The subclass implementation must call WillConnect() at the beginning of its
166 // implementation.
167 [[nodiscard]] virtual bool Connect() = 0;
168
169 // Pause the channel. Subsequent sends will be queued internally until
170 // Unpause() is called and the channel is flushed either by Unpause() or a
171 // subsequent call to Flush().
172 virtual void Pause();
173
174 // Unpause the channel. This allows subsequent Send() calls to transmit
175 // messages immediately, without queueing. If |flush| is true, any messages
176 // queued while paused will be flushed immediately upon unpausing. Otherwise
177 // you must call Flush() explicitly.
178 //
179 // Not all implementations support Unpause(). See ConnectPaused() above for
180 // details.
181 virtual void Unpause(bool flush);
182
183 // Manually flush the pipe. This is only useful exactly once, and only after
184 // a call to Unpause(false), in order to explicitly flush out any
185 // messages which were queued prior to unpausing.
186 //
187 // Not all implementations support Flush(). See ConnectPaused() above for
188 // details.
189 virtual void Flush();
190
191 // Close this Channel explicitly. May be called multiple times.
192 // On POSIX calling close on an IPC channel that listens for connections will
193 // cause it to close any accepted connections, and it will stop listening for
194 // new connections. If you just want to close the currently accepted
195 // connection and listen for new ones, use ResetToAcceptingConnectionState.
196 virtual void Close() = 0;
197
198 // Gets a helper for associating Mojo interfaces with this Channel.
199 //
200 // NOTE: Not all implementations support this.
201 virtual AssociatedInterfaceSupport* GetAssociatedInterfaceSupport();
202
203 // Overridden from ipc::Sender.
204 // Send a message over the Channel to the listener on the other end.
205 //
206 // |message| must be allocated using operator new. This object will be
207 // deleted once the contents of the Message have been sent.
208 bool Send(Message* message) override = 0;
209
210 // Sets the UrgentMessageObserver for this channel. `observer` must outlive
211 // the channel.
212 //
213 // Only channel associated mojo interfaces support urgent messages.
214 virtual void SetUrgentMessageObserver(UrgentMessageObserver* observer);
215
216 #if !BUILDFLAG(IS_NACL)
217 // Generates a channel ID that's non-predictable and unique.
218 static std::string GenerateUniqueRandomChannelID();
219 #endif
220
221 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
222 // Sandboxed processes live in a PID namespace, so when sending the IPC hello
223 // message from client to server we need to send the PID from the global
224 // PID namespace.
225 static void SetGlobalPid(int pid);
226 static int GetGlobalPid();
227 #endif
228
229 protected:
230 // Subclasses must call this method at the beginning of their implementation
231 // of Connect().
232 void WillConnect();
233
234 private:
235 bool did_start_connect_ = false;
236 };
237
238 } // namespace IPC
239
240 #endif // IPC_IPC_CHANNEL_H_
241