node_controller.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Copyright 2016 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 MOJO_CORE_NODE_CONTROLLER_H_
  5. #define MOJO_CORE_NODE_CONTROLLER_H_
  6. #include <map>
  7. #include <memory>
  8. #include <string>
  9. #include <unordered_map>
  10. #include <unordered_set>
  11. #include <utility>
  12. #include <vector>
  13. #include "base/callback.h"
  14. #include "base/containers/queue.h"
  15. #include "base/containers/span.h"
  16. #include "base/memory/ref_counted.h"
  17. #include "base/memory/writable_shared_memory_region.h"
  18. #include "base/process/process.h"
  19. #include "base/task/single_thread_task_runner.h"
  20. #include "build/build_config.h"
  21. #include "mojo/core/atomic_flag.h"
  22. #include "mojo/core/node_channel.h"
  23. #include "mojo/core/ports/event.h"
  24. #include "mojo/core/ports/name.h"
  25. #include "mojo/core/ports/node.h"
  26. #include "mojo/core/ports/node_delegate.h"
  27. #include "mojo/core/system_impl_export.h"
  28. #include "mojo/public/cpp/platform/platform_handle.h"
  29. #include "third_party/abseil-cpp/absl/types/optional.h"
  30. namespace mojo {
  31. namespace core {
  32. class Broker;
  33. class Core;
  34. // A set of NodeNames that is bounded by a maximum size.
  35. // If the max size is reached, it will delete the older half of stored names.
  36. class BoundedPeerSet {
  37. public:
  38. BoundedPeerSet();
  39. BoundedPeerSet(const BoundedPeerSet&) = delete;
  40. BoundedPeerSet& operator=(const BoundedPeerSet&) = delete;
  41. ~BoundedPeerSet();
  42. void Insert(const ports::NodeName& name);
  43. bool Contains(const ports::NodeName& name);
  44. private:
  45. static constexpr int kHalfSize = 50000;
  46. std::unordered_set<ports::NodeName> old_set_;
  47. std::unordered_set<ports::NodeName> new_set_;
  48. };
  49. // The owner of ports::Node which facilitates core EDK implementation. All
  50. // public interface methods are safe to call from any thread.
  51. class MOJO_SYSTEM_IMPL_EXPORT NodeController : public ports::NodeDelegate,
  52. public NodeChannel::Delegate {
  53. public:
  54. class PortObserver : public ports::UserData {
  55. public:
  56. virtual void OnPortStatusChanged() = 0;
  57. protected:
  58. ~PortObserver() override = default;
  59. };
  60. // |core| owns and out-lives us.
  61. NodeController();
  62. NodeController(const NodeController&) = delete;
  63. NodeController& operator=(const NodeController&) = delete;
  64. ~NodeController() override;
  65. const ports::NodeName& name() const { return name_; }
  66. ports::Node* node() const { return node_.get(); }
  67. scoped_refptr<base::SingleThreadTaskRunner> io_task_runner() const {
  68. return io_task_runner_;
  69. }
  70. // Called exactly once, shortly after construction, and before any other
  71. // methods are called on this object.
  72. void SetIOTaskRunner(
  73. scoped_refptr<base::SingleThreadTaskRunner> io_task_runner);
  74. // Sends an invitation to a remote process (via |connection_params|) to join
  75. // this process's graph of connected processes as a broker client.
  76. void SendBrokerClientInvitation(
  77. base::Process target_process,
  78. ConnectionParams connection_params,
  79. const std::vector<std::pair<std::string, ports::PortRef>>& attached_ports,
  80. const ProcessErrorCallback& process_error_callback);
  81. // Connects this node to the process which invited it to be a broker client.
  82. void AcceptBrokerClientInvitation(ConnectionParams connection_params);
  83. // Connects this node to a peer node. On success, |port| will be merged with
  84. // the corresponding port in the peer node.
  85. void ConnectIsolated(ConnectionParams connection_params,
  86. const ports::PortRef& port,
  87. base::StringPiece connection_name);
  88. // Sets a port's observer. If |observer| is null the port's current observer
  89. // is removed.
  90. void SetPortObserver(const ports::PortRef& port,
  91. scoped_refptr<PortObserver> observer);
  92. // Closes a port. Use this in lieu of calling Node::ClosePort() directly, as
  93. // it ensures the port's observer has also been removed.
  94. void ClosePort(const ports::PortRef& port);
  95. // Sends a message on a port to its peer.
  96. int SendUserMessage(const ports::PortRef& port_ref,
  97. std::unique_ptr<ports::UserMessageEvent> message);
  98. // Merges a local port |port| into a port reserved by |name| in the node which
  99. // invited this node.
  100. void MergePortIntoInviter(const std::string& name,
  101. const ports::PortRef& port);
  102. // Merges two local ports together.
  103. int MergeLocalPorts(const ports::PortRef& port0, const ports::PortRef& port1);
  104. // Creates a new shared buffer for use in the current process.
  105. base::WritableSharedMemoryRegion CreateSharedBuffer(size_t num_bytes);
  106. // Request that the Node be shut down cleanly. This may take an arbitrarily
  107. // long time to complete, at which point |callback| will be called.
  108. //
  109. // Note that while it is safe to continue using the NodeController's public
  110. // interface after requesting shutdown, you do so at your own risk and there
  111. // is NO guarantee that new messages will be sent or ports will complete
  112. // transfer.
  113. void RequestShutdown(base::OnceClosure callback);
  114. // Notifies the NodeController that we received a bad message from the given
  115. // node. To avoid losing error reports the caller should ensure that the
  116. // source node |HasBadMessageHandler| before calling |NotifyBadMessageFrom|.
  117. void NotifyBadMessageFrom(const ports::NodeName& source_node,
  118. const std::string& error);
  119. // Returns whether |source_node| exists and has a bad message handler.
  120. bool HasBadMessageHandler(const ports::NodeName& source_node);
  121. // Force-closes the connection to another process to simulate connection
  122. // failures for testing. |process_id| must correspond to a process to which
  123. // this node has an active NodeChannel.
  124. void ForceDisconnectProcessForTesting(base::ProcessId process_id);
  125. static void DeserializeRawBytesAsEventForFuzzer(
  126. base::span<const unsigned char> data);
  127. static void DeserializeMessageAsEventForFuzzer(Channel::MessagePtr message);
  128. scoped_refptr<NodeChannel> GetBrokerChannel();
  129. private:
  130. friend Core;
  131. using NodeMap =
  132. std::unordered_map<ports::NodeName, scoped_refptr<NodeChannel>>;
  133. using OutgoingMessageQueue = base::queue<Channel::MessagePtr>;
  134. using PortMap = std::map<std::string, ports::PortRef>;
  135. struct IsolatedConnection {
  136. IsolatedConnection();
  137. IsolatedConnection(const IsolatedConnection& other);
  138. IsolatedConnection(IsolatedConnection&& other);
  139. IsolatedConnection(scoped_refptr<NodeChannel> channel,
  140. const ports::PortRef& local_port,
  141. base::StringPiece name);
  142. ~IsolatedConnection();
  143. IsolatedConnection& operator=(const IsolatedConnection& other);
  144. IsolatedConnection& operator=(IsolatedConnection&& other);
  145. // NOTE: |channel| is null once the connection is fully established.
  146. scoped_refptr<NodeChannel> channel;
  147. ports::PortRef local_port;
  148. std::string name;
  149. };
  150. void SendBrokerClientInvitationOnIOThread(
  151. base::Process target_process,
  152. ConnectionParams connection_params,
  153. ports::NodeName token,
  154. const ProcessErrorCallback& process_error_callback);
  155. void AcceptBrokerClientInvitationOnIOThread(
  156. ConnectionParams connection_params,
  157. absl::optional<PlatformHandle> broker_host_handle);
  158. void ConnectIsolatedOnIOThread(ConnectionParams connection_params,
  159. ports::PortRef port,
  160. const std::string& connection_name);
  161. scoped_refptr<NodeChannel> GetPeerChannel(const ports::NodeName& name);
  162. scoped_refptr<NodeChannel> GetInviterChannel();
  163. void AddPeer(const ports::NodeName& name,
  164. scoped_refptr<NodeChannel> channel,
  165. bool start_channel,
  166. bool allow_name_reuse = false);
  167. void DropPeer(const ports::NodeName& name, NodeChannel* channel);
  168. void SendPeerEvent(const ports::NodeName& name, ports::ScopedEvent event);
  169. void DropAllPeers();
  170. // ports::NodeDelegate:
  171. void ForwardEvent(const ports::NodeName& node,
  172. ports::ScopedEvent event) override;
  173. void BroadcastEvent(ports::ScopedEvent event) override;
  174. void PortStatusChanged(const ports::PortRef& port) override;
  175. // NodeChannel::Delegate:
  176. void OnAcceptInvitee(const ports::NodeName& from_node,
  177. const ports::NodeName& inviter_name,
  178. const ports::NodeName& token) override;
  179. void OnAcceptInvitation(const ports::NodeName& from_node,
  180. const ports::NodeName& token,
  181. const ports::NodeName& invitee_name) override;
  182. void OnAddBrokerClient(const ports::NodeName& from_node,
  183. const ports::NodeName& client_name,
  184. base::ProcessHandle process_handle) override;
  185. void OnBrokerClientAdded(const ports::NodeName& from_node,
  186. const ports::NodeName& client_name,
  187. PlatformHandle broker_channel) override;
  188. void OnAcceptBrokerClient(const ports::NodeName& from_node,
  189. const ports::NodeName& broker_name,
  190. PlatformHandle broker_channel,
  191. const uint64_t broker_capabilities) override;
  192. void OnEventMessage(const ports::NodeName& from_node,
  193. Channel::MessagePtr message) override;
  194. void OnRequestPortMerge(const ports::NodeName& from_node,
  195. const ports::PortName& connector_port_name,
  196. const std::string& token) override;
  197. void OnRequestIntroduction(const ports::NodeName& from_node,
  198. const ports::NodeName& name) override;
  199. void OnIntroduce(const ports::NodeName& from_node,
  200. const ports::NodeName& name,
  201. PlatformHandle channel_handle,
  202. const uint64_t remote_capailities) override;
  203. void OnBroadcast(const ports::NodeName& from_node,
  204. Channel::MessagePtr message) override;
  205. #if BUILDFLAG(IS_WIN)
  206. void OnRelayEventMessage(const ports::NodeName& from_node,
  207. base::ProcessHandle from_process,
  208. const ports::NodeName& destination,
  209. Channel::MessagePtr message) override;
  210. void OnEventMessageFromRelay(const ports::NodeName& from_node,
  211. const ports::NodeName& source_node,
  212. Channel::MessagePtr message) override;
  213. #endif
  214. void OnAcceptPeer(const ports::NodeName& from_node,
  215. const ports::NodeName& token,
  216. const ports::NodeName& peer_name,
  217. const ports::PortName& port_name) override;
  218. void OnChannelError(const ports::NodeName& from_node,
  219. NodeChannel* channel) override;
  220. // Cancels all pending port merges. These are merges which are supposed to
  221. // be requested from the inviter ASAP, and they may be cancelled if the
  222. // connection to the inviter is broken or never established.
  223. void CancelPendingPortMerges();
  224. // Marks this NodeController for destruction when the IO thread shuts down.
  225. // This is used in case Core is torn down before the IO thread. Must only be
  226. // called on the IO thread.
  227. void DestroyOnIOThreadShutdown();
  228. // If there is a registered shutdown callback (meaning shutdown has been
  229. // requested, this checks the Node's status to see if clean shutdown is
  230. // possible. If so, shutdown is performed and the shutdown callback is run.
  231. void AttemptShutdownIfRequested();
  232. // See |ForceDisconnectProcessForTesting()|.
  233. void ForceDisconnectProcessForTestingOnIOThread(base::ProcessId process_id);
  234. // Mark a port that it is about to be merged. This allows us to do a security
  235. // check on the incoming port merge that this port was intended to be merged.
  236. void RecordPendingPortMerge(const ports::PortRef& port);
  237. // These are safe to access from any thread as long as the Node is alive.
  238. const ports::NodeName name_;
  239. const std::unique_ptr<ports::Node> node_;
  240. scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
  241. // Guards |peers_| and |pending_peer_messages_|.
  242. base::Lock peers_lock_;
  243. // Channels to known peers, including inviter and invitees, if any.
  244. NodeMap peers_;
  245. BoundedPeerSet dropped_peers_;
  246. // Outgoing message queues for peers we've heard of but can't yet talk to.
  247. std::unordered_map<ports::NodeName, OutgoingMessageQueue>
  248. pending_peer_messages_;
  249. // Guards |reserved_ports_|.
  250. base::Lock reserved_ports_lock_;
  251. // Ports reserved by name, per peer.
  252. std::map<ports::NodeName, PortMap> reserved_ports_;
  253. // Guards |pending_port_merges_| and |reject_pending_merges_|.
  254. base::Lock pending_port_merges_lock_;
  255. // A set of port merge requests awaiting inviter connection.
  256. std::vector<std::pair<std::string, ports::PortRef>> pending_port_merges_;
  257. // Indicates that new merge requests should be rejected because the inviter
  258. // has disconnected.
  259. bool reject_pending_merges_ = false;
  260. // Guards |inviter_name_| and |bootstrap_inviter_channel_|.
  261. base::Lock inviter_lock_;
  262. // The name of the node which invited us to join its network, if any.
  263. ports::NodeName inviter_name_;
  264. // A temporary reference to the inviter channel before we know their name.
  265. scoped_refptr<NodeChannel> bootstrap_inviter_channel_;
  266. // Guards |broker_name_|, |pending_broker_clients_|, and
  267. // |pending_relay_messages_|.
  268. base::Lock broker_lock_;
  269. // The name of our broker node, if any.
  270. ports::NodeName broker_name_;
  271. // A queue of remote broker clients waiting to be connected to the broker.
  272. base::queue<ports::NodeName> pending_broker_clients_;
  273. // Messages waiting to be relayed by the broker once it's known.
  274. std::unordered_map<ports::NodeName, OutgoingMessageQueue>
  275. pending_relay_messages_;
  276. // Guards |shutdown_callback_|.
  277. base::Lock shutdown_lock_;
  278. // Set by RequestShutdown(). If this is non-null, the controller will
  279. // begin polling the Node to see if clean shutdown is possible any time the
  280. // Node's state is modified by the controller.
  281. base::OnceClosure shutdown_callback_;
  282. // Flag to fast-path checking |shutdown_callback_|.
  283. AtomicFlag shutdown_callback_flag_;
  284. // All other fields below must only be accessed on the I/O thread, i.e., the
  285. // thread on which `io_task_runner_` runs tasks.
  286. // Channels to invitees during handshake.
  287. NodeMap pending_invitations_;
  288. std::map<ports::NodeName, IsolatedConnection> pending_isolated_connections_;
  289. std::map<std::string, ports::NodeName> named_isolated_connections_;
  290. // Indicates whether this object should delete itself on IO thread shutdown.
  291. // Must only be accessed from the IO thread.
  292. bool destroy_on_io_thread_shutdown_ = false;
  293. #if !BUILDFLAG(IS_APPLE) && !BUILDFLAG(IS_NACL) && !BUILDFLAG(IS_FUCHSIA)
  294. // Broker for sync shared buffer creation on behalf of broker clients.
  295. std::unique_ptr<Broker> broker_;
  296. #endif
  297. };
  298. } // namespace core
  299. } // namespace mojo
  300. #endif // MOJO_CORE_NODE_CONTROLLER_H_