Switch.hpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. ~Switch();
  53. /**
  54. * Called when a packet is received from the real network
  55. *
  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(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 network Which network's TAP did this packet come from?
  66. * @param from Originating MAC address
  67. * @param to Destination MAC address
  68. * @param etherType Ethernet packet type
  69. * @param vlanId VLAN ID or 0 if none
  70. * @param data Ethernet payload
  71. * @param len Frame length
  72. */
  73. void onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  74. /**
  75. * Send a packet to a ZeroTier address (destination in packet)
  76. *
  77. * The packet must be fully composed with source and destination but not
  78. * yet encrypted. If the destination peer is known the packet
  79. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  80. *
  81. * The packet may be compressed. Compression isn't done here.
  82. *
  83. * Needless to say, the packet's source must be this node. Otherwise it
  84. * won't be encrypted right. (This is not used for relaying.)
  85. *
  86. * The network ID should only be specified for frames and other actual
  87. * network traffic. Other traffic such as controller requests and regular
  88. * protocol messages should specify zero.
  89. *
  90. * @param packet Packet to send
  91. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  92. * @param nwid Related network ID or 0 if message is not in-network traffic
  93. */
  94. void send(const Packet &packet,bool encrypt,uint64_t nwid);
  95. /**
  96. * Send RENDEZVOUS to two peers to permit them to directly connect
  97. *
  98. * This only works if both peers are known, with known working direct
  99. * links to this peer. The best link for each peer is sent to the other.
  100. *
  101. * @param p1 One of two peers (order doesn't matter)
  102. * @param p2 Second of pair
  103. */
  104. bool unite(const Address &p1,const Address &p2);
  105. /**
  106. * Attempt NAT traversal to peer at a given physical address
  107. *
  108. * @param peer Peer to contact
  109. * @param localAddr Local interface address
  110. * @param atAddr Address of peer
  111. */
  112. void rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr);
  113. /**
  114. * Request WHOIS on a given address
  115. *
  116. * @param addr Address to look up
  117. */
  118. void requestWhois(const Address &addr);
  119. /**
  120. * Run any processes that are waiting for this peer's identity
  121. *
  122. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  123. *
  124. * @param peer New peer
  125. */
  126. void doAnythingWaitingForPeer(const SharedPtr<Peer> &peer);
  127. /**
  128. * Perform retries and other periodic timer tasks
  129. *
  130. * This can return a very long delay if there are no pending timer
  131. * tasks. The caller should cap this comparatively vs. other values.
  132. *
  133. * @param now Current time
  134. * @return Number of milliseconds until doTimerTasks() should be run again
  135. */
  136. unsigned long doTimerTasks(uint64_t now);
  137. private:
  138. void _handleRemotePacketFragment(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  139. void _handleRemotePacketHead(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  140. Address _sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
  141. bool _trySend(const Packet &packet,bool encrypt,uint64_t nwid);
  142. const RuntimeEnvironment *const RR;
  143. uint64_t _lastBeaconResponse;
  144. // Outstanding WHOIS requests and how many retries they've undergone
  145. struct WhoisRequest
  146. {
  147. WhoisRequest() : lastSent(0),retries(0) {}
  148. uint64_t lastSent;
  149. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  150. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  151. };
  152. Hashtable< Address,WhoisRequest > _outstandingWhoisRequests;
  153. Mutex _outstandingWhoisRequests_m;
  154. // Packet defragmentation queue -- comes before RX queue in path
  155. struct DefragQueueEntry
  156. {
  157. DefragQueueEntry() : creationTime(0),totalFragments(0),haveFragments(0) {}
  158. uint64_t creationTime;
  159. SharedPtr<IncomingPacket> frag0;
  160. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1];
  161. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  162. uint32_t haveFragments; // bit mask, LSB to MSB
  163. };
  164. Hashtable< uint64_t,DefragQueueEntry > _defragQueue;
  165. Mutex _defragQueue_m;
  166. // ZeroTier-layer RX queue of incoming packets in the process of being decoded
  167. std::list< SharedPtr<IncomingPacket> > _rxQueue;
  168. Mutex _rxQueue_m;
  169. // ZeroTier-layer TX queue entry
  170. struct TXQueueEntry
  171. {
  172. TXQueueEntry() {}
  173. TXQueueEntry(Address d,uint64_t ct,const Packet &p,bool enc,uint64_t nw) :
  174. dest(d),
  175. creationTime(ct),
  176. nwid(nw),
  177. packet(p),
  178. encrypt(enc) {}
  179. Address dest;
  180. uint64_t creationTime;
  181. uint64_t nwid;
  182. Packet packet; // unencrypted/unMAC'd packet -- this is done at send time
  183. bool encrypt;
  184. };
  185. std::list< TXQueueEntry > _txQueue;
  186. Mutex _txQueue_m;
  187. // Tracks sending of VERB_RENDEZVOUS to relaying peers
  188. struct _LastUniteKey
  189. {
  190. _LastUniteKey() : x(0),y(0) {}
  191. _LastUniteKey(const Address &a1,const Address &a2)
  192. {
  193. if (a1 > a2) {
  194. x = a2.toInt();
  195. y = a1.toInt();
  196. } else {
  197. x = a1.toInt();
  198. y = a2.toInt();
  199. }
  200. }
  201. inline unsigned long hashCode() const throw() { return ((unsigned long)x ^ (unsigned long)y); }
  202. inline bool operator==(const _LastUniteKey &k) const throw() { return ((x == k.x)&&(y == k.y)); }
  203. uint64_t x,y;
  204. };
  205. Hashtable< _LastUniteKey,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  206. Mutex _lastUniteAttempt_m;
  207. // Active attempts to contact remote peers, including state of multi-phase NAT traversal
  208. struct ContactQueueEntry
  209. {
  210. ContactQueueEntry() {}
  211. ContactQueueEntry(const SharedPtr<Peer> &p,uint64_t ft,const InetAddress &laddr,const InetAddress &a) :
  212. peer(p),
  213. fireAtTime(ft),
  214. inaddr(a),
  215. localAddr(laddr),
  216. strategyIteration(0) {}
  217. SharedPtr<Peer> peer;
  218. uint64_t fireAtTime;
  219. InetAddress inaddr;
  220. InetAddress localAddr;
  221. unsigned int strategyIteration;
  222. };
  223. std::list<ContactQueueEntry> _contactQueue;
  224. Mutex _contactQueue_m;
  225. };
  226. } // namespace ZeroTier
  227. #endif