Switch.hpp 8.5 KB

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