Peer.hpp 16 KB

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