Peer.hpp 18 KB

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