Switch.hpp 8.5 KB

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