Peer.hpp 21 KB

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