ipc_channel.h 9.6 KB

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