Switch.hpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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 "Array.hpp"
  41. #include "Network.hpp"
  42. #include "SharedPtr.hpp"
  43. #include "IncomingPacket.hpp"
  44. #include "Hashtable.hpp"
  45. namespace ZeroTier {
  46. class RuntimeEnvironment;
  47. class Peer;
  48. /**
  49. * Core of the distributed Ethernet switch and protocol implementation
  50. *
  51. * This class is perhaps a bit misnamed, but it's basically where everything
  52. * meets. Transport-layer ZT packets come in here, as do virtual network
  53. * packets from tap devices, and this sends them where they need to go and
  54. * wraps/unwraps accordingly. It also handles queues and timeouts and such.
  55. */
  56. class Switch : NonCopyable
  57. {
  58. public:
  59. Switch(const RuntimeEnvironment *renv);
  60. /**
  61. * Called when a packet is received from the real network
  62. *
  63. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  64. * @param localAddr Local interface address
  65. * @param fromAddr Internet IP address of origin
  66. * @param data Packet data
  67. * @param len Packet length
  68. */
  69. void onRemotePacket(void *tPtr,const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  70. /**
  71. * Called when a packet comes from a local Ethernet tap
  72. *
  73. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  74. * @param network Which network's TAP did this packet come from?
  75. * @param from Originating MAC address
  76. * @param to Destination MAC address
  77. * @param etherType Ethernet packet type
  78. * @param vlanId VLAN ID or 0 if none
  79. * @param data Ethernet payload
  80. * @param len Frame length
  81. */
  82. 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);
  83. /**
  84. * Send a packet to a ZeroTier address (destination in packet)
  85. *
  86. * The packet must be fully composed with source and destination but not
  87. * yet encrypted. If the destination peer is known the packet
  88. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  89. *
  90. * The packet may be compressed. Compression isn't done here.
  91. *
  92. * Needless to say, the packet's source must be this node. Otherwise it
  93. * won't be encrypted right. (This is not used for relaying.)
  94. *
  95. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  96. * @param packet Packet to send (buffer may be modified)
  97. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  98. */
  99. void send(void *tPtr,Packet &packet,bool encrypt);
  100. /**
  101. * Request WHOIS on a given address
  102. *
  103. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  104. * @param addr Address to look up
  105. */
  106. void requestWhois(void *tPtr,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,uint64_t now);
  127. private:
  128. bool _shouldUnite(const uint64_t now,const Address &source,const Address &destination);
  129. Address _sendWhoisRequest(void *tPtr,const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
  130. bool _trySend(void *tPtr,Packet &packet,bool encrypt); // packet is modified if return is true
  131. const RuntimeEnvironment *const RR;
  132. uint64_t _lastBeaconResponse;
  133. // Outstanding WHOIS requests and how many retries they've undergone
  134. struct WhoisRequest
  135. {
  136. WhoisRequest() : lastSent(0),retries(0) {}
  137. uint64_t lastSent;
  138. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  139. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  140. };
  141. Hashtable< Address,WhoisRequest > _outstandingWhoisRequests;
  142. Mutex _outstandingWhoisRequests_m;
  143. // Packets waiting for WHOIS replies or other decode info or missing fragments
  144. struct RXQueueEntry
  145. {
  146. RXQueueEntry() : timestamp(0) {}
  147. uint64_t timestamp; // 0 if entry is not in use
  148. uint64_t packetId;
  149. IncomingPacket frag0; // head of packet
  150. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1]; // later fragments (if any)
  151. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  152. uint32_t haveFragments; // bit mask, LSB to MSB
  153. bool complete; // if true, packet is complete
  154. };
  155. RXQueueEntry _rxQueue[ZT_RX_QUEUE_SIZE];
  156. Mutex _rxQueue_m;
  157. /* Returns the matching or oldest entry. Caller must check timestamp and
  158. * packet ID to determine which. */
  159. inline RXQueueEntry *_findRXQueueEntry(uint64_t now,uint64_t packetId)
  160. {
  161. RXQueueEntry *rq;
  162. RXQueueEntry *oldest = &(_rxQueue[ZT_RX_QUEUE_SIZE - 1]);
  163. unsigned long i = ZT_RX_QUEUE_SIZE;
  164. while (i) {
  165. rq = &(_rxQueue[--i]);
  166. if ((rq->packetId == packetId)&&(rq->timestamp))
  167. return rq;
  168. if ((now - rq->timestamp) >= ZT_RX_QUEUE_EXPIRE)
  169. rq->timestamp = 0;
  170. if (rq->timestamp < oldest->timestamp)
  171. oldest = rq;
  172. }
  173. return oldest;
  174. }
  175. // ZeroTier-layer TX queue entry
  176. struct TXQueueEntry
  177. {
  178. TXQueueEntry() {}
  179. TXQueueEntry(Address d,uint64_t ct,const Packet &p,bool enc) :
  180. dest(d),
  181. creationTime(ct),
  182. packet(p),
  183. encrypt(enc) {}
  184. Address dest;
  185. uint64_t creationTime;
  186. Packet packet; // unencrypted/unMAC'd packet -- this is done at send time
  187. bool encrypt;
  188. };
  189. std::list< TXQueueEntry > _txQueue;
  190. Mutex _txQueue_m;
  191. // Tracks sending of VERB_RENDEZVOUS to relaying peers
  192. struct _LastUniteKey
  193. {
  194. _LastUniteKey() : x(0),y(0) {}
  195. _LastUniteKey(const Address &a1,const Address &a2)
  196. {
  197. if (a1 > a2) {
  198. x = a2.toInt();
  199. y = a1.toInt();
  200. } else {
  201. x = a1.toInt();
  202. y = a2.toInt();
  203. }
  204. }
  205. inline unsigned long hashCode() const throw() { return ((unsigned long)x ^ (unsigned long)y); }
  206. inline bool operator==(const _LastUniteKey &k) const throw() { return ((x == k.x)&&(y == k.y)); }
  207. uint64_t x,y;
  208. };
  209. Hashtable< _LastUniteKey,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  210. Mutex _lastUniteAttempt_m;
  211. };
  212. } // namespace ZeroTier
  213. #endif