Switch.hpp 7.7 KB

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