Switch.hpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_N_SWITCH_HPP
  28. #define ZT_N_SWITCH_HPP
  29. #include <map>
  30. #include <set>
  31. #include <vector>
  32. #include <list>
  33. #include "Constants.hpp"
  34. #include "Mutex.hpp"
  35. #include "MAC.hpp"
  36. #include "NonCopyable.hpp"
  37. #include "Packet.hpp"
  38. #include "Utils.hpp"
  39. #include "InetAddress.hpp"
  40. #include "Topology.hpp"
  41. #include "Array.hpp"
  42. #include "Network.hpp"
  43. #include "SharedPtr.hpp"
  44. #include "IncomingPacket.hpp"
  45. #include "Hashtable.hpp"
  46. /* Ethernet frame types that might be relevant to us */
  47. #define ZT_ETHERTYPE_IPV4 0x0800
  48. #define ZT_ETHERTYPE_ARP 0x0806
  49. #define ZT_ETHERTYPE_RARP 0x8035
  50. #define ZT_ETHERTYPE_ATALK 0x809b
  51. #define ZT_ETHERTYPE_AARP 0x80f3
  52. #define ZT_ETHERTYPE_IPX_A 0x8137
  53. #define ZT_ETHERTYPE_IPX_B 0x8138
  54. #define ZT_ETHERTYPE_IPV6 0x86dd
  55. namespace ZeroTier {
  56. class RuntimeEnvironment;
  57. class Peer;
  58. /**
  59. * Core of the distributed Ethernet switch and protocol implementation
  60. *
  61. * This class is perhaps a bit misnamed, but it's basically where everything
  62. * meets. Transport-layer ZT packets come in here, as do virtual network
  63. * packets from tap devices, and this sends them where they need to go and
  64. * wraps/unwraps accordingly. It also handles queues and timeouts and such.
  65. */
  66. class Switch : NonCopyable
  67. {
  68. public:
  69. Switch(const RuntimeEnvironment *renv);
  70. ~Switch();
  71. /**
  72. * Called when a packet is received from the real network
  73. *
  74. * @param localAddr Local interface address
  75. * @param fromAddr Internet IP address of origin
  76. * @param data Packet data
  77. * @param len Packet length
  78. */
  79. void onRemotePacket(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  80. /**
  81. * Called when a packet comes from a local Ethernet tap
  82. *
  83. * @param network Which network's TAP did this packet come from?
  84. * @param from Originating MAC address
  85. * @param to Destination MAC address
  86. * @param etherType Ethernet packet type
  87. * @param vlanId VLAN ID or 0 if none
  88. * @param data Ethernet payload
  89. * @param len Frame length
  90. */
  91. void onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,unsigned int vlanId,const void *data,unsigned int len);
  92. /**
  93. * Send a packet to a ZeroTier address (destination in packet)
  94. *
  95. * The packet must be fully composed with source and destination but not
  96. * yet encrypted. If the destination peer is known the packet
  97. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  98. *
  99. * The packet may be compressed. Compression isn't done here.
  100. *
  101. * Needless to say, the packet's source must be this node. Otherwise it
  102. * won't be encrypted right. (This is not used for relaying.)
  103. *
  104. * The network ID should only be specified for frames and other actual
  105. * network traffic. Other traffic such as controller requests and regular
  106. * protocol messages should specify zero.
  107. *
  108. * @param packet Packet to send
  109. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  110. * @param nwid Related network ID or 0 if message is not in-network traffic
  111. */
  112. void send(const Packet &packet,bool encrypt,uint64_t nwid);
  113. /**
  114. * Send RENDEZVOUS to two peers to permit them to directly connect
  115. *
  116. * This only works if both peers are known, with known working direct
  117. * links to this peer. The best link for each peer is sent to the other.
  118. *
  119. * @param p1 One of two peers (order doesn't matter)
  120. * @param p2 Second of pair
  121. */
  122. bool unite(const Address &p1,const Address &p2);
  123. /**
  124. * Attempt NAT traversal to peer at a given physical address
  125. *
  126. * @param peer Peer to contact
  127. * @param localAddr Local interface address
  128. * @param atAddr Address of peer
  129. */
  130. void rendezvous(const SharedPtr<Peer> &peer,const InetAddress &localAddr,const InetAddress &atAddr);
  131. /**
  132. * Request WHOIS on a given address
  133. *
  134. * @param addr Address to look up
  135. */
  136. void requestWhois(const Address &addr);
  137. /**
  138. * Cancel WHOIS for an address
  139. *
  140. * @param addr Address to cancel
  141. */
  142. void cancelWhoisRequest(const Address &addr);
  143. /**
  144. * Run any processes that are waiting for this peer's identity
  145. *
  146. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  147. *
  148. * @param peer New peer
  149. */
  150. void doAnythingWaitingForPeer(const SharedPtr<Peer> &peer);
  151. /**
  152. * Perform retries and other periodic timer tasks
  153. *
  154. * This can return a very long delay if there are no pending timer
  155. * tasks. The caller should cap this comparatively vs. other values.
  156. *
  157. * @param now Current time
  158. * @return Number of milliseconds until doTimerTasks() should be run again
  159. */
  160. unsigned long doTimerTasks(uint64_t now);
  161. private:
  162. void _handleRemotePacketFragment(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  163. void _handleRemotePacketHead(const InetAddress &localAddr,const InetAddress &fromAddr,const void *data,unsigned int len);
  164. Address _sendWhoisRequest(const Address &addr,const Address *peersAlreadyConsulted,unsigned int numPeersAlreadyConsulted);
  165. bool _trySend(const Packet &packet,bool encrypt,uint64_t nwid);
  166. bool _shouldTryUnite(const uint64_t now,const Address &p1,const Address &p2);
  167. const RuntimeEnvironment *const RR;
  168. uint64_t _lastBeaconResponse;
  169. // Outsanding WHOIS requests and how many retries they've undergone
  170. struct WhoisRequest
  171. {
  172. WhoisRequest() : lastSent(0),retries(0) {}
  173. uint64_t lastSent;
  174. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  175. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  176. };
  177. Hashtable< Address,WhoisRequest > _outstandingWhoisRequests;
  178. Mutex _outstandingWhoisRequests_m;
  179. // Packet defragmentation queue -- comes before RX queue in path
  180. struct DefragQueueEntry
  181. {
  182. DefragQueueEntry() : creationTime(0),totalFragments(0),haveFragments(0) {}
  183. uint64_t creationTime;
  184. SharedPtr<IncomingPacket> frag0;
  185. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1];
  186. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  187. uint32_t haveFragments; // bit mask, LSB to MSB
  188. };
  189. Hashtable< uint64_t,DefragQueueEntry > _defragQueue;
  190. Mutex _defragQueue_m;
  191. // ZeroTier-layer RX queue of incoming packets in the process of being decoded
  192. std::list< SharedPtr<IncomingPacket> > _rxQueue;
  193. Mutex _rxQueue_m;
  194. // ZeroTier-layer TX queue entry
  195. struct TXQueueEntry
  196. {
  197. TXQueueEntry() {}
  198. TXQueueEntry(Address d,uint64_t ct,const Packet &p,bool enc,uint64_t nw) :
  199. dest(d),
  200. creationTime(ct),
  201. nwid(nw),
  202. packet(p),
  203. encrypt(enc) {}
  204. Address dest;
  205. uint64_t creationTime;
  206. uint64_t nwid;
  207. Packet packet; // unencrypted/unMAC'd packet -- this is done at send time
  208. bool encrypt;
  209. };
  210. std::list< TXQueueEntry > _txQueue;
  211. Mutex _txQueue_m;
  212. // Tracks sending of VERB_RENDEZVOUS to relaying peers
  213. struct _LastUniteKey
  214. {
  215. _LastUniteKey() : x(0),y(0) {}
  216. _LastUniteKey(const Address &a1,const Address &a2)
  217. {
  218. if (a1 > a2) {
  219. x = a2.toInt();
  220. y = a1.toInt();
  221. } else {
  222. x = a1.toInt();
  223. y = a2.toInt();
  224. }
  225. }
  226. inline unsigned long hashCode() const throw() { return ((unsigned long)x ^ (unsigned long)y); }
  227. inline bool operator==(const _LastUniteKey &k) const throw() { return ((x == k.x)&&(y == k.y)); }
  228. uint64_t x,y;
  229. };
  230. Hashtable< _LastUniteKey,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  231. Mutex _lastUniteAttempt_m;
  232. // Active attempts to contact remote peers, including state of multi-phase NAT traversal
  233. struct ContactQueueEntry
  234. {
  235. ContactQueueEntry() {}
  236. ContactQueueEntry(const SharedPtr<Peer> &p,uint64_t ft,const InetAddress &laddr,const InetAddress &a) :
  237. peer(p),
  238. fireAtTime(ft),
  239. inaddr(a),
  240. localAddr(laddr),
  241. strategyIteration(0) {}
  242. SharedPtr<Peer> peer;
  243. uint64_t fireAtTime;
  244. InetAddress inaddr;
  245. InetAddress localAddr;
  246. unsigned int strategyIteration;
  247. };
  248. std::list<ContactQueueEntry> _contactQueue;
  249. Mutex _contactQueue_m;
  250. };
  251. } // namespace ZeroTier
  252. #endif