Switch.hpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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 "Demarc.hpp"
  45. #include "Multicaster.hpp"
  46. #include "PacketDecoder.hpp"
  47. /* Ethernet frame types that might be relevant to us */
  48. #define ZT_ETHERTYPE_IPV4 0x0800
  49. #define ZT_ETHERTYPE_ARP 0x0806
  50. #define ZT_ETHERTYPE_RARP 0x8035
  51. #define ZT_ETHERTYPE_ATALK 0x809b
  52. #define ZT_ETHERTYPE_AARP 0x80f3
  53. #define ZT_ETHERTYPE_IPX_A 0x8137
  54. #define ZT_ETHERTYPE_IPX_B 0x8138
  55. #define ZT_ETHERTYPE_IPV6 0x86dd
  56. namespace ZeroTier {
  57. class RuntimeEnvironment;
  58. class EthernetTap;
  59. class Logger;
  60. class Node;
  61. class Peer;
  62. /**
  63. * Core of the distributed Ethernet switch and protocol implementation
  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 localPort Local port on which packet was received
  74. * @param fromAddr Internet IP address of origin
  75. * @param data Packet data
  76. */
  77. void onRemotePacket(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data);
  78. /**
  79. * Called when a packet comes from a local Ethernet tap
  80. *
  81. * @param network Which network's TAP did this packet come from?
  82. * @param from Originating MAC address
  83. * @param to Destination MAC address
  84. * @param etherType Ethernet packet type
  85. * @param data Ethernet payload
  86. */
  87. void onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  88. /**
  89. * Send a packet to a ZeroTier address (destination in packet)
  90. *
  91. * The packet must be fully composed with source and destination but not
  92. * yet encrypted. If the destination peer is known the packet
  93. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  94. *
  95. * The packet may be compressed. Compression isn't done here.
  96. *
  97. * Needless to say, the packet's source must be this node. Otherwise it
  98. * won't be encrypted right. (This is not used for relaying.)
  99. *
  100. * @param packet Packet to send
  101. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  102. */
  103. void send(const Packet &packet,bool encrypt);
  104. /**
  105. * Send a HELLO announcement
  106. *
  107. * @param dest Address of destination
  108. */
  109. void sendHELLO(const Address &dest);
  110. /**
  111. * Send a HELLO announcement immediately to the indicated address
  112. *
  113. * @param localPort Originating local port or ANY_PORT to pick
  114. * @param remoteAddr IP address to send to
  115. * @param dest Destination peer
  116. * @return True if send appears successful
  117. */
  118. bool sendHELLO(const SharedPtr<Peer> &dest,Demarc::Port localPort,const InetAddress &remoteAddr);
  119. /**
  120. * Send a PROBE immediately to the indicated address
  121. *
  122. * @param localPort Originating local port or ANY_PORT to pick
  123. * @param remoteAddr IP address to send to
  124. * @param dest Destination peer
  125. * @return True if send appears successful
  126. */
  127. bool sendPROBE(const SharedPtr<Peer> &dest,Demarc::Port localPort,const InetAddress &remoteAddr);
  128. /**
  129. * Send RENDEZVOUS to two peers to permit them to directly connect
  130. *
  131. * This only works if both peers are known, with known working direct
  132. * links to this peer. The best link for each peer is sent to the other.
  133. *
  134. * A rate limiter is in effect via the _lastUniteAttempt map. If force
  135. * is true, a unite attempt is made even if one has been made less than
  136. * ZT_MIN_UNITE_INTERVAL milliseconds ago.
  137. *
  138. * @param p1 One of two peers (order doesn't matter)
  139. * @param p2 Second of pair
  140. * @param force If true, send now regardless of interval
  141. */
  142. bool unite(const Address &p1,const Address &p2,bool force);
  143. /**
  144. * Send NAT traversal messages to peer at the given candidate address
  145. *
  146. * @param peer Peer to contact
  147. * @param atAddr Address of peer
  148. */
  149. void contact(const SharedPtr<Peer> &peer,const InetAddress &atAddr);
  150. /**
  151. * Perform retries and other periodic timer tasks
  152. *
  153. * @return Number of milliseconds until doTimerTasks() should be run again
  154. */
  155. unsigned long doTimerTasks();
  156. /**
  157. * Announce multicast group memberships
  158. *
  159. * This announces all the groups for all the networks in the supplied map to
  160. * all peers with whom we have an active direct link. Only isAllowed() peers
  161. * and supernodes get announcements for each given network.
  162. *
  163. * @param allMemberships Memberships for a number of networks
  164. */
  165. void announceMulticastGroups(const std::map< SharedPtr<Network>,std::set<MulticastGroup> > &allMemberships);
  166. /**
  167. * Announce multicast group memberships
  168. *
  169. * This announces all current multicast memberships to a single peer. Only
  170. * memberships for networks where the peer isAllowed() are included, unless
  171. * the peer is a supernode.
  172. *
  173. * @param peer Peer to announce all memberships to
  174. */
  175. void announceMulticastGroups(const SharedPtr<Peer> &peer);
  176. /**
  177. * Request WHOIS on a given address
  178. *
  179. * @param addr Address to look up
  180. */
  181. void requestWhois(const Address &addr);
  182. /**
  183. * Cancel WHOIS for an address
  184. *
  185. * @param addr Address to cancel
  186. */
  187. void cancelWhoisRequest(const Address &addr);
  188. /**
  189. * Run any processes that are waiting for this peer
  190. *
  191. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  192. *
  193. * @param peer New peer
  194. */
  195. void doAnythingWaitingForPeer(const SharedPtr<Peer> &peer);
  196. /**
  197. * @param etherType Ethernet type ID
  198. * @return Human-readable name
  199. */
  200. static const char *etherTypeName(const unsigned int etherType)
  201. throw();
  202. private:
  203. void _handleRemotePacketFragment(
  204. Demarc::Port localPort,
  205. const InetAddress &fromAddr,
  206. const Buffer<4096> &data);
  207. void _handleRemotePacketHead(
  208. Demarc::Port localPort,
  209. const InetAddress &fromAddr,
  210. const Buffer<4096> &data);
  211. Address _sendWhoisRequest(
  212. const Address &addr,
  213. const Address *peersAlreadyConsulted,
  214. unsigned int numPeersAlreadyConsulted);
  215. bool _trySend(
  216. const Packet &packet,
  217. bool encrypt);
  218. const RuntimeEnvironment *const _r;
  219. volatile unsigned int _multicastIdCounter;
  220. struct WhoisRequest
  221. {
  222. uint64_t lastSent;
  223. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  224. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  225. };
  226. std::map< Address,WhoisRequest > _outstandingWhoisRequests;
  227. Mutex _outstandingWhoisRequests_m;
  228. std::list< SharedPtr<PacketDecoder> > _rxQueue;
  229. Mutex _rxQueue_m;
  230. struct TXQueueEntry
  231. {
  232. TXQueueEntry() {}
  233. TXQueueEntry(uint64_t ct,const Packet &p,bool enc) :
  234. creationTime(ct),
  235. packet(p),
  236. encrypt(enc) {}
  237. uint64_t creationTime;
  238. Packet packet; // unencrypted/untagged for TX queue
  239. bool encrypt;
  240. };
  241. std::multimap< Address,TXQueueEntry > _txQueue;
  242. Mutex _txQueue_m;
  243. struct DefragQueueEntry
  244. {
  245. uint64_t creationTime;
  246. SharedPtr<PacketDecoder> frag0;
  247. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1];
  248. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  249. uint32_t haveFragments; // bit mask, LSB to MSB
  250. };
  251. std::map< uint64_t,DefragQueueEntry > _defragQueue;
  252. Mutex _defragQueue_m;
  253. std::map< Array< Address,2 >,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  254. Mutex _lastUniteAttempt_m;
  255. struct ContactQueueEntry
  256. {
  257. ContactQueueEntry() {}
  258. ContactQueueEntry(const SharedPtr<Peer> &p,uint64_t ft,Demarc::Port lp,const InetAddress &a) :
  259. peer(p),
  260. fireAtTime(ft),
  261. localPort(lp),
  262. inaddr(a) {}
  263. SharedPtr<Peer> peer;
  264. uint64_t fireAtTime;
  265. Demarc::Port localPort;
  266. InetAddress inaddr;
  267. };
  268. std::list<ContactQueueEntry> _contactQueue;
  269. Mutex _contactQueue_m;
  270. };
  271. } // namespace ZeroTier
  272. #endif