Switch.hpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #ifndef ZT_N_SWITCH_HPP
  19. #define ZT_N_SWITCH_HPP
  20. #include <map>
  21. #include <set>
  22. #include <vector>
  23. #include <list>
  24. #include "Constants.hpp"
  25. #include "Mutex.hpp"
  26. #include "MAC.hpp"
  27. #include "NonCopyable.hpp"
  28. #include "Packet.hpp"
  29. #include "Utils.hpp"
  30. #include "InetAddress.hpp"
  31. #include "Topology.hpp"
  32. #include "Array.hpp"
  33. #include "Network.hpp"
  34. #include "SharedPtr.hpp"
  35. #include "IncomingPacket.hpp"
  36. #include "Hashtable.hpp"
  37. namespace ZeroTier {
  38. class RuntimeEnvironment;
  39. class Peer;
  40. /**
  41. * Core of the distributed Ethernet switch and protocol implementation
  42. *
  43. * This class is perhaps a bit misnamed, but it's basically where everything
  44. * meets. Transport-layer ZT packets come in here, as do virtual network
  45. * packets from tap devices, and this sends them where they need to go and
  46. * wraps/unwraps accordingly. It also handles queues and timeouts and such.
  47. */
  48. class Switch : NonCopyable
  49. {
  50. public:
  51. Switch(const RuntimeEnvironment *renv);
  52. /**
  53. * Called when a packet is received from the real network
  54. *
  55. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  56. * @param localAddr Local interface address
  57. * @param fromAddr Internet IP address of origin
  58. * @param data Packet data
  59. * @param len Packet length
  60. */
  61. void onRemotePacket(void *tPtr,const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  62. /**
  63. * Called when a packet comes from a local Ethernet tap
  64. *
  65. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  66. * @param network Which network's TAP did this packet come from?
  67. * @param from Originating MAC address
  68. * @param to Destination MAC address
  69. * @param etherType Ethernet packet type
  70. * @param vlanId VLAN ID or 0 if none
  71. * @param data Ethernet payload
  72. * @param len Frame length
  73. */
  74. 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);
  75. /**
  76. * Send a packet to a ZeroTier address (destination in packet)
  77. *
  78. * The packet must be fully composed with source and destination but not
  79. * yet encrypted. If the destination peer is known the packet
  80. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  81. *
  82. * The packet may be compressed. Compression isn't done here.
  83. *
  84. * Needless to say, the packet's source must be this node. Otherwise it
  85. * won't be encrypted right. (This is not used for relaying.)
  86. *
  87. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  88. * @param packet Packet to send (buffer may be modified)
  89. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  90. */
  91. void send(void *tPtr,Packet &packet,bool encrypt);
  92. /**
  93. * Request WHOIS on a given address
  94. *
  95. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  96. * @param addr Address to look up
  97. */
  98. void requestWhois(void *tPtr,const Address &addr);
  99. /**
  100. * Run any processes that are waiting for this peer's identity
  101. *
  102. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  103. *
  104. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  105. * @param peer New peer
  106. */
  107. void doAnythingWaitingForPeer(void *tPtr,const SharedPtr<Peer> &peer);
  108. /**
  109. * Perform retries and other periodic timer tasks
  110. *
  111. * This can return a very long delay if there are no pending timer
  112. * tasks. The caller should cap this comparatively vs. other values.
  113. *
  114. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  115. * @param now Current time
  116. * @return Number of milliseconds until doTimerTasks() should be run again
  117. */
  118. unsigned long doTimerTasks(void *tPtr,uint64_t now);
  119. private:
  120. bool _shouldUnite(const uint64_t now,const Address &source,const Address &destination);
  121. Address _sendWhoisRequest(void *tPtr,const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
  122. bool _trySend(void *tPtr,Packet &packet,bool encrypt); // packet is modified if return is true
  123. const RuntimeEnvironment *const RR;
  124. uint64_t _lastBeaconResponse;
  125. // Outstanding WHOIS requests and how many retries they've undergone
  126. struct WhoisRequest
  127. {
  128. WhoisRequest() : lastSent(0),retries(0) {}
  129. uint64_t lastSent;
  130. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  131. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  132. };
  133. Hashtable< Address,WhoisRequest > _outstandingWhoisRequests;
  134. Mutex _outstandingWhoisRequests_m;
  135. // Packets waiting for WHOIS replies or other decode info or missing fragments
  136. struct RXQueueEntry
  137. {
  138. RXQueueEntry() : timestamp(0) {}
  139. uint64_t timestamp; // 0 if entry is not in use
  140. 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. bool complete; // if true, packet is complete
  146. };
  147. RXQueueEntry _rxQueue[ZT_RX_QUEUE_SIZE];
  148. Mutex _rxQueue_m;
  149. /* Returns the matching or oldest entry. Caller must check timestamp and
  150. * packet ID to determine which. */
  151. inline RXQueueEntry *_findRXQueueEntry(uint64_t now,uint64_t packetId)
  152. {
  153. RXQueueEntry *rq;
  154. RXQueueEntry *oldest = &(_rxQueue[ZT_RX_QUEUE_SIZE - 1]);
  155. unsigned long i = ZT_RX_QUEUE_SIZE;
  156. while (i) {
  157. rq = &(_rxQueue[--i]);
  158. if ((rq->packetId == packetId)&&(rq->timestamp))
  159. return rq;
  160. if ((now - rq->timestamp) >= ZT_RX_QUEUE_EXPIRE)
  161. rq->timestamp = 0;
  162. if (rq->timestamp < oldest->timestamp)
  163. oldest = rq;
  164. }
  165. return oldest;
  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 throw() { return ((unsigned long)x ^ (unsigned long)y); }
  198. inline bool operator==(const _LastUniteKey &k) const throw() { 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