Switch.hpp 11 KB

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