Switch.hpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 RENDEZVOUS to two peers to permit them to directly connect
  121. *
  122. * This only works if both peers are known, with known working direct
  123. * links to this peer. The best link for each peer is sent to the other.
  124. *
  125. * A rate limiter is in effect via the _lastUniteAttempt map. If force
  126. * is true, a unite attempt is made even if one has been made less than
  127. * ZT_MIN_UNITE_INTERVAL milliseconds ago.
  128. *
  129. * @param p1 One of two peers (order doesn't matter)
  130. * @param p2 Second of pair
  131. * @param force If true, send now regardless of interval
  132. */
  133. bool unite(const Address &p1,const Address &p2,bool force);
  134. /**
  135. * Send NAT traversal messages to peer at the given candidate address
  136. *
  137. * @param peer Peer to contact
  138. * @param atAddr Address of peer
  139. */
  140. void contact(const SharedPtr<Peer> &peer,const InetAddress &atAddr);
  141. /**
  142. * Perform retries and other periodic timer tasks
  143. *
  144. * @return Number of milliseconds until doTimerTasks() should be run again
  145. */
  146. unsigned long doTimerTasks();
  147. /**
  148. * Announce multicast group memberships
  149. *
  150. * This announces all the groups for all the networks in the supplied map to
  151. * all peers with whom we have an active direct link. Only isAllowed() peers
  152. * and supernodes get announcements for each given network.
  153. *
  154. * @param allMemberships Memberships for a number of networks
  155. */
  156. void announceMulticastGroups(const std::map< SharedPtr<Network>,std::set<MulticastGroup> > &allMemberships);
  157. /**
  158. * Announce multicast group memberships
  159. *
  160. * This announces all current multicast memberships to a single peer. Only
  161. * memberships for networks where the peer isAllowed() are included, unless
  162. * the peer is a supernode.
  163. *
  164. * @param peer Peer to announce all memberships to
  165. */
  166. void announceMulticastGroups(const SharedPtr<Peer> &peer);
  167. /**
  168. * Request WHOIS on a given address
  169. *
  170. * @param addr Address to look up
  171. */
  172. void requestWhois(const Address &addr);
  173. /**
  174. * Cancel WHOIS for an address
  175. *
  176. * @param addr Address to cancel
  177. */
  178. void cancelWhoisRequest(const Address &addr);
  179. /**
  180. * Run any processes that are waiting for this peer
  181. *
  182. * Called when we learn of a peer's identity from HELLO, OK(WHOIS), etc.
  183. *
  184. * @param peer New peer
  185. */
  186. void doAnythingWaitingForPeer(const SharedPtr<Peer> &peer);
  187. /**
  188. * @param etherType Ethernet type ID
  189. * @return Human-readable name
  190. */
  191. static const char *etherTypeName(const unsigned int etherType)
  192. throw();
  193. private:
  194. void _handleRemotePacketFragment(
  195. Demarc::Port localPort,
  196. const InetAddress &fromAddr,
  197. const Buffer<4096> &data);
  198. void _handleRemotePacketHead(
  199. Demarc::Port localPort,
  200. const InetAddress &fromAddr,
  201. const Buffer<4096> &data);
  202. Address _sendWhoisRequest(
  203. const Address &addr,
  204. const Address *peersAlreadyConsulted,
  205. unsigned int numPeersAlreadyConsulted);
  206. bool _trySend(
  207. const Packet &packet,
  208. bool encrypt);
  209. const RuntimeEnvironment *const _r;
  210. volatile unsigned int _multicastIdCounter;
  211. struct WhoisRequest
  212. {
  213. uint64_t lastSent;
  214. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  215. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  216. };
  217. std::map< Address,WhoisRequest > _outstandingWhoisRequests;
  218. Mutex _outstandingWhoisRequests_m;
  219. std::list< SharedPtr<PacketDecoder> > _rxQueue;
  220. Mutex _rxQueue_m;
  221. struct TXQueueEntry
  222. {
  223. TXQueueEntry() {}
  224. TXQueueEntry(uint64_t ct,const Packet &p,bool enc) :
  225. creationTime(ct),
  226. packet(p),
  227. encrypt(enc) {}
  228. uint64_t creationTime;
  229. Packet packet; // unencrypted/untagged for TX queue
  230. bool encrypt;
  231. };
  232. std::multimap< Address,TXQueueEntry > _txQueue;
  233. Mutex _txQueue_m;
  234. struct DefragQueueEntry
  235. {
  236. uint64_t creationTime;
  237. SharedPtr<PacketDecoder> frag0;
  238. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1];
  239. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  240. uint32_t haveFragments; // bit mask, LSB to MSB
  241. };
  242. std::map< uint64_t,DefragQueueEntry > _defragQueue;
  243. Mutex _defragQueue_m;
  244. std::map< Array< Address,2 >,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  245. Mutex _lastUniteAttempt_m;
  246. struct ContactQueueEntry
  247. {
  248. ContactQueueEntry() {}
  249. ContactQueueEntry(const SharedPtr<Peer> &p,uint64_t ft,Demarc::Port lp,const InetAddress &a) :
  250. peer(p),
  251. fireAtTime(ft),
  252. localPort(lp),
  253. inaddr(a) {}
  254. SharedPtr<Peer> peer;
  255. uint64_t fireAtTime;
  256. Demarc::Port localPort;
  257. InetAddress inaddr;
  258. };
  259. std::list<ContactQueueEntry> _contactQueue;
  260. Mutex _contactQueue_m;
  261. };
  262. } // namespace ZeroTier
  263. #endif