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