2
0

Switch.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_N_SWITCH_HPP
  14. #define ZT_N_SWITCH_HPP
  15. #include "Constants.hpp"
  16. #include "Hashtable.hpp"
  17. #include "IncomingPacket.hpp"
  18. #include "InetAddress.hpp"
  19. #include "MAC.hpp"
  20. #include "Mutex.hpp"
  21. #include "Network.hpp"
  22. #include "Packet.hpp"
  23. #include "SharedPtr.hpp"
  24. #include "Topology.hpp"
  25. #include <list>
  26. #include <map>
  27. #include <vector>
  28. /* Ethernet frame types that might be relevant to us */
  29. #define ZT_ETHERTYPE_IPV4 0x0800
  30. #define ZT_ETHERTYPE_ARP 0x0806
  31. #define ZT_ETHERTYPE_RARP 0x8035
  32. #define ZT_ETHERTYPE_ATALK 0x809b
  33. #define ZT_ETHERTYPE_AARP 0x80f3
  34. #define ZT_ETHERTYPE_IPX_A 0x8137
  35. #define ZT_ETHERTYPE_IPX_B 0x8138
  36. #define ZT_ETHERTYPE_IPV6 0x86dd
  37. namespace ZeroTier {
  38. class RuntimeEnvironment;
  39. class Peer;
  40. /**
  41. * Core of the distributed Ethernet switch and protocol implementation
  42. *
  43. * This class is perhaps a bit misnamed, but it's basically where everything
  44. * meets. Transport-layer ZT packets come in here, as do virtual network
  45. * packets from tap devices, and this sends them where they need to go and
  46. * wraps/unwraps accordingly. It also handles queues and timeouts and such.
  47. */
  48. class Switch {
  49. struct ManagedQueue;
  50. struct TXQueueEntry;
  51. friend class SharedPtr<Peer>;
  52. typedef struct {
  53. TXQueueEntry* p;
  54. bool ok_to_drop;
  55. } dqr;
  56. public:
  57. Switch(const RuntimeEnvironment* renv);
  58. /**
  59. * Called when a packet is received from the real network
  60. *
  61. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  62. * @param localSocket Local I/O socket as supplied by external code
  63. * @param fromAddr Internet IP address of origin
  64. * @param data Packet data
  65. * @param len Packet length
  66. */
  67. void onRemotePacket(void* tPtr, const int64_t localSocket, const InetAddress& fromAddr, const void* data, unsigned int len);
  68. /**
  69. * Returns whether our bonding or balancing policy is aware of flows.
  70. */
  71. bool isFlowAware();
  72. /**
  73. * Called when a packet comes from a local Ethernet tap
  74. *
  75. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  76. * @param network Which network's TAP did this packet come from?
  77. * @param from Originating MAC address
  78. * @param to Destination MAC address
  79. * @param etherType Ethernet packet type
  80. * @param vlanId VLAN ID or 0 if none
  81. * @param data Ethernet payload
  82. * @param len Frame length
  83. */
  84. void onLocalEthernet(void* tPtr, const SharedPtr<Network>& network, const MAC& from, const MAC& to, unsigned int etherType, unsigned int vlanId, const void* data, unsigned int len);
  85. /**
  86. * Determines the next drop schedule for packets in the TX queue
  87. *
  88. * @param t Current time
  89. * @param count Number of packets dropped this round
  90. */
  91. uint64_t control_law(uint64_t t, int count);
  92. /**
  93. * Selects a packet eligible for transmission from a TX queue. According to the control law, multiple packets
  94. * may be intentionally dropped before a packet is returned to the AQM scheduler.
  95. *
  96. * @param q The TX queue that is being dequeued from
  97. * @param now Current time
  98. */
  99. dqr dodequeue(ManagedQueue* q, uint64_t now);
  100. /**
  101. * Presents a packet to the AQM scheduler.
  102. *
  103. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  104. * @param network Network that the packet shall be sent over
  105. * @param packet Packet to be sent
  106. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  107. * @param qosBucket Which bucket the rule-system determined this packet should fall into
  108. */
  109. void aqm_enqueue(void* tPtr, const SharedPtr<Network>& network, Packet& packet, const bool encrypt, const int qosBucket, const uint64_t nwid, const int32_t flowId /* = ZT_QOS_NO_FLOW*/);
  110. /**
  111. * Performs a single AQM cycle and dequeues and transmits all eligible packets on all networks
  112. *
  113. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  114. */
  115. void aqm_dequeue(void* tPtr);
  116. /**
  117. * Calls the dequeue mechanism and adjust queue state variables
  118. *
  119. * @param q The TX queue that is being dequeued from
  120. * @param isNew Whether or not this queue is in the NEW list
  121. * @param now Current time
  122. */
  123. Switch::TXQueueEntry* CoDelDequeue(ManagedQueue* q, bool isNew, uint64_t now);
  124. /**
  125. * Removes QoS Queues and flow state variables for a specific network. These queues are created
  126. * automatically upon the transmission of the first packet from this peer to another peer on the
  127. * given network.
  128. *
  129. * The reason for existence of queues and flow state variables specific to each network is so that
  130. * each network's QoS rules function independently.
  131. *
  132. * @param nwid Network ID
  133. */
  134. void removeNetworkQoSControlBlock(uint64_t nwid);
  135. /**
  136. * Send a packet to a ZeroTier address (destination in packet)
  137. *
  138. * The packet must be fully composed with source and destination but not
  139. * yet encrypted. If the destination peer is known the packet
  140. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  141. *
  142. * The packet may be compressed. Compression isn't done here.
  143. *
  144. * Needless to say, the packet's source must be this node. Otherwise it
  145. * won't be encrypted right. (This is not used for relaying.)
  146. *
  147. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  148. * @param packet Packet to send (buffer may be modified)
  149. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  150. * @param nwid Network ID to which this packet is related or 0 if none
  151. */
  152. void send(void* tPtr, Packet& packet, const bool encrypt, const uint64_t nwid, const int32_t flowId /* = ZT_QOS_NO_FLOW*/);
  153. /**
  154. * Request WHOIS on a given address
  155. *
  156. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  157. * @param now Current time
  158. * @param addr Address to look up
  159. */
  160. void requestWhois(void* tPtr, const int64_t now, const Address& addr);
  161. /**
  162. * Run any processes that are waiting for this peer's identity
  163. *
  164. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  165. *
  166. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  167. * @param peer New peer
  168. */
  169. void doAnythingWaitingForPeer(void* tPtr, const SharedPtr<Peer>& peer);
  170. /**
  171. * Perform retries and other periodic timer tasks
  172. *
  173. * This can return a very long delay if there are no pending timer
  174. * tasks. The caller should cap this comparatively vs. other values.
  175. *
  176. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  177. * @param now Current time
  178. * @return Number of milliseconds until doTimerTasks() should be run again
  179. */
  180. unsigned long doTimerTasks(void* tPtr, int64_t now);
  181. private:
  182. bool _shouldUnite(const int64_t now, const Address& source, const Address& destination);
  183. bool _trySend(void* tPtr, Packet& packet, bool encrypt, const uint64_t nwid, const int32_t flowId /* = ZT_QOS_NO_FLOW*/);
  184. void _sendViaSpecificPath(void* tPtr, SharedPtr<Peer> peer, SharedPtr<Path> viaPath, uint16_t userSpecifiedMtu, int64_t now, Packet& packet, bool encrypt, int32_t flowId);
  185. void _recordOutgoingPacketMetrics(const Packet& p);
  186. const RuntimeEnvironment* const RR;
  187. int64_t _lastBeaconResponse;
  188. volatile int64_t _lastCheckedQueues;
  189. // Time we last sent a WHOIS request for each address
  190. Hashtable<Address, int64_t> _lastSentWhoisRequest;
  191. Mutex _lastSentWhoisRequest_m;
  192. // Packets waiting for WHOIS replies or other decode info or missing fragments
  193. struct RXQueueEntry {
  194. RXQueueEntry() : timestamp(0)
  195. {
  196. }
  197. volatile int64_t timestamp; // 0 if entry is not in use
  198. volatile uint64_t packetId;
  199. IncomingPacket frag0; // head of packet
  200. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1]; // later fragments (if any)
  201. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  202. uint32_t haveFragments; // bit mask, LSB to MSB
  203. volatile bool complete; // if true, packet is complete
  204. volatile int32_t flowId;
  205. Mutex lock;
  206. };
  207. RXQueueEntry _rxQueue[ZT_RX_QUEUE_SIZE];
  208. AtomicCounter _rxQueuePtr;
  209. // Returns matching or next available RX queue entry
  210. inline RXQueueEntry* _findRXQueueEntry(uint64_t packetId)
  211. {
  212. const unsigned int current = static_cast<unsigned int>(_rxQueuePtr.load());
  213. for (unsigned int k = 1; k <= ZT_RX_QUEUE_SIZE; ++k) {
  214. RXQueueEntry* rq = &(_rxQueue[(current - k) % ZT_RX_QUEUE_SIZE]);
  215. if ((rq->packetId == packetId) && (rq->timestamp)) {
  216. return rq;
  217. }
  218. }
  219. ++_rxQueuePtr;
  220. return &(_rxQueue[static_cast<unsigned int>(current) % ZT_RX_QUEUE_SIZE]);
  221. }
  222. // Returns current entry in rx queue ring buffer and increments ring pointer
  223. inline RXQueueEntry* _nextRXQueueEntry()
  224. {
  225. return &(_rxQueue[static_cast<unsigned int>((++_rxQueuePtr) - 1) % ZT_RX_QUEUE_SIZE]);
  226. }
  227. // ZeroTier-layer TX queue entry
  228. struct TXQueueEntry {
  229. TXQueueEntry()
  230. {
  231. }
  232. TXQueueEntry(Address d, uint64_t nwid, uint64_t ct, const Packet& p, bool enc, int32_t fid) : dest(d), nwid(nwid), creationTime(ct), packet(p), encrypt(enc), flowId(fid)
  233. {
  234. }
  235. Address dest;
  236. uint64_t nwid;
  237. uint64_t creationTime;
  238. Packet packet; // unencrypted/unMAC'd packet -- this is done at send time
  239. bool encrypt;
  240. int32_t flowId;
  241. };
  242. std::list<TXQueueEntry> _txQueue;
  243. Mutex _txQueue_m;
  244. Mutex _aqm_m;
  245. // Tracks sending of VERB_RENDEZVOUS to relaying peers
  246. struct _LastUniteKey {
  247. _LastUniteKey() : x(0), y(0)
  248. {
  249. }
  250. _LastUniteKey(const Address& a1, const Address& a2)
  251. {
  252. if (a1 > a2) {
  253. x = a2.toInt();
  254. y = a1.toInt();
  255. }
  256. else {
  257. x = a1.toInt();
  258. y = a2.toInt();
  259. }
  260. }
  261. inline unsigned long hashCode() const
  262. {
  263. return ((unsigned long)x ^ (unsigned long)y);
  264. }
  265. inline bool operator==(const _LastUniteKey& k) const
  266. {
  267. return ((x == k.x) && (y == k.y));
  268. }
  269. uint64_t x, y;
  270. };
  271. Hashtable<_LastUniteKey, uint64_t> _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  272. Mutex _lastUniteAttempt_m;
  273. // Queue with additional flow state variables
  274. struct ManagedQueue {
  275. ManagedQueue(int id) : id(id), byteCredit(ZT_AQM_QUANTUM), byteLength(0), dropping(false)
  276. {
  277. }
  278. int id;
  279. int byteCredit;
  280. int byteLength;
  281. uint64_t first_above_time;
  282. uint32_t count;
  283. uint64_t drop_next;
  284. bool dropping;
  285. uint64_t drop_next_time;
  286. std::list<TXQueueEntry*> q;
  287. };
  288. // To implement fq_codel we need to maintain a queue of queues
  289. struct NetworkQoSControlBlock {
  290. int _currEnqueuedPackets;
  291. std::vector<ManagedQueue*> newQueues;
  292. std::vector<ManagedQueue*> oldQueues;
  293. std::vector<ManagedQueue*> inactiveQueues;
  294. };
  295. std::map<uint64_t, NetworkQoSControlBlock*> _netQueueControlBlock;
  296. };
  297. } // namespace ZeroTier
  298. #endif