Peer.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /*
  2. * Copyright (c)2013-2020 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: 2024-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 "../include/ZeroTierOne.h"
  17. #include "Constants.hpp"
  18. #include "RuntimeEnvironment.hpp"
  19. #include "Node.hpp"
  20. #include "Path.hpp"
  21. #include "Address.hpp"
  22. #include "Utils.hpp"
  23. #include "Identity.hpp"
  24. #include "InetAddress.hpp"
  25. #include "Packet.hpp"
  26. #include "SharedPtr.hpp"
  27. #include "AtomicCounter.hpp"
  28. #include "Hashtable.hpp"
  29. #include "Mutex.hpp"
  30. #include "Bond.hpp"
  31. #include "BondController.hpp"
  32. #define ZT_PEER_MAX_SERIALIZED_STATE_SIZE (sizeof(Peer) + 32 + (sizeof(Path) * 2))
  33. namespace ZeroTier {
  34. /**
  35. * Peer on P2P Network (virtual layer 1)
  36. */
  37. class Peer
  38. {
  39. friend class SharedPtr<Peer>;
  40. friend class SharedPtr<Bond>;
  41. friend class Switch;
  42. friend class Bond;
  43. private:
  44. Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  45. public:
  46. ~Peer() { Utils::burn(_key,sizeof(_key)); }
  47. /**
  48. * Construct a new peer
  49. *
  50. * @param renv Runtime environment
  51. * @param myIdentity Identity of THIS node (for key agreement)
  52. * @param peerIdentity Identity of peer
  53. * @throws std::runtime_error Key agreement with peer's identity failed
  54. */
  55. Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity);
  56. /**
  57. * @return This peer's ZT address (short for identity().address())
  58. */
  59. inline const Address &address() const { return _id.address(); }
  60. /**
  61. * @return This peer's identity
  62. */
  63. inline const Identity &identity() const { return _id; }
  64. /**
  65. * Log receipt of an authenticated packet
  66. *
  67. * This is called by the decode pipe when a packet is proven to be authentic
  68. * and appears to be valid.
  69. *
  70. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  71. * @param path Path over which packet was received
  72. * @param hops ZeroTier (not IP) hops
  73. * @param packetId Packet ID
  74. * @param verb Packet verb
  75. * @param inRePacketId Packet ID in reply to (default: none)
  76. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  77. * @param trustEstablished If true, some form of non-trivial trust (like allowed in network) has been established
  78. * @param networkId Network ID if this pertains to a network, or 0 otherwise
  79. */
  80. void received(
  81. void *tPtr,
  82. const SharedPtr<Path> &path,
  83. const unsigned int hops,
  84. const uint64_t packetId,
  85. const unsigned int payloadLength,
  86. const Packet::Verb verb,
  87. const uint64_t inRePacketId,
  88. const Packet::Verb inReVerb,
  89. const bool trustEstablished,
  90. const uint64_t networkId,
  91. const int32_t flowId);
  92. /**
  93. * Check whether we have an active path to this peer via the given address
  94. *
  95. * @param now Current time
  96. * @param addr Remote address
  97. * @return True if we have an active path to this destination
  98. */
  99. inline bool hasActivePathTo(int64_t now,const InetAddress &addr) const
  100. {
  101. Mutex::Lock _l(_paths_m);
  102. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  103. if (_paths[i].p) {
  104. if (((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)&&(_paths[i].p->address() == addr))
  105. return true;
  106. } else break;
  107. }
  108. return false;
  109. }
  110. /**
  111. * Send via best direct path
  112. *
  113. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  114. * @param data Packet data
  115. * @param len Packet length
  116. * @param now Current time
  117. * @param force If true, send even if path is not alive
  118. * @return True if we actually sent something
  119. */
  120. inline bool sendDirect(void *tPtr,const void *data,unsigned int len,int64_t now,bool force)
  121. {
  122. SharedPtr<Path> bp(getAppropriatePath(now,force));
  123. if (bp)
  124. return bp->send(RR,tPtr,data,len,now);
  125. return false;
  126. }
  127. /**
  128. * Record incoming packets to
  129. *
  130. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  131. * @param path Path over which packet was received
  132. * @param packetId Packet ID
  133. * @param payloadLength Length of packet data payload
  134. * @param verb Packet verb
  135. * @param flowId Flow ID
  136. * @param now Current time
  137. */
  138. void recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId,
  139. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now);
  140. /**
  141. *
  142. * @param path Path over which packet is being sent
  143. * @param packetId Packet ID
  144. * @param payloadLength Length of packet data payload
  145. * @param verb Packet verb
  146. * @param flowId Flow ID
  147. * @param now Current time
  148. */
  149. void recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId,
  150. uint16_t payloadLength, const Packet::Verb verb, const int32_t flowId, int64_t now);
  151. /**
  152. * Record an invalid incoming packet. This packet failed
  153. * MAC/compression/cipher checks and will now contribute to a
  154. * Packet Error Ratio (PER).
  155. *
  156. * @param path Path over which packet was received
  157. */
  158. void recordIncomingInvalidPacket(const SharedPtr<Path>& path);
  159. /**
  160. * Get the most appropriate direct path based on current multipath and QoS configuration
  161. *
  162. * @param now Current time
  163. * @param includeExpired If true, include even expired paths
  164. * @return Best current path or NULL if none
  165. */
  166. SharedPtr<Path> getAppropriatePath(int64_t now, bool includeExpired, int32_t flowId = -1);
  167. /**
  168. * Send VERB_RENDEZVOUS to this and another peer via the best common IP scope and path
  169. */
  170. void introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const;
  171. /**
  172. * Send a HELLO to this peer at a specified physical address
  173. *
  174. * No statistics or sent times are updated here.
  175. *
  176. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  177. * @param localSocket Local source socket
  178. * @param atAddress Destination address
  179. * @param now Current time
  180. */
  181. void sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now);
  182. /**
  183. * Send ECHO (or HELLO for older peers) to this peer at the given address
  184. *
  185. * No statistics or sent times are updated here.
  186. *
  187. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  188. * @param localSocket Local source socket
  189. * @param atAddress Destination address
  190. * @param now Current time
  191. * @param sendFullHello If true, always send a full HELLO instead of just an ECHO
  192. */
  193. void attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello);
  194. /**
  195. * Try a memorized or statically defined path if any are known
  196. *
  197. * Under the hood this is done periodically based on ZT_TRY_MEMORIZED_PATH_INTERVAL.
  198. *
  199. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  200. * @param now Current time
  201. */
  202. void tryMemorizedPath(void *tPtr,int64_t now);
  203. /**
  204. * A check to be performed periodically which determines whether multipath communication is
  205. * possible with this peer. This check should be performed early in the life-cycle of the peer
  206. * as well as during the process of learning new paths.
  207. */
  208. void performMultipathStateCheck(int64_t now);
  209. /**
  210. * Send pings or keepalives depending on configured timeouts
  211. *
  212. * This also cleans up some internal data structures. It's called periodically from Node.
  213. *
  214. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  215. * @param now Current time
  216. * @param inetAddressFamily Keep this address family alive, or -1 for any
  217. * @return 0 if nothing sent or bit mask: bit 0x1 if IPv4 sent, bit 0x2 if IPv6 sent (0x3 means both sent)
  218. */
  219. unsigned int doPingAndKeepalive(void *tPtr,int64_t now);
  220. /**
  221. * Process a cluster redirect sent by this peer
  222. *
  223. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  224. * @param originatingPath Path from which redirect originated
  225. * @param remoteAddress Remote address
  226. * @param now Current time
  227. */
  228. void clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now);
  229. /**
  230. * Reset paths within a given IP scope and address family
  231. *
  232. * Resetting a path involves sending an ECHO to it and then deactivating
  233. * it until or unless it responds. This is done when we detect a change
  234. * to our external IP or another system change that might invalidate
  235. * many or all current paths.
  236. *
  237. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  238. * @param scope IP scope
  239. * @param inetAddressFamily Family e.g. AF_INET
  240. * @param now Current time
  241. */
  242. void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now);
  243. /**
  244. * @param now Current time
  245. * @return All known paths to this peer
  246. */
  247. inline std::vector< SharedPtr<Path> > paths(const int64_t now) const
  248. {
  249. std::vector< SharedPtr<Path> > pp;
  250. Mutex::Lock _l(_paths_m);
  251. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  252. if (!_paths[i].p) break;
  253. pp.push_back(_paths[i].p);
  254. }
  255. return pp;
  256. }
  257. /**
  258. * @return Time of last receive of anything, whether direct or relayed
  259. */
  260. inline int64_t lastReceive() const { return _lastReceive; }
  261. /**
  262. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  263. */
  264. inline bool isAlive(const int64_t now) const { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  265. /**
  266. * @return True if this peer has sent us real network traffic recently
  267. */
  268. inline int64_t isActive(int64_t now) const { return ((now - _lastNontrivialReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  269. /**
  270. * @return Latency in milliseconds of best/aggregate path or 0xffff if unknown / no paths
  271. */
  272. inline unsigned int latency(const int64_t now)
  273. {
  274. if (_canUseMultipath) {
  275. return (int)_lastComputedAggregateMeanLatency;
  276. } else {
  277. SharedPtr<Path> bp(getAppropriatePath(now,false));
  278. if (bp)
  279. return bp->latency();
  280. return 0xffff;
  281. }
  282. }
  283. /**
  284. * This computes a quality score for relays and root servers
  285. *
  286. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  287. * receive the worst possible quality (max unsigned int). Otherwise the
  288. * quality is a product of latency and the number of potential missed
  289. * pings. This causes roots and relays to switch over a bit faster if they
  290. * fail.
  291. *
  292. * @return Relay quality score computed from latency and other factors, lower is better
  293. */
  294. inline unsigned int relayQuality(const int64_t now)
  295. {
  296. const uint64_t tsr = now - _lastReceive;
  297. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  298. return (~(unsigned int)0);
  299. unsigned int l = latency(now);
  300. if (!l)
  301. l = 0xffff;
  302. return (l * (((unsigned int)tsr / (ZT_PEER_PING_PERIOD + 1000)) + 1));
  303. }
  304. /**
  305. * @return 256-bit secret symmetric encryption key
  306. */
  307. inline const unsigned char *key() const { return _key; }
  308. /**
  309. * Set the currently known remote version of this peer's client
  310. *
  311. * @param vproto Protocol version
  312. * @param vmaj Major version
  313. * @param vmin Minor version
  314. * @param vrev Revision
  315. */
  316. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  317. {
  318. _vProto = (uint16_t)vproto;
  319. _vMajor = (uint16_t)vmaj;
  320. _vMinor = (uint16_t)vmin;
  321. _vRevision = (uint16_t)vrev;
  322. }
  323. inline unsigned int remoteVersionProtocol() const { return _vProto; }
  324. inline unsigned int remoteVersionMajor() const { return _vMajor; }
  325. inline unsigned int remoteVersionMinor() const { return _vMinor; }
  326. inline unsigned int remoteVersionRevision() const { return _vRevision; }
  327. inline bool remoteVersionKnown() const { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  328. /**
  329. * @return True if peer has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  330. */
  331. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  332. /**
  333. * Rate limit gate for VERB_PUSH_DIRECT_PATHS
  334. */
  335. inline bool rateGatePushDirectPaths(const int64_t now)
  336. {
  337. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  338. ++_directPathPushCutoffCount;
  339. else _directPathPushCutoffCount = 0;
  340. _lastDirectPathPushReceive = now;
  341. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  342. }
  343. /**
  344. * Rate limit gate for VERB_NETWORK_CREDENTIALS
  345. */
  346. inline bool rateGateCredentialsReceived(const int64_t now)
  347. {
  348. if ((now - _lastCredentialsReceived) <= ZT_PEER_CREDENTIALS_CUTOFF_TIME)
  349. ++_credentialsCutoffCount;
  350. else _credentialsCutoffCount = 0;
  351. _lastCredentialsReceived = now;
  352. return (_directPathPushCutoffCount < ZT_PEER_CREDEITIALS_CUTOFF_LIMIT);
  353. }
  354. /**
  355. * Rate limit gate for sending of ERROR_NEED_MEMBERSHIP_CERTIFICATE
  356. */
  357. inline bool rateGateRequestCredentials(const int64_t now)
  358. {
  359. if ((now - _lastCredentialRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  360. _lastCredentialRequestSent = now;
  361. return true;
  362. }
  363. return false;
  364. }
  365. /**
  366. * Rate limit gate for inbound WHOIS requests
  367. */
  368. inline bool rateGateInboundWhoisRequest(const int64_t now)
  369. {
  370. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  371. _lastWhoisRequestReceived = now;
  372. return true;
  373. }
  374. return false;
  375. }
  376. /**
  377. * Rate limit gate for inbound ECHO requests. This rate limiter works
  378. * by draining a certain number of requests per unit time. Each peer may
  379. * theoretically receive up to ZT_ECHO_CUTOFF_LIMIT requests per second.
  380. */
  381. inline bool rateGateEchoRequest(const int64_t now)
  382. {
  383. /*
  384. // TODO: Rethink this
  385. if (_canUseMultipath) {
  386. _echoRequestCutoffCount++;
  387. int numToDrain = (now - _lastEchoCheck) / ZT_ECHO_DRAINAGE_DIVISOR;
  388. _lastEchoCheck = now;
  389. fprintf(stderr, "ZT_ECHO_CUTOFF_LIMIT=%d, (now - _lastEchoCheck)=%d, numToDrain=%d, ZT_ECHO_DRAINAGE_DIVISOR=%d\n", ZT_ECHO_CUTOFF_LIMIT, (now - _lastEchoCheck), numToDrain, ZT_ECHO_DRAINAGE_DIVISOR);
  390. if (_echoRequestCutoffCount > numToDrain) {
  391. _echoRequestCutoffCount-=numToDrain;
  392. }
  393. else {
  394. _echoRequestCutoffCount = 0;
  395. }
  396. return (_echoRequestCutoffCount < ZT_ECHO_CUTOFF_LIMIT);
  397. } else {
  398. if ((now - _lastEchoRequestReceived) >= (ZT_PEER_GENERAL_RATE_LIMIT)) {
  399. _lastEchoRequestReceived = now;
  400. return true;
  401. }
  402. return false;
  403. }
  404. */
  405. return true;
  406. }
  407. /**
  408. * Serialize a peer for storage in local cache
  409. *
  410. * This does not serialize everything, just non-ephemeral information.
  411. */
  412. template<unsigned int C>
  413. inline void serializeForCache(Buffer<C> &b) const
  414. {
  415. b.append((uint8_t)1);
  416. _id.serialize(b);
  417. b.append((uint16_t)_vProto);
  418. b.append((uint16_t)_vMajor);
  419. b.append((uint16_t)_vMinor);
  420. b.append((uint16_t)_vRevision);
  421. {
  422. Mutex::Lock _l(_paths_m);
  423. unsigned int pc = 0;
  424. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  425. if (_paths[i].p)
  426. ++pc;
  427. else break;
  428. }
  429. b.append((uint16_t)pc);
  430. for(unsigned int i=0;i<pc;++i)
  431. _paths[i].p->address().serialize(b);
  432. }
  433. }
  434. template<unsigned int C>
  435. inline static SharedPtr<Peer> deserializeFromCache(int64_t now,void *tPtr,Buffer<C> &b,const RuntimeEnvironment *renv)
  436. {
  437. try {
  438. unsigned int ptr = 0;
  439. if (b[ptr++] != 1)
  440. return SharedPtr<Peer>();
  441. Identity id;
  442. ptr += id.deserialize(b,ptr);
  443. if (!id)
  444. return SharedPtr<Peer>();
  445. SharedPtr<Peer> p(new Peer(renv,renv->identity,id));
  446. p->_vProto = b.template at<uint16_t>(ptr); ptr += 2;
  447. p->_vMajor = b.template at<uint16_t>(ptr); ptr += 2;
  448. p->_vMinor = b.template at<uint16_t>(ptr); ptr += 2;
  449. p->_vRevision = b.template at<uint16_t>(ptr); ptr += 2;
  450. // When we deserialize from the cache we don't actually restore paths. We
  451. // just try them and then re-learn them if they happen to still be up.
  452. // Paths are fairly ephemeral in the real world in most cases.
  453. const unsigned int tryPathCount = b.template at<uint16_t>(ptr); ptr += 2;
  454. for(unsigned int i=0;i<tryPathCount;++i) {
  455. InetAddress inaddr;
  456. try {
  457. ptr += inaddr.deserialize(b,ptr);
  458. if (inaddr)
  459. p->attemptToContactAt(tPtr,-1,inaddr,now,true);
  460. } catch ( ... ) {
  461. break;
  462. }
  463. }
  464. return p;
  465. } catch ( ... ) {
  466. return SharedPtr<Peer>();
  467. }
  468. }
  469. /**
  470. *
  471. * @return
  472. */
  473. SharedPtr<Bond> bond() { return _bondToPeer; }
  474. /**
  475. *
  476. * @return
  477. */
  478. inline int8_t bondingPolicy() { return _bondingPolicy; }
  479. private:
  480. struct _PeerPath
  481. {
  482. _PeerPath() : lr(0),p(),priority(1) {}
  483. int64_t lr; // time of last valid ZeroTier packet
  484. SharedPtr<Path> p;
  485. long priority; // >= 1, higher is better
  486. };
  487. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  488. const RuntimeEnvironment *RR;
  489. int64_t _lastReceive; // direct or indirect
  490. int64_t _lastNontrivialReceive; // frames, things like netconf, etc.
  491. int64_t _lastTriedMemorizedPath;
  492. int64_t _lastDirectPathPushSent;
  493. int64_t _lastDirectPathPushReceive;
  494. int64_t _lastEchoRequestReceived;
  495. int64_t _lastCredentialRequestSent;
  496. int64_t _lastWhoisRequestReceived;
  497. int64_t _lastCredentialsReceived;
  498. int64_t _lastTrustEstablishedPacketReceived;
  499. int64_t _lastSentFullHello;
  500. int64_t _lastEchoCheck;
  501. unsigned char _freeRandomByte;
  502. uint16_t _vProto;
  503. uint16_t _vMajor;
  504. uint16_t _vMinor;
  505. uint16_t _vRevision;
  506. _PeerPath _paths[ZT_MAX_PEER_NETWORK_PATHS];
  507. Mutex _paths_m;
  508. Identity _id;
  509. unsigned int _directPathPushCutoffCount;
  510. unsigned int _credentialsCutoffCount;
  511. unsigned int _echoRequestCutoffCount;
  512. AtomicCounter __refCount;
  513. bool _remotePeerMultipathEnabled;
  514. int _uniqueAlivePathCount;
  515. bool _localMultipathSupported;
  516. bool _remoteMultipathSupported;
  517. bool _canUseMultipath;
  518. volatile bool _shouldCollectPathStatistics;
  519. volatile int8_t _bondingPolicy;
  520. int32_t _lastComputedAggregateMeanLatency;
  521. SharedPtr<Bond> _bondToPeer;
  522. };
  523. } // namespace ZeroTier
  524. // Add a swap() for shared ptr's to peers to speed up peer sorts
  525. namespace std {
  526. template<>
  527. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  528. {
  529. a.swap(b);
  530. }
  531. }
  532. #endif