Switch.hpp 7.7 KB

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