port.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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_PORTS_PORT_H_
  5. #define MOJO_CORE_PORTS_PORT_H_
  6. #include <map>
  7. #include <memory>
  8. #include <queue>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/containers/queue.h"
  12. #include "base/memory/ref_counted.h"
  13. #include "base/synchronization/lock.h"
  14. #include "mojo/core/ports/event.h"
  15. #include "mojo/core/ports/message_queue.h"
  16. #include "mojo/core/ports/user_data.h"
  17. namespace mojo {
  18. namespace core {
  19. namespace ports {
  20. class PortLocker;
  21. // A Port is essentially a node in a circular list of addresses. For the sake of
  22. // this documentation such a list will henceforth be referred to as a "route."
  23. // Routes are the fundamental medium upon which all Node event circulation takes
  24. // place and are thus the backbone of all Mojo message passing.
  25. //
  26. // Each Port is identified by a 128-bit address within a Node (see node.h). A
  27. // Port doesn't really *do* anything per se: it's a named collection of state,
  28. // and its owning Node manages all event production, transmission, routing, and
  29. // processing logic. See Node for more details on how Ports may be used to
  30. // transmit arbitrary user messages as well as other Ports.
  31. //
  32. // Ports may be in any of a handful of states (see State below) which dictate
  33. // how they react to system events targeting them. In the simplest and most
  34. // common case, Ports are initially created as an entangled pair (i.e. a simple
  35. // cycle consisting of two Ports) both in the |kReceiving| State. Consider Ports
  36. // we'll label |A| and |B| here, which may be created using
  37. // Node::CreatePortPair():
  38. //
  39. // +-----+ +-----+
  40. // | |--------->| |
  41. // | A | | B |
  42. // | |<---------| |
  43. // +-----+ +-----+
  44. //
  45. // |A| references |B| via |peer_node_name| and |peer_port_name|, while |B| in
  46. // turn references |A|. Note that a Node is NEVER aware of who is sending events
  47. // to a given Port; it is only aware of where it must route events FROM a given
  48. // Port.
  49. //
  50. // For the sake of documentation, we refer to one receiving port in a route as
  51. // the "conjugate" of the other. A receiving port's conjugate is also its peer
  52. // upon initial creation, but because of proxying this may not be the case at a
  53. // later time.
  54. //
  55. // ALL access to this data structure must be guarded by |lock_| acquisition,
  56. // which is only possible using a PortLocker. PortLocker ensures that
  57. // overlapping Port lock acquisitions on a single thread are always acquired in
  58. // a globally consistent order.
  59. class Port : public base::RefCountedThreadSafe<Port> {
  60. public:
  61. // The state of a given Port. A Port may only exist in one of these states at
  62. // any given time.
  63. enum State {
  64. // The Port is not yet paired with a peer and is therefore unusable. See
  65. // Node::CreateUninitializedPort and Node::InitializePort for motivation.
  66. kUninitialized,
  67. // The Port is publicly visible outside of its Node and may be used to send
  68. // and receive user messages. There are always AT MOST two |kReceiving|
  69. // Ports along any given route. A user message event sent from a receiving
  70. // port is always circulated along the Port's route until it reaches either
  71. // a dead-end -- in which case the route is broken -- or it reaches the
  72. // other receiving Port in the route -- in which case it lands in that
  73. // Port's incoming message queue which can by read by user code.
  74. kReceiving,
  75. // The Port has been taken out of the |kReceiving| state in preparation for
  76. // proxying to a new destination. A Port enters this state immediately when
  77. // it's attached to a user message and may only leave this state when
  78. // transitioning to |kProxying|. See Node for more details.
  79. kBuffering,
  80. // The Port is forwarding all user messages (and most other events) to its
  81. // peer without discretion. Ports in the |kProxying| state may never leave
  82. // this state and only exist temporarily until their owning Node has
  83. // established that no more events will target them. See Node for more
  84. // details.
  85. kProxying,
  86. // The Port has been closed and is now permanently unusable. Only
  87. // |kReceiving| ports can be closed.
  88. kClosed
  89. };
  90. // The current State of the Port.
  91. State state;
  92. // The Node and Port address to which events should be routed FROM this Port.
  93. // Note that this is NOT necessarily the address of the Port currently sending
  94. // events TO this Port.
  95. NodeName peer_node_name;
  96. PortName peer_port_name;
  97. // We keep track of the port that is currently sending messages to this port.
  98. // This allows us to verify that the sender node is allowed to send messages
  99. // to this port as a mitigation against info leak vulnerabilities.
  100. // Tracking the previous port has the nice side effect of keeping received
  101. // messages in order.
  102. NodeName prev_node_name;
  103. PortName prev_port_name;
  104. // Mark this port as to be merged.
  105. bool pending_merge_peer;
  106. // Next sequence number to send for all event messages.
  107. uint64_t next_control_sequence_num_to_send;
  108. uint64_t next_control_sequence_num_to_receive;
  109. // The next available sequence number to use for outgoing user message events
  110. // originating from this port.
  111. uint64_t next_sequence_num_to_send;
  112. // The largest acknowledged user message event sequence number.
  113. uint64_t last_sequence_num_acknowledged;
  114. // The interval for which acknowledge requests will be sent. A value of N will
  115. // cause an acknowledge request for |last_sequence_num_acknowledged| + N when
  116. // initially set and on received acknowledge. This means that the lower bound
  117. // for unread or in-transit messages is |next_sequence_num_to_send| -
  118. // |last_sequence_num_acknowledged| + |sequence_number_acknowledge_interval|.
  119. // If zero, no acknowledge requests are sent.
  120. uint64_t sequence_num_acknowledge_interval;
  121. // The sequence number of the last message this Port should ever expect to
  122. // receive in its lifetime. May be used to determine that a proxying port is
  123. // ready to be destroyed or that a receiving port's conjugate has been closed
  124. // and we know the sequence number of the last message it sent.
  125. uint64_t last_sequence_num_to_receive;
  126. // The sequence number of the message for which this Port should send an
  127. // acknowledge message. In the buffering state, holds the acknowledge request
  128. // value that is forwarded to the peer on transition to proxying.
  129. // This is zero in any port that's never received an acknowledge request, and
  130. // in proxies that have forwarded a stored acknowledge.
  131. uint64_t sequence_num_to_acknowledge;
  132. // The queue of incoming user messages received by this Port. Only non-empty
  133. // for buffering or receiving Ports. When a buffering port enters the proxying
  134. // state, it flushes its queue and the proxy then bypasses the queue
  135. // indefinitely.
  136. //
  137. // A receiving port's queue only has elements removed by user code reading
  138. // messages from the port.
  139. //
  140. // Note that this is a priority queue which only exposes messages to consumers
  141. // in strict sequential order.
  142. MessageQueue message_queue;
  143. // Buffer outgoing control messages while this port is in kBuffering state.
  144. base::queue<std::pair<NodeName, ScopedEvent>> control_message_queue;
  145. // In some edge cases, a Node may need to remember to route a single special
  146. // event upon destruction of this (proxying) Port. That event is stashed here
  147. // in the interim.
  148. std::unique_ptr<std::pair<NodeName, ScopedEvent>> send_on_proxy_removal;
  149. // Arbitrary user data attached to the Port. In practice, Mojo uses this to
  150. // stash an observer interface which can be notified about various Port state
  151. // changes.
  152. scoped_refptr<UserData> user_data;
  153. // Indicates that this (proxying) Port has received acknowledgement that no
  154. // new user messages will be routed to it. If |true|, the proxy will be
  155. // removed once it has received and forwarded all sequenced messages up to and
  156. // including the one numbered |last_sequence_num_to_receive|.
  157. bool remove_proxy_on_last_message;
  158. // Indicates that this Port is aware that its nearest (in terms of forward,
  159. // non-zero cyclic routing distance) receiving Port has been closed.
  160. bool peer_closed;
  161. // Indicates that this Port lost its peer unexpectedly (e.g. via process death
  162. // rather than receiving an ObserveClosure event). In this case
  163. // |peer_closed| will be true but |last_sequence_num_to_receive| cannot be
  164. // known. Such ports will continue to make message available until their
  165. // message queue is empty.
  166. bool peer_lost_unexpectedly;
  167. Port(uint64_t next_sequence_num_to_send,
  168. uint64_t next_sequence_num_to_receive);
  169. Port(const Port&) = delete;
  170. Port& operator=(const Port&) = delete;
  171. void AssertLockAcquired() {
  172. #if DCHECK_IS_ON()
  173. lock_.AssertAcquired();
  174. #endif
  175. }
  176. // Check if the given event should be handled next based on the sequence
  177. // number and sender peer.
  178. bool IsNextEvent(const NodeName& from_node, const Event& event);
  179. // Get the next buffered event to be processed. If none is available, |event|
  180. // will not be modified.
  181. void NextEvent(NodeName* from_node, ScopedEvent* event);
  182. // Buffer the event for later processing.
  183. void BufferEvent(const NodeName& from_node, ScopedEvent event);
  184. // Flushes the queue of events pending peer verification and returns all user
  185. // events
  186. void TakePendingMessages(
  187. std::vector<std::unique_ptr<UserMessageEvent>>& messages);
  188. private:
  189. using NodePortPair = std::pair<NodeName, PortName>;
  190. using EventQueue = std::vector<std::unique_ptr<Event>>;
  191. std::map<NodePortPair, EventQueue> control_event_queues_;
  192. friend class base::RefCountedThreadSafe<Port>;
  193. friend class PortLocker;
  194. ~Port();
  195. base::Lock lock_;
  196. };
  197. } // namespace ports
  198. } // namespace core
  199. } // namespace mojo
  200. #endif // MOJO_CORE_PORTS_PORT_H_