Peer.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_PEER_HPP
  14. #define ZT_PEER_HPP
  15. #include <vector>
  16. #include "Constants.hpp"
  17. #include "RuntimeEnvironment.hpp"
  18. #include "Node.hpp"
  19. #include "Path.hpp"
  20. #include "Address.hpp"
  21. #include "Utils.hpp"
  22. #include "Identity.hpp"
  23. #include "InetAddress.hpp"
  24. #include "Packet.hpp"
  25. #include "SharedPtr.hpp"
  26. #include "AtomicCounter.hpp"
  27. #include "Hashtable.hpp"
  28. #include "Mutex.hpp"
  29. #define ZT_PEER_MAX_SERIALIZED_STATE_SIZE (sizeof(Peer) + 32 + (sizeof(Path) * 2))
  30. namespace ZeroTier {
  31. /**
  32. * Peer on P2P Network (virtual layer 1)
  33. */
  34. class Peer
  35. {
  36. friend class SharedPtr<Peer>;
  37. private:
  38. inline Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  39. public:
  40. inline ~Peer() { Utils::burn(_key,sizeof(_key)); }
  41. /**
  42. * Construct a new peer
  43. *
  44. * @param renv Runtime environment
  45. * @param myIdentity Identity of THIS node (for key agreement)
  46. * @param peerIdentity Identity of peer
  47. * @throws std::runtime_error Key agreement with peer's identity failed
  48. */
  49. Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity);
  50. /**
  51. * @return This peer's ZT address (short for identity().address())
  52. */
  53. ZT_ALWAYS_INLINE const Address &address() const { return _id.address(); }
  54. /**
  55. * @return This peer's identity
  56. */
  57. ZT_ALWAYS_INLINE const Identity &identity() const { return _id; }
  58. /**
  59. * Log receipt of an authenticated packet
  60. *
  61. * This is called by the decode pipe when a packet is proven to be authentic
  62. * and appears to be valid.
  63. *
  64. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  65. * @param path Path over which packet was received
  66. * @param hops ZeroTier (not IP) hops
  67. * @param packetId Packet ID
  68. * @param verb Packet verb
  69. * @param inRePacketId Packet ID in reply to (default: none)
  70. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  71. * @param networkId Network ID if this packet is related to a network, 0 otherwise
  72. */
  73. void received(
  74. void *tPtr,
  75. const SharedPtr<Path> &path,
  76. const unsigned int hops,
  77. const uint64_t packetId,
  78. const unsigned int payloadLength,
  79. const Packet::Verb verb,
  80. const uint64_t inRePacketId,
  81. const Packet::Verb inReVerb,
  82. const uint64_t networkId);
  83. /**
  84. * Check whether we have an active path to this peer via the given address
  85. *
  86. * @param now Current time
  87. * @param addr Remote address
  88. * @return True if we have an active path to this destination
  89. */
  90. inline bool hasActivePathTo(int64_t now,const InetAddress &addr) const
  91. {
  92. Mutex::Lock _l(_paths_m);
  93. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  94. if (_paths[i]) {
  95. if ((_paths[i]->address() == addr)&&(_paths[i]->alive(now)))
  96. return true;
  97. } else break;
  98. }
  99. return false;
  100. }
  101. /**
  102. * Send via best direct path
  103. *
  104. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  105. * @param data Packet data
  106. * @param len Packet length
  107. * @param now Current time
  108. * @param force If true, send even if path is not alive
  109. * @return True if we actually sent something
  110. */
  111. ZT_ALWAYS_INLINE bool sendDirect(void *tPtr,const void *data,unsigned int len,int64_t now,bool force)
  112. {
  113. SharedPtr<Path> bp(getAppropriatePath(now,force));
  114. if (bp)
  115. return bp->send(RR,tPtr,data,len,now);
  116. return false;
  117. }
  118. /**
  119. * Record statistics on outgoing packets
  120. *
  121. * @param path Path over which packet was sent
  122. * @param id Packet ID
  123. * @param len Length of packet payload
  124. * @param verb Packet verb
  125. * @param now Current time
  126. */
  127. void recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId, uint16_t payloadLength, const Packet::Verb verb, int64_t now);
  128. /**
  129. * Record statistics on incoming packets
  130. *
  131. * @param path Path over which packet was sent
  132. * @param id Packet ID
  133. * @param len Length of packet payload
  134. * @param verb Packet verb
  135. * @param now Current time
  136. */
  137. void recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId, uint16_t payloadLength, const Packet::Verb verb, int64_t now);
  138. /**
  139. * Send an ACK to peer for the most recent packets received
  140. *
  141. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  142. * @param localSocket Raw socket the ACK packet will be sent over
  143. * @param atAddress Destination for the ACK packet
  144. * @param now Current time
  145. */
  146. void sendACK(void *tPtr, const SharedPtr<Path> &path, const int64_t localSocket,const InetAddress &atAddress,int64_t now);
  147. /**
  148. * Send a QoS packet to peer so that it can evaluate the quality of this link
  149. *
  150. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  151. * @param localSocket Raw socket the QoS packet will be sent over
  152. * @param atAddress Destination for the QoS packet
  153. * @param now Current time
  154. */
  155. void sendQOS_MEASUREMENT(void *tPtr, const SharedPtr<Path> &path, const int64_t localSocket,const InetAddress &atAddress,int64_t now);
  156. /**
  157. * Compute relative quality values and allocations for the components of the aggregate link
  158. *
  159. * @param now Current time
  160. */
  161. void computeAggregateProportionalAllocation(int64_t now);
  162. /**
  163. * @return The aggregate link Packet Delay Variance (PDV)
  164. */
  165. int computeAggregateLinkPacketDelayVariance();
  166. /**
  167. * @return The aggregate link mean latency
  168. */
  169. int computeAggregateLinkMeanLatency();
  170. /**
  171. * @return The number of currently alive "physical" paths in the aggregate link
  172. */
  173. int aggregateLinkPhysicalPathCount();
  174. /**
  175. * @return The number of currently alive "logical" paths in the aggregate link
  176. */
  177. int aggregateLinkLogicalPathCount();
  178. /**
  179. * Get the most appropriate direct path based on current multipath and QoS configuration
  180. *
  181. * @param now Current time
  182. * @param includeExpired If true, include even expired paths
  183. * @return Best current path or NULL if none
  184. */
  185. SharedPtr<Path> getAppropriatePath(int64_t now, bool includeExpired);
  186. /**
  187. * Generate a human-readable string of interface names making up the aggregate link, also include
  188. * moving allocation and IP version number for each (for tracing)
  189. */
  190. char *interfaceListStr();
  191. /**
  192. * Send VERB_RENDEZVOUS to this and another peer via the best common IP scope and path
  193. */
  194. void introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const;
  195. /**
  196. * Send a HELLO to this peer at a specified physical address
  197. *
  198. * No statistics or sent times are updated here.
  199. *
  200. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  201. * @param localSocket Local source socket
  202. * @param atAddress Destination address
  203. * @param now Current time
  204. */
  205. void sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now);
  206. /**
  207. * Send pings to active paths
  208. *
  209. * This also cleans up some internal data structures. It's called periodically from Node.
  210. *
  211. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  212. * @param now Current time
  213. * @param v4SendCount Number of IPv4 packets sent (result parameter)
  214. * @param v6SendCount Number of IPv6 packets sent (result parameter)
  215. */
  216. void ping(void *tPtr,int64_t now,unsigned int &v4SendCount,unsigned int &v6SendCount);
  217. /**
  218. * Reset paths within a given IP scope and address family
  219. *
  220. * Resetting a path involves sending an ECHO to it and then deactivating
  221. * it until or unless it responds. This is done when we detect a change
  222. * to our external IP or another system change that might invalidate
  223. * many or all current paths.
  224. *
  225. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  226. * @param scope IP scope
  227. * @param inetAddressFamily Family e.g. AF_INET
  228. * @param now Current time
  229. */
  230. void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now);
  231. /**
  232. * @param now Current time
  233. * @return All known paths to this peer
  234. */
  235. inline std::vector< SharedPtr<Path> > paths(const int64_t now) const
  236. {
  237. std::vector< SharedPtr<Path> > pp;
  238. Mutex::Lock _l(_paths_m);
  239. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  240. if (!_paths[i]) break;
  241. pp.push_back(_paths[i]);
  242. }
  243. return pp;
  244. }
  245. /**
  246. * @return Time of last receive of anything, whether direct or relayed
  247. */
  248. ZT_ALWAYS_INLINE int64_t lastReceive() const { return _lastReceive; }
  249. /**
  250. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  251. */
  252. ZT_ALWAYS_INLINE bool alive(const int64_t now) const { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  253. /**
  254. * @return Latency in milliseconds of best/aggregate path or 0xffff if unknown / no paths
  255. */
  256. ZT_ALWAYS_INLINE unsigned int latency(const int64_t now)
  257. {
  258. if (_canUseMultipath) {
  259. return (int)computeAggregateLinkMeanLatency();
  260. } else {
  261. SharedPtr<Path> bp(getAppropriatePath(now,false));
  262. if (bp)
  263. return bp->latency();
  264. return 0xffff;
  265. }
  266. }
  267. /**
  268. * This computes a quality score for relays and root servers
  269. *
  270. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  271. * receive the worst possible quality (max unsigned int). Otherwise the
  272. * quality is a product of latency and the number of potential missed
  273. * pings. This causes roots and relays to switch over a bit faster if they
  274. * fail.
  275. *
  276. * @return Relay quality score computed from latency and other factors, lower is better
  277. */
  278. ZT_ALWAYS_INLINE unsigned int relayQuality(const int64_t now)
  279. {
  280. const uint64_t tsr = now - _lastReceive;
  281. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  282. return (~(unsigned int)0);
  283. unsigned int l = latency(now);
  284. if (!l)
  285. l = 0xffff;
  286. return (l * (((unsigned int)tsr / (ZT_PEER_PING_PERIOD + 1000)) + 1));
  287. }
  288. /**
  289. * @return 256-bit secret symmetric encryption key
  290. */
  291. ZT_ALWAYS_INLINE const unsigned char *key() const { return _key; }
  292. /**
  293. * Set the currently known remote version of this peer's client
  294. *
  295. * @param vproto Protocol version
  296. * @param vmaj Major version
  297. * @param vmin Minor version
  298. * @param vrev Revision
  299. */
  300. ZT_ALWAYS_INLINE void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  301. {
  302. _vProto = (uint16_t)vproto;
  303. _vMajor = (uint16_t)vmaj;
  304. _vMinor = (uint16_t)vmin;
  305. _vRevision = (uint16_t)vrev;
  306. }
  307. ZT_ALWAYS_INLINE unsigned int remoteVersionProtocol() const { return _vProto; }
  308. ZT_ALWAYS_INLINE unsigned int remoteVersionMajor() const { return _vMajor; }
  309. ZT_ALWAYS_INLINE unsigned int remoteVersionMinor() const { return _vMinor; }
  310. ZT_ALWAYS_INLINE unsigned int remoteVersionRevision() const { return _vRevision; }
  311. ZT_ALWAYS_INLINE bool remoteVersionKnown() const { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  312. /**
  313. * Periodically update known multipath activation constraints. This is done so that we know when and when
  314. * not to use multipath logic. Doing this once every few seconds is sufficient.
  315. *
  316. * @param now Current time
  317. */
  318. void processBackgroundPeerTasks(const int64_t now);
  319. /**
  320. * Record that the remote peer does have multipath enabled. As is evident by the receipt of a VERB_ACK
  321. * or a VERB_QOS_MEASUREMENT packet at some point in the past. Until this flag is set, the local client
  322. * shall assume that multipath is not enabled and should only use classical Protocol 9 logic.
  323. */
  324. inline void inferRemoteMultipathEnabled() { _remotePeerMultipathEnabled = true; }
  325. /**
  326. * @return Whether the local client supports and is configured to use multipath
  327. */
  328. inline bool localMultipathSupport() { return _localMultipathSupported; }
  329. /**
  330. * @return Whether the remote peer supports and is configured to use multipath
  331. */
  332. inline bool remoteMultipathSupport() { return _remoteMultipathSupported; }
  333. /**
  334. * @return Whether this client can use multipath to communicate with this peer. True if both peers are using
  335. * the correct protocol and if both peers have multipath enabled. False if otherwise.
  336. */
  337. inline bool canUseMultipath() { return _canUseMultipath; }
  338. /**
  339. * Rate limit gate for VERB_PUSH_DIRECT_PATHS
  340. */
  341. ZT_ALWAYS_INLINE bool rateGatePushDirectPaths(const int64_t now)
  342. {
  343. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  344. ++_directPathPushCutoffCount;
  345. else _directPathPushCutoffCount = 0;
  346. _lastDirectPathPushReceive = now;
  347. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  348. }
  349. /**
  350. * Rate limit gate for VERB_NETWORK_CREDENTIALS
  351. */
  352. ZT_ALWAYS_INLINE bool rateGateCredentialsReceived(const int64_t now)
  353. {
  354. if ((now - _lastCredentialsReceived) <= ZT_PEER_CREDENTIALS_CUTOFF_TIME)
  355. ++_credentialsCutoffCount;
  356. else _credentialsCutoffCount = 0;
  357. _lastCredentialsReceived = now;
  358. return (_directPathPushCutoffCount < ZT_PEER_CREDEITIALS_CUTOFF_LIMIT);
  359. }
  360. /**
  361. * Rate limit gate for sending of ERROR_NEED_MEMBERSHIP_CERTIFICATE
  362. */
  363. ZT_ALWAYS_INLINE bool rateGateRequestCredentials(const int64_t now)
  364. {
  365. if ((now - _lastCredentialRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  366. _lastCredentialRequestSent = now;
  367. return true;
  368. }
  369. return false;
  370. }
  371. /**
  372. * Rate limit gate for inbound WHOIS requests
  373. */
  374. ZT_ALWAYS_INLINE bool rateGateInboundWhoisRequest(const int64_t now)
  375. {
  376. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  377. _lastWhoisRequestReceived = now;
  378. return true;
  379. }
  380. return false;
  381. }
  382. /**
  383. * Rate limit gate for inbound ECHO requests
  384. */
  385. ZT_ALWAYS_INLINE bool rateGateEchoRequest(const int64_t now)
  386. {
  387. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  388. _lastEchoRequestReceived = now;
  389. return true;
  390. }
  391. return false;
  392. }
  393. /**
  394. * Rate limit gate for VERB_ACK
  395. */
  396. ZT_ALWAYS_INLINE bool rateGateACK(const int64_t now)
  397. {
  398. if ((now - _lastACKWindowReset) >= ZT_PATH_QOS_ACK_CUTOFF_TIME) {
  399. _lastACKWindowReset = now;
  400. _ACKCutoffCount = 0;
  401. } else {
  402. ++_ACKCutoffCount;
  403. }
  404. return (_ACKCutoffCount < ZT_PATH_QOS_ACK_CUTOFF_LIMIT);
  405. }
  406. /**
  407. * Rate limit gate for VERB_QOS_MEASUREMENT
  408. */
  409. ZT_ALWAYS_INLINE bool rateGateQoS(const int64_t now)
  410. {
  411. if ((now - _lastQoSWindowReset) >= ZT_PATH_QOS_ACK_CUTOFF_TIME) {
  412. _lastQoSWindowReset = now;
  413. _QoSCutoffCount = 0;
  414. } else {
  415. ++_QoSCutoffCount;
  416. }
  417. return (_QoSCutoffCount < ZT_PATH_QOS_ACK_CUTOFF_LIMIT);
  418. }
  419. /**
  420. * Rate limit gate for trying externally defined or static path
  421. */
  422. ZT_ALWAYS_INLINE bool rateGateTryStaticPath(const int64_t now)
  423. {
  424. if ((now - _lastTriedStaticPath) >= ZT_PEER_PING_PERIOD) {
  425. _lastTriedStaticPath = now;
  426. return true;
  427. }
  428. return false;
  429. }
  430. /**
  431. * @return Whether this peer is reachable via an aggregate link
  432. */
  433. inline bool hasAggregateLink()
  434. {
  435. return _localMultipathSupported && _remoteMultipathSupported && _remotePeerMultipathEnabled;
  436. }
  437. private:
  438. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  439. const RuntimeEnvironment *RR;
  440. int64_t _lastReceive; // direct or indirect
  441. int64_t _lastDirectPathPushSent;
  442. int64_t _lastDirectPathPushReceive;
  443. int64_t _lastCredentialRequestSent;
  444. int64_t _lastWhoisRequestReceived;
  445. int64_t _lastEchoRequestReceived;
  446. int64_t _lastCredentialsReceived;
  447. int64_t _lastACKWindowReset;
  448. int64_t _lastQoSWindowReset;
  449. int64_t _lastMultipathCompatibilityCheck;
  450. int64_t _lastTriedStaticPath;
  451. int _uniqueAlivePathCount;
  452. bool _localMultipathSupported;
  453. bool _remoteMultipathSupported;
  454. bool _canUseMultipath;
  455. uint8_t _freeRandomByte;
  456. uint16_t _vProto;
  457. uint16_t _vMajor;
  458. uint16_t _vMinor;
  459. uint16_t _vRevision;
  460. SharedPtr<Path> _paths[ZT_MAX_PEER_NETWORK_PATHS];
  461. Mutex _paths_m;
  462. Identity _id;
  463. unsigned int _directPathPushCutoffCount;
  464. unsigned int _credentialsCutoffCount;
  465. unsigned int _QoSCutoffCount;
  466. unsigned int _ACKCutoffCount;
  467. AtomicCounter __refCount;
  468. RingBuffer<int,ZT_MULTIPATH_PROPORTION_WIN_SZ> _pathChoiceHist;
  469. bool _linkIsBalanced;
  470. bool _linkIsRedundant;
  471. bool _remotePeerMultipathEnabled;
  472. int64_t _lastAggregateStatsReport;
  473. int64_t _lastAggregateAllocation;
  474. char _interfaceListStr[256]; // 16 characters * 16 paths in a link
  475. };
  476. } // namespace ZeroTier
  477. // Add a swap() for shared ptr's to peers to speed up peer sorts
  478. namespace std {
  479. template<>
  480. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  481. {
  482. a.swap(b);
  483. }
  484. }
  485. #endif