Switch.hpp 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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: 2024-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 "Utils.hpp"
  23. #include "InetAddress.hpp"
  24. #include "Topology.hpp"
  25. #include "Network.hpp"
  26. #include "SharedPtr.hpp"
  27. #include "IncomingPacket.hpp"
  28. #include "Hashtable.hpp"
  29. #include "Protocol.hpp"
  30. namespace ZeroTier {
  31. class RuntimeEnvironment;
  32. class Peer;
  33. /**
  34. * Core of the distributed Ethernet switch and protocol implementation
  35. *
  36. * This class is perhaps a bit misnamed, but it's basically where everything
  37. * meets. Transport-layer ZT packets come in here, as do virtual network
  38. * packets from tap devices, and this sends them where they need to go and
  39. * wraps/unwraps accordingly. It also handles queues and timeouts and such.
  40. */
  41. class Switch
  42. {
  43. public:
  44. explicit Switch(const RuntimeEnvironment *renv);
  45. /**
  46. * Called when a packet is received from the real network
  47. *
  48. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  49. * @param localSocket Local I/O socket as supplied by external code
  50. * @param fromAddr Internet IP address of origin
  51. * @param data Packet data
  52. * @param len Packet length
  53. */
  54. void onRemotePacket(void *tPtr,int64_t localSocket,const InetAddress &fromAddr,const void *data,unsigned int len);
  55. /**
  56. * Called when a packet comes from a local Ethernet tap
  57. *
  58. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  59. * @param network Which network's TAP did this packet come from?
  60. * @param from Originating MAC address
  61. * @param to Destination MAC address
  62. * @param etherType Ethernet packet type
  63. * @param vlanId VLAN ID or 0 if none
  64. * @param data Ethernet payload
  65. * @param len Frame length
  66. */
  67. 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);
  68. /**
  69. * Send a packet to a ZeroTier address (destination in packet)
  70. *
  71. * The packet must be fully composed with source and destination but not
  72. * yet encrypted. If the destination peer is known the packet
  73. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  74. *
  75. * The packet may be compressed. Compression isn't done here.
  76. *
  77. * Needless to say, the packet's source must be this node. Otherwise it
  78. * won't be encrypted right. (This is not used for relaying.)
  79. *
  80. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  81. * @param packet Packet to send (buffer may be modified)
  82. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  83. */
  84. void send(void *tPtr,Packet &packet,bool encrypt);
  85. /**
  86. * Request WHOIS on a given address
  87. *
  88. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  89. * @param now Current time
  90. * @param addr Address to look up
  91. */
  92. void requestWhois(void *tPtr,int64_t now,const Address &addr);
  93. /**
  94. * Run any processes that are waiting for this peer's identity
  95. *
  96. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  97. *
  98. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  99. * @param peer New peer
  100. */
  101. void doAnythingWaitingForPeer(void *tPtr,const SharedPtr<Peer> &peer);
  102. /**
  103. * Perform retries and other periodic timer tasks
  104. *
  105. * This can return a very long delay if there are no pending timer
  106. * tasks. The caller should cap this comparatively vs. other values.
  107. *
  108. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  109. * @param now Current time
  110. * @return Number of milliseconds until doTimerTasks() should be run again
  111. */
  112. unsigned long doTimerTasks(void *tPtr,int64_t now);
  113. private:
  114. bool _trySend(void *tPtr,Packet &packet,bool encrypt); // packet is modified if return is true
  115. const RuntimeEnvironment *const RR;
  116. volatile int64_t _lastCheckedQueues;
  117. // Time we last sent a WHOIS request for each address
  118. Hashtable< Address,int64_t > _lastSentWhoisRequest;
  119. Mutex _lastSentWhoisRequest_m;
  120. // Packets waiting for WHOIS replies or other decode info or missing fragments
  121. struct RXQueueEntry
  122. {
  123. ZT_ALWAYS_INLINE RXQueueEntry() : timestamp(0) {}
  124. volatile int64_t timestamp; // 0 if entry is not in use
  125. volatile uint64_t packetId;
  126. IncomingPacket frag0; // head of packet
  127. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1]; // later fragments (if any)
  128. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  129. uint32_t haveFragments; // bit mask, LSB to MSB
  130. volatile bool complete; // if true, packet is complete
  131. Mutex lock;
  132. };
  133. RXQueueEntry _rxQueue[ZT_RX_QUEUE_SIZE];
  134. AtomicCounter _rxQueuePtr;
  135. // Returns matching or next available RX queue entry
  136. ZT_ALWAYS_INLINE RXQueueEntry *_findRXQueueEntry(uint64_t packetId)
  137. {
  138. const unsigned int current = static_cast<unsigned int>(_rxQueuePtr.load());
  139. for(unsigned int k=1;k<=ZT_RX_QUEUE_SIZE;++k) {
  140. RXQueueEntry *rq = &(_rxQueue[(current - k) % ZT_RX_QUEUE_SIZE]);
  141. if ((rq->packetId == packetId)&&(rq->timestamp))
  142. return rq;
  143. }
  144. ++_rxQueuePtr;
  145. return &(_rxQueue[static_cast<unsigned int>(current) % ZT_RX_QUEUE_SIZE]);
  146. }
  147. // Returns current entry in rx queue ring buffer and increments ring pointer
  148. ZT_ALWAYS_INLINE RXQueueEntry *_nextRXQueueEntry()
  149. {
  150. return &(_rxQueue[static_cast<unsigned int>((++_rxQueuePtr) - 1) % ZT_RX_QUEUE_SIZE]);
  151. }
  152. // ZeroTier-layer TX queue entry
  153. struct TXQueueEntry
  154. {
  155. ZT_ALWAYS_INLINE TXQueueEntry() {}
  156. ZT_ALWAYS_INLINE TXQueueEntry(Address d,uint64_t ct,const Packet &p,bool enc) :
  157. dest(d),
  158. creationTime(ct),
  159. packet(p),
  160. encrypt(enc) {}
  161. Address dest;
  162. uint64_t creationTime;
  163. Packet packet; // unencrypted/unMAC'd packet -- this is done at send time
  164. bool encrypt;
  165. };
  166. std::list< TXQueueEntry > _txQueue;
  167. Mutex _txQueue_m;
  168. };
  169. } // namespace ZeroTier
  170. #endif