Peer.hpp 22 KB

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