Peer.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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 <stdint.h>
  29. #include "Constants.hpp"
  30. #include <algorithm>
  31. #include <utility>
  32. #include <vector>
  33. #include <stdexcept>
  34. #include "../include/ZeroTierOne.h"
  35. #include "RuntimeEnvironment.hpp"
  36. #include "Path.hpp"
  37. #include "Address.hpp"
  38. #include "Utils.hpp"
  39. #include "Identity.hpp"
  40. #include "InetAddress.hpp"
  41. #include "Packet.hpp"
  42. #include "SharedPtr.hpp"
  43. #include "AtomicCounter.hpp"
  44. #include "Hashtable.hpp"
  45. #include "Mutex.hpp"
  46. #include "NonCopyable.hpp"
  47. namespace ZeroTier {
  48. /**
  49. * Peer on P2P Network (virtual layer 1)
  50. */
  51. class Peer : NonCopyable
  52. {
  53. friend class SharedPtr<Peer>;
  54. private:
  55. Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  56. public:
  57. ~Peer() { Utils::burn(_key,sizeof(_key)); }
  58. /**
  59. * Construct a new peer
  60. *
  61. * @param renv Runtime environment
  62. * @param myIdentity Identity of THIS node (for key agreement)
  63. * @param peerIdentity Identity of peer
  64. * @throws std::runtime_error Key agreement with peer's identity failed
  65. */
  66. Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity);
  67. /**
  68. * @return This peer's ZT address (short for identity().address())
  69. */
  70. inline const Address &address() const throw() { return _id.address(); }
  71. /**
  72. * @return This peer's identity
  73. */
  74. inline const Identity &identity() const throw() { return _id; }
  75. /**
  76. * Log receipt of an authenticated packet
  77. *
  78. * This is called by the decode pipe when a packet is proven to be authentic
  79. * and appears to be valid.
  80. *
  81. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  82. * @param path Path over which packet was received
  83. * @param hops ZeroTier (not IP) hops
  84. * @param packetId Packet ID
  85. * @param verb Packet verb
  86. * @param inRePacketId Packet ID in reply to (default: none)
  87. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  88. * @param trustEstablished If true, some form of non-trivial trust (like allowed in network) has been established
  89. */
  90. void received(
  91. void *tPtr,
  92. const SharedPtr<Path> &path,
  93. const unsigned int hops,
  94. const uint64_t packetId,
  95. const Packet::Verb verb,
  96. const uint64_t inRePacketId,
  97. const Packet::Verb inReVerb,
  98. const bool trustEstablished);
  99. /**
  100. * @param now Current time
  101. * @param addr Remote address
  102. * @return True if we have an active path to this destination
  103. */
  104. inline bool hasActivePathTo(uint64_t now,const InetAddress &addr) const
  105. {
  106. Mutex::Lock _l(_paths_m);
  107. return ( ((addr.ss_family == AF_INET)&&(_v4Path.p)&&(_v4Path.p->address() == addr)&&(_v4Path.p->alive(now))) || ((addr.ss_family == AF_INET6)&&(_v6Path.p)&&(_v6Path.p->address() == addr)&&(_v6Path.p->alive(now))) );
  108. }
  109. /**
  110. * Send via best direct path
  111. *
  112. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  113. * @param data Packet data
  114. * @param len Packet length
  115. * @param now Current time
  116. * @param force If true, send even if path is not alive
  117. * @return True if we actually sent something
  118. */
  119. bool sendDirect(void *tPtr,const void *data,unsigned int len,uint64_t now,bool force);
  120. /**
  121. * Get the best current direct path
  122. *
  123. * This does not check Path::alive(), but does return the most recently
  124. * active path and does check expiration (which is a longer timeout).
  125. *
  126. * @param now Current time
  127. * @param includeExpired If true, include even expired paths
  128. * @return Best current path or NULL if none
  129. */
  130. SharedPtr<Path> getBestPath(uint64_t now,bool includeExpired);
  131. /**
  132. * Send a HELLO to this peer at a specified physical address
  133. *
  134. * No statistics or sent times are updated here.
  135. *
  136. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  137. * @param localAddr Local address
  138. * @param atAddress Destination address
  139. * @param now Current time
  140. * @param counter Outgoing packet counter
  141. */
  142. void sendHELLO(void *tPtr,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int counter);
  143. /**
  144. * Send ECHO (or HELLO for older peers) to this peer at the given address
  145. *
  146. * No statistics or sent times are updated here.
  147. *
  148. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  149. * @param localAddr Local address
  150. * @param atAddress Destination address
  151. * @param now Current time
  152. * @param sendFullHello If true, always send a full HELLO instead of just an ECHO
  153. * @param counter Outgoing packet counter
  154. */
  155. void attemptToContactAt(void *tPtr,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,bool sendFullHello,unsigned int counter);
  156. /**
  157. * Try a memorized or statically defined path if any are known
  158. *
  159. * Under the hood this is done periodically based on ZT_TRY_MEMORIZED_PATH_INTERVAL.
  160. *
  161. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  162. * @param now Current time
  163. */
  164. void tryMemorizedPath(void *tPtr,uint64_t now);
  165. /**
  166. * Send pings or keepalives depending on configured timeouts
  167. *
  168. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  169. * @param now Current time
  170. * @param inetAddressFamily Keep this address family alive, or -1 for any
  171. * @return True if we have at least one direct path of the given family (or any if family is -1)
  172. */
  173. bool doPingAndKeepalive(void *tPtr,uint64_t now,int inetAddressFamily);
  174. /**
  175. * Reset paths within a given IP scope and address family
  176. *
  177. * Resetting a path involves sending an ECHO to it and then deactivating
  178. * it until or unless it responds.
  179. *
  180. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  181. * @param scope IP scope
  182. * @param inetAddressFamily Family e.g. AF_INET
  183. * @param now Current time
  184. */
  185. inline void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,uint64_t now)
  186. {
  187. Mutex::Lock _l(_paths_m);
  188. if ((inetAddressFamily == AF_INET)&&(_v4Path.lr)&&(_v4Path.p->address().ipScope() == scope)) {
  189. attemptToContactAt(tPtr,_v4Path.p->localAddress(),_v4Path.p->address(),now,false,_v4Path.p->nextOutgoingCounter());
  190. _v4Path.p->sent(now);
  191. _v4Path.lr = 0; // path will not be used unless it speaks again
  192. } else if ((inetAddressFamily == AF_INET6)&&(_v6Path.lr)&&(_v6Path.p->address().ipScope() == scope)) {
  193. attemptToContactAt(tPtr,_v6Path.p->localAddress(),_v6Path.p->address(),now,false,_v6Path.p->nextOutgoingCounter());
  194. _v6Path.p->sent(now);
  195. _v6Path.lr = 0; // path will not be used unless it speaks again
  196. }
  197. }
  198. /**
  199. * Indicate that the given address was provided by a cluster as a preferred destination
  200. *
  201. * @param addr Address cluster prefers that we use
  202. */
  203. inline void setClusterPreferred(const InetAddress &addr)
  204. {
  205. if (addr.ss_family == AF_INET)
  206. _v4ClusterPreferred = addr;
  207. else if (addr.ss_family == AF_INET6)
  208. _v6ClusterPreferred = addr;
  209. }
  210. /**
  211. * Fill parameters with V4 and V6 addresses if known and alive
  212. *
  213. * @param now Current time
  214. * @param v4 Result parameter to receive active IPv4 address, if any
  215. * @param v6 Result parameter to receive active IPv6 address, if any
  216. */
  217. inline void getRendezvousAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const
  218. {
  219. Mutex::Lock _l(_paths_m);
  220. if (((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION)&&(_v4Path.p->alive(now)))
  221. v4 = _v4Path.p->address();
  222. if (((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION)&&(_v6Path.p->alive(now)))
  223. v6 = _v6Path.p->address();
  224. }
  225. /**
  226. * @param now Current time
  227. * @return All known paths to this peer
  228. */
  229. inline std::vector< SharedPtr<Path> > paths(const uint64_t now) const
  230. {
  231. std::vector< SharedPtr<Path> > pp;
  232. Mutex::Lock _l(_paths_m);
  233. if (((now - _v4Path.lr) < ZT_PEER_PATH_EXPIRATION)&&(_v4Path.p->alive(now)))
  234. pp.push_back(_v4Path.p);
  235. if (((now - _v6Path.lr) < ZT_PEER_PATH_EXPIRATION)&&(_v6Path.p->alive(now)))
  236. pp.push_back(_v6Path.p);
  237. return pp;
  238. }
  239. /**
  240. * @return Time of last receive of anything, whether direct or relayed
  241. */
  242. inline uint64_t lastReceive() const { return _lastReceive; }
  243. /**
  244. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  245. */
  246. inline bool isAlive(const uint64_t now) const { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  247. /**
  248. * @return True if this peer has sent us real network traffic recently
  249. */
  250. inline uint64_t isActive(uint64_t now) const { return ((now - _lastNontrivialReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  251. /**
  252. * @return Latency in milliseconds or 0 if unknown
  253. */
  254. inline unsigned int latency() const { return _latency; }
  255. /**
  256. * This computes a quality score for relays and root servers
  257. *
  258. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  259. * receive the worst possible quality (max unsigned int). Otherwise the
  260. * quality is a product of latency and the number of potential missed
  261. * pings. This causes roots and relays to switch over a bit faster if they
  262. * fail.
  263. *
  264. * @return Relay quality score computed from latency and other factors, lower is better
  265. */
  266. inline unsigned int relayQuality(const uint64_t now) const
  267. {
  268. const uint64_t tsr = now - _lastReceive;
  269. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  270. return (~(unsigned int)0);
  271. unsigned int l = _latency;
  272. if (!l)
  273. l = 0xffff;
  274. return (l * (((unsigned int)tsr / (ZT_PEER_PING_PERIOD + 1000)) + 1));
  275. }
  276. /**
  277. * Update latency with a new direct measurment
  278. *
  279. * @param l Direct latency measurment in ms
  280. */
  281. inline void addDirectLatencyMeasurment(unsigned int l)
  282. {
  283. unsigned int ol = _latency;
  284. if ((ol > 0)&&(ol < 10000))
  285. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  286. else _latency = std::min(l,(unsigned int)65535);
  287. }
  288. #ifdef ZT_ENABLE_CLUSTER
  289. /**
  290. * @param now Current time
  291. * @return True if this peer has at least one active direct path that is not cluster-suboptimal
  292. */
  293. inline bool hasLocalClusterOptimalPath(uint64_t now) const
  294. {
  295. Mutex::Lock _l(_paths_m);
  296. return ( ((_v4Path.p)&&(_v4Path.p->alive(now))&&(!_v4Path.localClusterSuboptimal)) || ((_v6Path.p)&&(_v6Path.p->alive(now))&&(!_v6Path.localClusterSuboptimal)) );
  297. }
  298. #endif
  299. /**
  300. * @return 256-bit secret symmetric encryption key
  301. */
  302. inline const unsigned char *key() const { return _key; }
  303. /**
  304. * Set the currently known remote version of this peer's client
  305. *
  306. * @param vproto Protocol version
  307. * @param vmaj Major version
  308. * @param vmin Minor version
  309. * @param vrev Revision
  310. */
  311. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  312. {
  313. _vProto = (uint16_t)vproto;
  314. _vMajor = (uint16_t)vmaj;
  315. _vMinor = (uint16_t)vmin;
  316. _vRevision = (uint16_t)vrev;
  317. }
  318. inline unsigned int remoteVersionProtocol() const { return _vProto; }
  319. inline unsigned int remoteVersionMajor() const { return _vMajor; }
  320. inline unsigned int remoteVersionMinor() const { return _vMinor; }
  321. inline unsigned int remoteVersionRevision() const { return _vRevision; }
  322. inline bool remoteVersionKnown() const { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  323. /**
  324. * @return True if peer has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  325. */
  326. inline bool trustEstablished(const uint64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  327. /**
  328. * Rate limit gate for VERB_PUSH_DIRECT_PATHS
  329. */
  330. inline bool rateGatePushDirectPaths(const uint64_t now)
  331. {
  332. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  333. ++_directPathPushCutoffCount;
  334. else _directPathPushCutoffCount = 0;
  335. _lastDirectPathPushReceive = now;
  336. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  337. }
  338. /**
  339. * Rate limit gate for VERB_NETWORK_CREDENTIALS
  340. */
  341. inline bool rateGateCredentialsReceived(const uint64_t now)
  342. {
  343. if ((now - _lastCredentialsReceived) <= ZT_PEER_CREDENTIALS_CUTOFF_TIME)
  344. ++_credentialsCutoffCount;
  345. else _credentialsCutoffCount = 0;
  346. _lastCredentialsReceived = now;
  347. return (_directPathPushCutoffCount < ZT_PEER_CREDEITIALS_CUTOFF_LIMIT);
  348. }
  349. /**
  350. * Rate limit gate for sending of ERROR_NEED_MEMBERSHIP_CERTIFICATE
  351. */
  352. inline bool rateGateRequestCredentials(const uint64_t now)
  353. {
  354. if ((now - _lastCredentialRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  355. _lastCredentialRequestSent = now;
  356. return true;
  357. }
  358. return false;
  359. }
  360. /**
  361. * Rate limit gate for inbound WHOIS requests
  362. */
  363. inline bool rateGateInboundWhoisRequest(const uint64_t now)
  364. {
  365. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  366. _lastWhoisRequestReceived = now;
  367. return true;
  368. }
  369. return false;
  370. }
  371. /**
  372. * Rate limit gate for inbound ECHO requests
  373. */
  374. inline bool rateGateEchoRequest(const uint64_t now)
  375. {
  376. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  377. _lastEchoRequestReceived = now;
  378. return true;
  379. }
  380. return false;
  381. }
  382. /**
  383. * Rate gate incoming requests for network COM
  384. */
  385. inline bool rateGateIncomingComRequest(const uint64_t now)
  386. {
  387. if ((now - _lastComRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  388. _lastComRequestReceived = now;
  389. return true;
  390. }
  391. return false;
  392. }
  393. /**
  394. * Rate gate outgoing requests for network COM
  395. */
  396. inline bool rateGateOutgoingComRequest(const uint64_t now)
  397. {
  398. if ((now - _lastComRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  399. _lastComRequestSent = now;
  400. return true;
  401. }
  402. return false;
  403. }
  404. private:
  405. struct _PeerPath
  406. {
  407. #ifdef ZT_ENABLE_CLUSTER
  408. _PeerPath() : lr(0),p(),localClusterSuboptimal(false) {}
  409. #else
  410. _PeerPath() : lr(0),p() {}
  411. #endif
  412. uint64_t lr; // time of last valid ZeroTier packet
  413. SharedPtr<Path> p;
  414. #ifdef ZT_ENABLE_CLUSTER
  415. bool localClusterSuboptimal; // true if our cluster has determined that we should not be serving this peer
  416. #endif
  417. };
  418. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  419. const RuntimeEnvironment *RR;
  420. uint64_t _lastReceive; // direct or indirect
  421. uint64_t _lastNontrivialReceive; // frames, things like netconf, etc.
  422. uint64_t _lastTriedMemorizedPath;
  423. uint64_t _lastDirectPathPushSent;
  424. uint64_t _lastDirectPathPushReceive;
  425. uint64_t _lastCredentialRequestSent;
  426. uint64_t _lastWhoisRequestReceived;
  427. uint64_t _lastEchoRequestReceived;
  428. uint64_t _lastComRequestReceived;
  429. uint64_t _lastComRequestSent;
  430. uint64_t _lastCredentialsReceived;
  431. uint64_t _lastTrustEstablishedPacketReceived;
  432. uint16_t _vProto;
  433. uint16_t _vMajor;
  434. uint16_t _vMinor;
  435. uint16_t _vRevision;
  436. InetAddress _v4ClusterPreferred;
  437. InetAddress _v6ClusterPreferred;
  438. _PeerPath _v4Path; // IPv4 direct path
  439. _PeerPath _v6Path; // IPv6 direct path
  440. Mutex _paths_m;
  441. Identity _id;
  442. unsigned int _latency;
  443. unsigned int _directPathPushCutoffCount;
  444. unsigned int _credentialsCutoffCount;
  445. AtomicCounter __refCount;
  446. };
  447. } // namespace ZeroTier
  448. // Add a swap() for shared ptr's to peers to speed up peer sorts
  449. namespace std {
  450. template<>
  451. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  452. {
  453. a.swap(b);
  454. }
  455. }
  456. #endif