Switch.hpp 11 KB

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