Switch.hpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 "Mutex.hpp"
  33. #include "MAC.hpp"
  34. #include "NonCopyable.hpp"
  35. #include "Constants.hpp"
  36. #include "Packet.hpp"
  37. #include "Utils.hpp"
  38. #include "InetAddress.hpp"
  39. #include "Topology.hpp"
  40. #include "Array.hpp"
  41. #include "Network.hpp"
  42. #include "SharedPtr.hpp"
  43. #include "Demarc.hpp"
  44. #include "Multicaster.hpp"
  45. #include "PacketDecoder.hpp"
  46. namespace ZeroTier {
  47. class RuntimeEnvironment;
  48. class EthernetTap;
  49. class Logger;
  50. class Node;
  51. class Peer;
  52. /**
  53. * Core of the distributed Ethernet switch and protocol implementation
  54. */
  55. class Switch : NonCopyable
  56. {
  57. public:
  58. Switch(const RuntimeEnvironment *renv);
  59. ~Switch();
  60. /**
  61. * Called when a packet is received from the real network
  62. *
  63. * @param localPort Local port on which packet was received
  64. * @param fromAddr Internet IP address of origin
  65. * @param data Packet data
  66. */
  67. void onRemotePacket(Demarc::Port localPort,const InetAddress &fromAddr,const Buffer<4096> &data);
  68. /**
  69. * Called when a packet comes from a local Ethernet tap
  70. *
  71. * @param network Which network's TAP did this packet come from?
  72. * @param from Originating MAC address
  73. * @param to Destination MAC address
  74. * @param etherType Ethernet packet type
  75. * @param data Ethernet payload
  76. */
  77. void onLocalEthernet(const SharedPtr<Network> &network,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  78. /**
  79. * Send a packet to a ZeroTier address (destination in packet)
  80. *
  81. * The packet must be fully composed with source and destination but not
  82. * yet encrypted. If the destination peer is known the packet
  83. * is sent immediately. Otherwise it is queued and a WHOIS is dispatched.
  84. *
  85. * The packet may be compressed. Compression isn't done here.
  86. *
  87. * Needless to say, the packet's source must be this node. Otherwise it
  88. * won't be encrypted right. (This is not used for relaying.)
  89. *
  90. * @param packet Packet to send
  91. * @param encrypt Encrypt packet payload? (always true except for HELLO)
  92. */
  93. void send(const Packet &packet,bool encrypt);
  94. /**
  95. * Send a HELLO announcement
  96. *
  97. * @param dest Address of destination
  98. */
  99. void sendHELLO(const Address &dest);
  100. /**
  101. * Send a HELLO announcement immediately to the indicated address
  102. *
  103. * @param localPort Originating local port or ANY_PORT to pick
  104. * @param addr IP address to send to
  105. * @param dest Destination peer
  106. * @return True if send appears successful
  107. */
  108. bool sendHELLO(const SharedPtr<Peer> &dest,Demarc::Port localPort,const InetAddress &addr);
  109. /**
  110. * Send RENDEZVOUS to two peers to permit them to directly connect
  111. *
  112. * This only works if both peers are known, with known working direct
  113. * links to this peer. The best link for each peer is sent to the other.
  114. *
  115. * A rate limiter is in effect via the _lastUniteAttempt map. If force
  116. * is true, a unite attempt is made even if one has been made less than
  117. * ZT_MIN_UNITE_INTERVAL milliseconds ago.
  118. *
  119. * @param p1 One of two peers (order doesn't matter)
  120. * @param p2 Second of pair
  121. * @param force If true, send now regardless of interval
  122. */
  123. bool unite(const Address &p1,const Address &p2,bool force);
  124. /**
  125. * Perform retries and other periodic timer tasks
  126. *
  127. * @return Number of milliseconds until doTimerTasks() should be run again
  128. */
  129. unsigned long doTimerTasks();
  130. /**
  131. * Announce multicast group memberships
  132. *
  133. * This efficiently announces memberships, sending single packets with
  134. * many LIKEs.
  135. *
  136. * @param allMemberships Memberships for a number of networks
  137. */
  138. void announceMulticastGroups(const std::map< SharedPtr<Network>,std::set<MulticastGroup> > &allMemberships);
  139. /**
  140. * Request WHOIS on a given address
  141. *
  142. * @param addr Address to look up
  143. */
  144. void requestWhois(const Address &addr);
  145. private:
  146. struct _CBaddPeerFromHello_Data
  147. {
  148. Switch *parent;
  149. Address source;
  150. InetAddress fromAddr;
  151. int localPort;
  152. unsigned int vMajor,vMinor,vRevision;
  153. uint64_t helloPacketId;
  154. uint64_t helloTimestamp;
  155. };
  156. static void _CBaddPeerFromHello(
  157. void *arg, // _CBaddPeerFromHello_Data
  158. const SharedPtr<Peer> &p,
  159. Topology::PeerVerifyResult result);
  160. static void _CBaddPeerFromWhois(
  161. void *arg, // this (Switch)
  162. const SharedPtr<Peer> &p,
  163. Topology::PeerVerifyResult result);
  164. void _finishWhoisRequest(
  165. const SharedPtr<Peer> &peer);
  166. void _handleRemotePacketFragment(
  167. Demarc::Port localPort,
  168. const InetAddress &fromAddr,
  169. const Buffer<4096> &data);
  170. void _handleRemotePacketHead(
  171. Demarc::Port localPort,
  172. const InetAddress &fromAddr,
  173. const Buffer<4096> &data);
  174. Address _sendWhoisRequest(
  175. const Address &addr,
  176. const Address *peersAlreadyConsulted,
  177. unsigned int numPeersAlreadyConsulted);
  178. bool _trySend(
  179. const Packet &packet,
  180. bool encrypt);
  181. const RuntimeEnvironment *const _r;
  182. Multicaster _multicaster;
  183. struct WhoisRequest
  184. {
  185. uint64_t lastSent;
  186. Address peersConsulted[ZT_MAX_WHOIS_RETRIES]; // by retry
  187. unsigned int retries; // 0..ZT_MAX_WHOIS_RETRIES
  188. };
  189. std::map< Address,WhoisRequest > _outstandingWhoisRequests;
  190. Mutex _outstandingWhoisRequests_m;
  191. std::multimap< Address,SharedPtr<PacketDecoder> > _rxQueue;
  192. Mutex _rxQueue_m;
  193. struct TXQueueEntry
  194. {
  195. TXQueueEntry() {}
  196. TXQueueEntry(uint64_t ct,const Packet &p,bool enc) :
  197. creationTime(ct),
  198. packet(p),
  199. encrypt(enc) {}
  200. uint64_t creationTime;
  201. Packet packet; // unencrypted/untagged for TX queue
  202. bool encrypt;
  203. };
  204. std::multimap< Address,TXQueueEntry > _txQueue;
  205. Mutex _txQueue_m;
  206. struct DefragQueueEntry
  207. {
  208. uint64_t creationTime;
  209. SharedPtr<PacketDecoder> frag0;
  210. Packet::Fragment frags[ZT_MAX_PACKET_FRAGMENTS - 1];
  211. unsigned int totalFragments; // 0 if only frag0 received, waiting for frags
  212. uint32_t haveFragments; // bit mask, LSB to MSB
  213. };
  214. std::map< uint64_t,DefragQueueEntry > _defragQueue;
  215. Mutex _defragQueue_m;
  216. std::map< Array< Address,2 >,uint64_t > _lastUniteAttempt; // key is always sorted in ascending order, for set-like behavior
  217. Mutex _lastUniteAttempt_m;
  218. struct RendezvousQueueEntry
  219. {
  220. InetAddress inaddr;
  221. uint64_t fireAtTime;
  222. Demarc::Port localPort;
  223. };
  224. std::map< Address,RendezvousQueueEntry > _rendezvousQueue;
  225. Mutex _rendezvousQueue_m;
  226. };
  227. } // namespace ZeroTier
  228. #endif