2
0

Switch.hpp 7.3 KB

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