Switch.hpp 6.8 KB

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