Switch.hpp 10 KB

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