Peer.hpp 17 KB

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