Peer.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. int computeAggregateLinkPacketDelayVariance();
  186. /**
  187. * @return The aggregate link mean latency
  188. */
  189. int 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 (_canUseMultipath) {
  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. * Periodically update known multipath activation constraints. This is done so that we know when and when
  377. * not to use multipath logic. Doing this once every few seconds is sufficient.
  378. *
  379. * @param now Current time
  380. */
  381. inline void processBackgroundPeerTasks(int64_t now);
  382. /**
  383. * Record that the remote peer does have multipath enabled. As is evident by the receipt of a VERB_ACK
  384. * or a VERB_QOS_MEASUREMENT packet at some point in the past. Until this flag is set, the local client
  385. * shall assume that multipath is not enabled and should only use classical Protocol 9 logic.
  386. */
  387. inline void inferRemoteMultipathEnabled() { _remotePeerMultipathEnabled = true; }
  388. /**
  389. * @return Whether the local client supports and is configured to use multipath
  390. */
  391. inline bool localMultipathSupport() { return _localMultipathSupported; }
  392. /**
  393. * @return Whether the remote peer supports and is configured to use multipath
  394. */
  395. inline bool remoteMultipathSupport() { return _remoteMultipathSupported; }
  396. /**
  397. * @return Whether this client can use multipath to communicate with this peer. True if both peers are using
  398. * the correct protocol and if both peers have multipath enabled. False if otherwise.
  399. */
  400. inline bool canUseMultipath() { return _canUseMultipath; }
  401. /**
  402. * @return True if peer has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  403. */
  404. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  405. /**
  406. * Rate limit gate for VERB_PUSH_DIRECT_PATHS
  407. */
  408. inline bool rateGatePushDirectPaths(const int64_t now)
  409. {
  410. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  411. ++_directPathPushCutoffCount;
  412. else _directPathPushCutoffCount = 0;
  413. _lastDirectPathPushReceive = now;
  414. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  415. }
  416. /**
  417. * Rate limit gate for VERB_NETWORK_CREDENTIALS
  418. */
  419. inline bool rateGateCredentialsReceived(const int64_t now)
  420. {
  421. if ((now - _lastCredentialsReceived) <= ZT_PEER_CREDENTIALS_CUTOFF_TIME)
  422. ++_credentialsCutoffCount;
  423. else _credentialsCutoffCount = 0;
  424. _lastCredentialsReceived = now;
  425. return (_directPathPushCutoffCount < ZT_PEER_CREDEITIALS_CUTOFF_LIMIT);
  426. }
  427. /**
  428. * Rate limit gate for sending of ERROR_NEED_MEMBERSHIP_CERTIFICATE
  429. */
  430. inline bool rateGateRequestCredentials(const int64_t now)
  431. {
  432. if ((now - _lastCredentialRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  433. _lastCredentialRequestSent = now;
  434. return true;
  435. }
  436. return false;
  437. }
  438. /**
  439. * Rate limit gate for inbound WHOIS requests
  440. */
  441. inline bool rateGateInboundWhoisRequest(const int64_t now)
  442. {
  443. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  444. _lastWhoisRequestReceived = now;
  445. return true;
  446. }
  447. return false;
  448. }
  449. /**
  450. * Rate limit gate for inbound ECHO requests
  451. */
  452. inline bool rateGateEchoRequest(const int64_t now)
  453. {
  454. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  455. _lastEchoRequestReceived = now;
  456. return true;
  457. }
  458. return false;
  459. }
  460. /**
  461. * Rate gate incoming requests for network COM
  462. */
  463. inline bool rateGateIncomingComRequest(const int64_t now)
  464. {
  465. if ((now - _lastComRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  466. _lastComRequestReceived = now;
  467. return true;
  468. }
  469. return false;
  470. }
  471. /**
  472. * Rate gate outgoing requests for network COM
  473. */
  474. inline bool rateGateOutgoingComRequest(const int64_t now)
  475. {
  476. if ((now - _lastComRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  477. _lastComRequestSent = now;
  478. return true;
  479. }
  480. return false;
  481. }
  482. /**
  483. * Rate limit gate for VERB_ACK
  484. */
  485. inline bool rateGateACK(const int64_t now)
  486. {
  487. if ((now - _lastACKWindowReset) >= ZT_PATH_QOS_ACK_CUTOFF_TIME) {
  488. _lastACKWindowReset = now;
  489. _ACKCutoffCount = 0;
  490. } else {
  491. ++_ACKCutoffCount;
  492. }
  493. return (_ACKCutoffCount < ZT_PATH_QOS_ACK_CUTOFF_LIMIT);
  494. }
  495. /**
  496. * Rate limit gate for VERB_QOS_MEASUREMENT
  497. */
  498. inline bool rateGateQoS(const int64_t now)
  499. {
  500. if ((now - _lastQoSWindowReset) >= ZT_PATH_QOS_ACK_CUTOFF_TIME) {
  501. _lastQoSWindowReset = now;
  502. _QoSCutoffCount = 0;
  503. } else {
  504. ++_QoSCutoffCount;
  505. }
  506. return (_QoSCutoffCount < ZT_PATH_QOS_ACK_CUTOFF_LIMIT);
  507. }
  508. /**
  509. * @return Whether this peer is reachable via an aggregate link
  510. */
  511. inline bool hasAggregateLink() {
  512. return _localMultipathSupported && _remoteMultipathSupported && _remotePeerMultipathEnabled;
  513. }
  514. /**
  515. * Serialize a peer for storage in local cache
  516. *
  517. * This does not serialize everything, just non-ephemeral information.
  518. */
  519. template<unsigned int C>
  520. inline void serializeForCache(Buffer<C> &b) const
  521. {
  522. b.append((uint8_t)1);
  523. _id.serialize(b);
  524. b.append((uint16_t)_vProto);
  525. b.append((uint16_t)_vMajor);
  526. b.append((uint16_t)_vMinor);
  527. b.append((uint16_t)_vRevision);
  528. {
  529. Mutex::Lock _l(_paths_m);
  530. unsigned int pc = 0;
  531. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  532. if (_paths[i].p)
  533. ++pc;
  534. else break;
  535. }
  536. b.append((uint16_t)pc);
  537. for(unsigned int i=0;i<pc;++i)
  538. _paths[i].p->address().serialize(b);
  539. }
  540. }
  541. template<unsigned int C>
  542. inline static SharedPtr<Peer> deserializeFromCache(int64_t now,void *tPtr,Buffer<C> &b,const RuntimeEnvironment *renv)
  543. {
  544. try {
  545. unsigned int ptr = 0;
  546. if (b[ptr++] != 1)
  547. return SharedPtr<Peer>();
  548. Identity id;
  549. ptr += id.deserialize(b,ptr);
  550. if (!id)
  551. return SharedPtr<Peer>();
  552. SharedPtr<Peer> p(new Peer(renv,renv->identity,id));
  553. p->_vProto = b.template at<uint16_t>(ptr); ptr += 2;
  554. p->_vMajor = b.template at<uint16_t>(ptr); ptr += 2;
  555. p->_vMinor = b.template at<uint16_t>(ptr); ptr += 2;
  556. p->_vRevision = b.template at<uint16_t>(ptr); ptr += 2;
  557. // When we deserialize from the cache we don't actually restore paths. We
  558. // just try them and then re-learn them if they happen to still be up.
  559. // Paths are fairly ephemeral in the real world in most cases.
  560. const unsigned int tryPathCount = b.template at<uint16_t>(ptr); ptr += 2;
  561. for(unsigned int i=0;i<tryPathCount;++i) {
  562. InetAddress inaddr;
  563. try {
  564. ptr += inaddr.deserialize(b,ptr);
  565. if (inaddr)
  566. p->attemptToContactAt(tPtr,-1,inaddr,now,true);
  567. } catch ( ... ) {
  568. break;
  569. }
  570. }
  571. return p;
  572. } catch ( ... ) {
  573. return SharedPtr<Peer>();
  574. }
  575. }
  576. private:
  577. struct _PeerPath
  578. {
  579. _PeerPath() : lr(0),p(),priority(1) {}
  580. int64_t lr; // time of last valid ZeroTier packet
  581. SharedPtr<Path> p;
  582. long priority; // >= 1, higher is better
  583. };
  584. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  585. const RuntimeEnvironment *RR;
  586. int64_t _lastReceive; // direct or indirect
  587. int64_t _lastNontrivialReceive; // frames, things like netconf, etc.
  588. int64_t _lastTriedMemorizedPath;
  589. int64_t _lastDirectPathPushSent;
  590. int64_t _lastDirectPathPushReceive;
  591. int64_t _lastCredentialRequestSent;
  592. int64_t _lastWhoisRequestReceived;
  593. int64_t _lastEchoRequestReceived;
  594. int64_t _lastComRequestReceived;
  595. int64_t _lastComRequestSent;
  596. int64_t _lastCredentialsReceived;
  597. int64_t _lastTrustEstablishedPacketReceived;
  598. int64_t _lastSentFullHello;
  599. int64_t _lastPathPrune;
  600. int64_t _lastACKWindowReset;
  601. int64_t _lastQoSWindowReset;
  602. int64_t _lastMultipathCompatibilityCheck;
  603. unsigned char _freeRandomByte;
  604. int _uniqueAlivePathCount;
  605. bool _localMultipathSupported;
  606. bool _remoteMultipathSupported;
  607. bool _canUseMultipath;
  608. uint16_t _vProto;
  609. uint16_t _vMajor;
  610. uint16_t _vMinor;
  611. uint16_t _vRevision;
  612. _PeerPath _paths[ZT_MAX_PEER_NETWORK_PATHS];
  613. Mutex _paths_m;
  614. Identity _id;
  615. unsigned int _directPathPushCutoffCount;
  616. unsigned int _credentialsCutoffCount;
  617. unsigned int _QoSCutoffCount;
  618. unsigned int _ACKCutoffCount;
  619. AtomicCounter __refCount;
  620. RingBuffer<int> *_pathChoiceHist;
  621. bool _linkIsBalanced;
  622. bool _linkIsRedundant;
  623. bool _remotePeerMultipathEnabled;
  624. int64_t _lastAggregateStatsReport;
  625. int64_t _lastAggregateAllocation;
  626. char _interfaceListStr[256]; // 16 characters * 16 paths in a link
  627. };
  628. } // namespace ZeroTier
  629. // Add a swap() for shared ptr's to peers to speed up peer sorts
  630. namespace std {
  631. template<>
  632. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  633. {
  634. a.swap(b);
  635. }
  636. }
  637. #endif