Peer.hpp 21 KB

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