Switch.hpp 8.4 KB

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