Switch.hpp 7.5 KB

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