Peer.hpp 15 KB

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