Peer.hpp 16 KB

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