Peer.hpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 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 "../include/ZeroTierOne.h"
  30. #include "Constants.hpp"
  31. #include "RuntimeEnvironment.hpp"
  32. #include "Node.hpp"
  33. #include "Path.hpp"
  34. #include "Address.hpp"
  35. #include "Utils.hpp"
  36. #include "Identity.hpp"
  37. #include "InetAddress.hpp"
  38. #include "Packet.hpp"
  39. #include "SharedPtr.hpp"
  40. #include "AtomicCounter.hpp"
  41. #include "Hashtable.hpp"
  42. #include "Mutex.hpp"
  43. #define ZT_PEER_MAX_SERIALIZED_STATE_SIZE (sizeof(Peer) + 32 + (sizeof(Path) * 2))
  44. namespace ZeroTier {
  45. /**
  46. * Peer on P2P Network (virtual layer 1)
  47. */
  48. class Peer
  49. {
  50. friend class SharedPtr<Peer>;
  51. private:
  52. Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  53. public:
  54. ~Peer() {
  55. Utils::burn(_key,sizeof(_key));
  56. delete _pathChoiceHist;
  57. _pathChoiceHist = NULL;
  58. }
  59. /**
  60. * Construct a new peer
  61. *
  62. * @param renv Runtime environment
  63. * @param myIdentity Identity of THIS node (for key agreement)
  64. * @param peerIdentity Identity of peer
  65. * @throws std::runtime_error Key agreement with peer's identity failed
  66. */
  67. Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity);
  68. /**
  69. * @return This peer's ZT address (short for identity().address())
  70. */
  71. inline const Address &address() const { return _id.address(); }
  72. /**
  73. * @return This peer's identity
  74. */
  75. inline const Identity &identity() const { return _id; }
  76. /**
  77. * Log receipt of an authenticated packet
  78. *
  79. * This is called by the decode pipe when a packet is proven to be authentic
  80. * and appears to be valid.
  81. *
  82. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  83. * @param path Path over which packet was received
  84. * @param hops ZeroTier (not IP) hops
  85. * @param packetId Packet ID
  86. * @param verb Packet verb
  87. * @param inRePacketId Packet ID in reply to (default: none)
  88. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  89. * @param trustEstablished If true, some form of non-trivial trust (like allowed in network) has been established
  90. * @param networkId Network ID if this pertains to a network, or 0 otherwise
  91. */
  92. void received(
  93. void *tPtr,
  94. const SharedPtr<Path> &path,
  95. const unsigned int hops,
  96. const uint64_t packetId,
  97. const unsigned int payloadLength,
  98. const Packet::Verb verb,
  99. const uint64_t inRePacketId,
  100. const Packet::Verb inReVerb,
  101. const bool trustEstablished,
  102. const uint64_t networkId);
  103. /**
  104. * Check whether we have an active path to this peer via the given address
  105. *
  106. * @param now Current time
  107. * @param addr Remote address
  108. * @return True if we have an active path to this destination
  109. */
  110. inline bool hasActivePathTo(int64_t now,const InetAddress &addr) const
  111. {
  112. Mutex::Lock _l(_paths_m);
  113. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  114. if (_paths[i].p) {
  115. if (((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)&&(_paths[i].p->address() == addr))
  116. return true;
  117. } else break;
  118. }
  119. return false;
  120. }
  121. /**
  122. * Send via best direct path
  123. *
  124. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  125. * @param data Packet data
  126. * @param len Packet length
  127. * @param now Current time
  128. * @param force If true, send even if path is not alive
  129. * @return True if we actually sent something
  130. */
  131. inline bool sendDirect(void *tPtr,const void *data,unsigned int len,int64_t now,bool force)
  132. {
  133. SharedPtr<Path> bp(getAppropriatePath(now,force));
  134. if (bp)
  135. return bp->send(RR,tPtr,data,len,now);
  136. return false;
  137. }
  138. /**
  139. * Record statistics on outgoing packets
  140. *
  141. * @param path Path over which packet was sent
  142. * @param id Packet ID
  143. * @param len Length of packet payload
  144. * @param verb Packet verb
  145. * @param now Current time
  146. */
  147. void recordOutgoingPacket(const SharedPtr<Path> &path, const uint64_t packetId, uint16_t payloadLength, const Packet::Verb verb, int64_t now);
  148. /**
  149. * Record statistics on incoming packets
  150. *
  151. * @param path Path over which packet was sent
  152. * @param id Packet ID
  153. * @param len Length of packet payload
  154. * @param verb Packet verb
  155. * @param now Current time
  156. */
  157. void recordIncomingPacket(void *tPtr, const SharedPtr<Path> &path, const uint64_t packetId, uint16_t payloadLength, const Packet::Verb verb, int64_t now);
  158. /**
  159. * Send an ACK to peer for the most recent packets received
  160. *
  161. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  162. * @param localSocket Raw socket the ACK packet will be sent over
  163. * @param atAddress Destination for the ACK packet
  164. * @param now Current time
  165. */
  166. void sendACK(void *tPtr, const SharedPtr<Path> &path, const int64_t localSocket,const InetAddress &atAddress,int64_t now);
  167. /**
  168. * Send a QoS packet to peer so that it can evaluate the quality of this link
  169. *
  170. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  171. * @param localSocket Raw socket the QoS packet will be sent over
  172. * @param atAddress Destination for the QoS packet
  173. * @param now Current time
  174. */
  175. void sendQOS_MEASUREMENT(void *tPtr, const SharedPtr<Path> &path, const int64_t localSocket,const InetAddress &atAddress,int64_t now);
  176. /**
  177. * @return The relative quality values for each path
  178. */
  179. float computeAggregateLinkRelativeQuality(int64_t now);
  180. /**
  181. * @return The aggregate link Packet Delay Variance (PDV)
  182. */
  183. float computeAggregateLinkPacketDelayVariance();
  184. /**
  185. * @return The aggregate link mean latency
  186. */
  187. float computeAggregateLinkMeanLatency();
  188. /**
  189. * @return The number of currently alive "physical" paths in the aggregate link
  190. */
  191. int aggregateLinkPhysicalPathCount();
  192. /**
  193. * @return The number of currently alive "logical" paths in the aggregate link
  194. */
  195. int aggregateLinkLogicalPathCount();
  196. /**
  197. * Get the most appropriate direct path based on current multipath and QoS configuration
  198. *
  199. * @param now Current time
  200. * @param includeExpired If true, include even expired paths
  201. * @return Best current path or NULL if none
  202. */
  203. SharedPtr<Path> getAppropriatePath(int64_t now, bool includeExpired);
  204. /**
  205. * Generate a human-readable string of interface names making up the aggregate link, also include
  206. * moving allocation and IP version number for each (for tracing)
  207. */
  208. char *interfaceListStr();
  209. /**
  210. * Send VERB_RENDEZVOUS to this and another peer via the best common IP scope and path
  211. */
  212. void introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const;
  213. /**
  214. * Send a HELLO to this peer at a specified physical address
  215. *
  216. * No statistics or sent times are updated here.
  217. *
  218. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  219. * @param localSocket Local source socket
  220. * @param atAddress Destination address
  221. * @param now Current time
  222. */
  223. void sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now);
  224. /**
  225. * Send ECHO (or HELLO for older peers) to this peer at the given address
  226. *
  227. * No statistics or sent times are updated here.
  228. *
  229. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  230. * @param localSocket Local source socket
  231. * @param atAddress Destination address
  232. * @param now Current time
  233. * @param sendFullHello If true, always send a full HELLO instead of just an ECHO
  234. */
  235. void attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello);
  236. /**
  237. * Try a memorized or statically defined path if any are known
  238. *
  239. * Under the hood this is done periodically based on ZT_TRY_MEMORIZED_PATH_INTERVAL.
  240. *
  241. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  242. * @param now Current time
  243. */
  244. void tryMemorizedPath(void *tPtr,int64_t now);
  245. /**
  246. * Send pings or keepalives depending on configured timeouts
  247. *
  248. * This also cleans up some internal data structures. It's called periodically from Node.
  249. *
  250. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  251. * @param now Current time
  252. * @param inetAddressFamily Keep this address family alive, or -1 for any
  253. * @return 0 if nothing sent or bit mask: bit 0x1 if IPv4 sent, bit 0x2 if IPv6 sent (0x3 means both sent)
  254. */
  255. unsigned int doPingAndKeepalive(void *tPtr,int64_t now);
  256. /**
  257. * Clear paths whose localSocket(s) are in a CLOSED state or have an otherwise INVALID state.
  258. * This should be called frequently so that we can detect and remove unproductive or invalid paths.
  259. *
  260. * Under the hood this is done periodically based on ZT_CLOSED_PATH_PRUNING_INTERVAL.
  261. *
  262. * @return Number of paths that were pruned this round
  263. */
  264. unsigned int prunePaths();
  265. /**
  266. * Process a cluster redirect sent by this peer
  267. *
  268. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  269. * @param originatingPath Path from which redirect originated
  270. * @param remoteAddress Remote address
  271. * @param now Current time
  272. */
  273. void clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now);
  274. /**
  275. * Reset paths within a given IP scope and address family
  276. *
  277. * Resetting a path involves sending an ECHO to it and then deactivating
  278. * it until or unless it responds. This is done when we detect a change
  279. * to our external IP or another system change that might invalidate
  280. * many or all current paths.
  281. *
  282. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  283. * @param scope IP scope
  284. * @param inetAddressFamily Family e.g. AF_INET
  285. * @param now Current time
  286. */
  287. void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now);
  288. /**
  289. * @param now Current time
  290. * @return All known paths to this peer
  291. */
  292. inline std::vector< SharedPtr<Path> > paths(const int64_t now) const
  293. {
  294. std::vector< SharedPtr<Path> > pp;
  295. Mutex::Lock _l(_paths_m);
  296. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  297. if (!_paths[i].p) break;
  298. pp.push_back(_paths[i].p);
  299. }
  300. return pp;
  301. }
  302. /**
  303. * @return Time of last receive of anything, whether direct or relayed
  304. */
  305. inline int64_t lastReceive() const { return _lastReceive; }
  306. /**
  307. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  308. */
  309. inline bool isAlive(const int64_t now) const { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  310. /**
  311. * @return True if this peer has sent us real network traffic recently
  312. */
  313. inline int64_t isActive(int64_t now) const { return ((now - _lastNontrivialReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  314. /**
  315. * @return Latency in milliseconds of best path or 0xffff if unknown / no paths
  316. */
  317. inline unsigned int latency(const int64_t now)
  318. {
  319. SharedPtr<Path> bp(getAppropriatePath(now,false));
  320. if (bp)
  321. return bp->latency();
  322. return 0xffff;
  323. }
  324. /**
  325. * This computes a quality score for relays and root servers
  326. *
  327. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  328. * receive the worst possible quality (max unsigned int). Otherwise the
  329. * quality is a product of latency and the number of potential missed
  330. * pings. This causes roots and relays to switch over a bit faster if they
  331. * fail.
  332. *
  333. * @return Relay quality score computed from latency and other factors, lower is better
  334. */
  335. inline unsigned int relayQuality(const int64_t now)
  336. {
  337. const uint64_t tsr = now - _lastReceive;
  338. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  339. return (~(unsigned int)0);
  340. unsigned int l = latency(now);
  341. if (!l)
  342. l = 0xffff;
  343. return (l * (((unsigned int)tsr / (ZT_PEER_PING_PERIOD + 1000)) + 1));
  344. }
  345. /**
  346. * @return 256-bit secret symmetric encryption key
  347. */
  348. inline const unsigned char *key() const { return _key; }
  349. /**
  350. * Set the currently known remote version of this peer's client
  351. *
  352. * @param vproto Protocol version
  353. * @param vmaj Major version
  354. * @param vmin Minor version
  355. * @param vrev Revision
  356. */
  357. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  358. {
  359. _vProto = (uint16_t)vproto;
  360. _vMajor = (uint16_t)vmaj;
  361. _vMinor = (uint16_t)vmin;
  362. _vRevision = (uint16_t)vrev;
  363. }
  364. inline unsigned int remoteVersionProtocol() const { return _vProto; }
  365. inline unsigned int remoteVersionMajor() const { return _vMajor; }
  366. inline unsigned int remoteVersionMinor() const { return _vMinor; }
  367. inline unsigned int remoteVersionRevision() const { return _vRevision; }
  368. inline bool remoteVersionKnown() const { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  369. /**
  370. * Record that the remote peer does have multipath enabled. As is evident by the receipt of a VERB_ACK
  371. * or a VERB_QOS_MEASUREMENT packet at some point in the past. Until this flag is set, the local client
  372. * shall assume that multipath is not enabled and should only use classical Protocol 9 logic.
  373. */
  374. inline void inferRemoteMultipathEnabled() { _remotePeerMultipathEnabled = true; }
  375. /**
  376. * @return Whether the local client supports and is configured to use multipath
  377. */
  378. inline bool localMultipathSupport() { return ((RR->node->getMultipathMode() != ZT_MULTIPATH_NONE) && (ZT_PROTO_VERSION > 9)); }
  379. /**
  380. * @return Whether the remote peer supports and is configured to use multipath
  381. */
  382. inline bool remoteMultipathSupport() { return (_remotePeerMultipathEnabled && (_vProto > 9)); }
  383. /**
  384. * @return Whether this client can use multipath to communicate with this peer. True if both peers are using
  385. * the correct protocol and if both peers have multipath enabled. False if otherwise.
  386. */
  387. inline bool canUseMultipath() { return (localMultipathSupport() && remoteMultipathSupport()); }
  388. /**
  389. * @return True if peer has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  390. */
  391. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  392. /**
  393. * Rate limit gate for VERB_PUSH_DIRECT_PATHS
  394. */
  395. inline bool rateGatePushDirectPaths(const int64_t now)
  396. {
  397. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  398. ++_directPathPushCutoffCount;
  399. else _directPathPushCutoffCount = 0;
  400. _lastDirectPathPushReceive = now;
  401. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  402. }
  403. /**
  404. * Rate limit gate for VERB_NETWORK_CREDENTIALS
  405. */
  406. inline bool rateGateCredentialsReceived(const int64_t now)
  407. {
  408. if ((now - _lastCredentialsReceived) <= ZT_PEER_CREDENTIALS_CUTOFF_TIME)
  409. ++_credentialsCutoffCount;
  410. else _credentialsCutoffCount = 0;
  411. _lastCredentialsReceived = now;
  412. return (_directPathPushCutoffCount < ZT_PEER_CREDEITIALS_CUTOFF_LIMIT);
  413. }
  414. /**
  415. * Rate limit gate for sending of ERROR_NEED_MEMBERSHIP_CERTIFICATE
  416. */
  417. inline bool rateGateRequestCredentials(const int64_t now)
  418. {
  419. if ((now - _lastCredentialRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  420. _lastCredentialRequestSent = now;
  421. return true;
  422. }
  423. return false;
  424. }
  425. /**
  426. * Rate limit gate for inbound WHOIS requests
  427. */
  428. inline bool rateGateInboundWhoisRequest(const int64_t now)
  429. {
  430. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  431. _lastWhoisRequestReceived = now;
  432. return true;
  433. }
  434. return false;
  435. }
  436. /**
  437. * Rate limit gate for inbound ECHO requests
  438. */
  439. inline bool rateGateEchoRequest(const int64_t now)
  440. {
  441. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  442. _lastEchoRequestReceived = now;
  443. return true;
  444. }
  445. return false;
  446. }
  447. /**
  448. * Rate gate incoming requests for network COM
  449. */
  450. inline bool rateGateIncomingComRequest(const int64_t now)
  451. {
  452. if ((now - _lastComRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  453. _lastComRequestReceived = now;
  454. return true;
  455. }
  456. return false;
  457. }
  458. /**
  459. * Rate gate outgoing requests for network COM
  460. */
  461. inline bool rateGateOutgoingComRequest(const int64_t now)
  462. {
  463. if ((now - _lastComRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  464. _lastComRequestSent = now;
  465. return true;
  466. }
  467. return false;
  468. }
  469. /**
  470. * Rate limit gate for VERB_QOS_MEASUREMENT
  471. */
  472. inline bool rateGateQoS(const int64_t now)
  473. {
  474. if ((now - _lastQoSReceive) <= ZT_PATH_QOS_ACK_CUTOFF_TIME)
  475. ++_QoSCutoffCount;
  476. else _QoSCutoffCount = 0;
  477. _lastQoSReceive = now;
  478. return (_QoSCutoffCount < ZT_PATH_QOS_ACK_CUTOFF_LIMIT);
  479. }
  480. /**
  481. * Rate limit gate for VERB_ACK
  482. */
  483. inline bool rateGateACK(const int64_t now)
  484. {
  485. if ((now - _lastACKReceive) <= ZT_PATH_QOS_ACK_CUTOFF_TIME)
  486. ++_ACKCutoffCount;
  487. else _ACKCutoffCount = 0;
  488. _lastACKReceive = now;
  489. return (_ACKCutoffCount < ZT_PATH_QOS_ACK_CUTOFF_LIMIT);
  490. }
  491. /**
  492. * Serialize a peer for storage in local cache
  493. *
  494. * This does not serialize everything, just non-ephemeral information.
  495. */
  496. template<unsigned int C>
  497. inline void serializeForCache(Buffer<C> &b) const
  498. {
  499. b.append((uint8_t)1);
  500. _id.serialize(b);
  501. b.append((uint16_t)_vProto);
  502. b.append((uint16_t)_vMajor);
  503. b.append((uint16_t)_vMinor);
  504. b.append((uint16_t)_vRevision);
  505. {
  506. Mutex::Lock _l(_paths_m);
  507. unsigned int pc = 0;
  508. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  509. if (_paths[i].p)
  510. ++pc;
  511. else break;
  512. }
  513. b.append((uint16_t)pc);
  514. for(unsigned int i=0;i<pc;++i)
  515. _paths[i].p->address().serialize(b);
  516. }
  517. }
  518. template<unsigned int C>
  519. inline static SharedPtr<Peer> deserializeFromCache(int64_t now,void *tPtr,Buffer<C> &b,const RuntimeEnvironment *renv)
  520. {
  521. try {
  522. unsigned int ptr = 0;
  523. if (b[ptr++] != 1)
  524. return SharedPtr<Peer>();
  525. Identity id;
  526. ptr += id.deserialize(b,ptr);
  527. if (!id)
  528. return SharedPtr<Peer>();
  529. SharedPtr<Peer> p(new Peer(renv,renv->identity,id));
  530. p->_vProto = b.template at<uint16_t>(ptr); ptr += 2;
  531. p->_vMajor = b.template at<uint16_t>(ptr); ptr += 2;
  532. p->_vMinor = b.template at<uint16_t>(ptr); ptr += 2;
  533. p->_vRevision = b.template at<uint16_t>(ptr); ptr += 2;
  534. // When we deserialize from the cache we don't actually restore paths. We
  535. // just try them and then re-learn them if they happen to still be up.
  536. // Paths are fairly ephemeral in the real world in most cases.
  537. const unsigned int tryPathCount = b.template at<uint16_t>(ptr); ptr += 2;
  538. for(unsigned int i=0;i<tryPathCount;++i) {
  539. InetAddress inaddr;
  540. try {
  541. ptr += inaddr.deserialize(b,ptr);
  542. if (inaddr)
  543. p->attemptToContactAt(tPtr,-1,inaddr,now,true);
  544. } catch ( ... ) {
  545. break;
  546. }
  547. }
  548. return p;
  549. } catch ( ... ) {
  550. return SharedPtr<Peer>();
  551. }
  552. }
  553. private:
  554. struct _PeerPath
  555. {
  556. _PeerPath() : lr(0),p(),priority(1) {}
  557. int64_t lr; // time of last valid ZeroTier packet
  558. SharedPtr<Path> p;
  559. long priority; // >= 1, higher is better
  560. };
  561. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  562. const RuntimeEnvironment *RR;
  563. int64_t _lastReceive; // direct or indirect
  564. int64_t _lastNontrivialReceive; // frames, things like netconf, etc.
  565. int64_t _lastTriedMemorizedPath;
  566. int64_t _lastDirectPathPushSent;
  567. int64_t _lastDirectPathPushReceive;
  568. int64_t _lastCredentialRequestSent;
  569. int64_t _lastWhoisRequestReceived;
  570. int64_t _lastEchoRequestReceived;
  571. int64_t _lastComRequestReceived;
  572. int64_t _lastComRequestSent;
  573. int64_t _lastCredentialsReceived;
  574. int64_t _lastTrustEstablishedPacketReceived;
  575. int64_t _lastQoSReceive;
  576. int64_t _lastACKReceive;
  577. int64_t _lastSentFullHello;
  578. int64_t _lastPathPrune;
  579. uint16_t _vProto;
  580. uint16_t _vMajor;
  581. uint16_t _vMinor;
  582. uint16_t _vRevision;
  583. _PeerPath _paths[ZT_MAX_PEER_NETWORK_PATHS];
  584. Mutex _paths_m;
  585. Identity _id;
  586. unsigned int _directPathPushCutoffCount;
  587. unsigned int _credentialsCutoffCount;
  588. unsigned int _QoSCutoffCount;
  589. unsigned int _ACKCutoffCount;
  590. AtomicCounter __refCount;
  591. RingBuffer<int> *_pathChoiceHist;
  592. bool _linkIsBalanced;
  593. bool _linkIsRedundant;
  594. bool _remotePeerMultipathEnabled;
  595. uint64_t _lastAggregateStatsReport;
  596. char _interfaceListStr[256]; // 16 characters * 16 paths in a link
  597. };
  598. } // namespace ZeroTier
  599. // Add a swap() for shared ptr's to peers to speed up peer sorts
  600. namespace std {
  601. template<>
  602. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  603. {
  604. a.swap(b);
  605. }
  606. }
  607. #endif