Peer.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 { return _id.address(); }
  72. /**
  73. * @return This peer's identity
  74. */
  75. inline const Identity &identity() const { 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. * @param networkId Network ID if this pertains to a network, or 0 otherwise
  91. */
  92. void received(
  93. void *tPtr,
  94. const SharedPtr<Path> &path,
  95. const unsigned int hops,
  96. const uint64_t packetId,
  97. const Packet::Verb verb,
  98. const uint64_t inRePacketId,
  99. const Packet::Verb inReVerb,
  100. const bool trustEstablished,
  101. const uint64_t networkId);
  102. /**
  103. * Check whether we have an active path to this peer via the given address
  104. *
  105. * @param now Current time
  106. * @param addr Remote address
  107. * @return True if we have an active path to this destination
  108. */
  109. inline bool hasActivePathTo(int64_t now,const InetAddress &addr) const
  110. {
  111. Mutex::Lock _l(_paths_m);
  112. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  113. if (_paths[i].p) {
  114. if (((now - _paths[i].lr) < ZT_PEER_PATH_EXPIRATION)&&(_paths[i].p->address() == addr))
  115. return true;
  116. } else break;
  117. }
  118. return false;
  119. }
  120. /**
  121. * Send via best direct path
  122. *
  123. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  124. * @param data Packet data
  125. * @param len Packet length
  126. * @param now Current time
  127. * @param force If true, send even if path is not alive
  128. * @return True if we actually sent something
  129. */
  130. inline bool sendDirect(void *tPtr,const void *data,unsigned int len,int64_t now,bool force)
  131. {
  132. SharedPtr<Path> bp(getBestPath(now,force));
  133. if (bp)
  134. return bp->send(RR,tPtr,data,len,now);
  135. return false;
  136. }
  137. /**
  138. * Get the best current direct path
  139. *
  140. * @param now Current time
  141. * @param includeExpired If true, include even expired paths
  142. * @return Best current path or NULL if none
  143. */
  144. SharedPtr<Path> getBestPath(int64_t now,bool includeExpired) const;
  145. /**
  146. * Send VERB_RENDEZVOUS to this and another peer via the best common IP scope and path
  147. */
  148. void introduce(void *const tPtr,const int64_t now,const SharedPtr<Peer> &other) const;
  149. /**
  150. * Send a HELLO to this peer at a specified physical address
  151. *
  152. * No statistics or sent times are updated here.
  153. *
  154. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  155. * @param localSocket Local source socket
  156. * @param atAddress Destination address
  157. * @param now Current time
  158. * @param counter Outgoing packet counter
  159. */
  160. void sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,unsigned int counter);
  161. /**
  162. * Send ECHO (or HELLO for older peers) to this peer at the given address
  163. *
  164. * No statistics or sent times are updated here.
  165. *
  166. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  167. * @param localSocket Local source socket
  168. * @param atAddress Destination address
  169. * @param now Current time
  170. * @param sendFullHello If true, always send a full HELLO instead of just an ECHO
  171. * @param counter Outgoing packet counter
  172. */
  173. void attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello,unsigned int counter);
  174. /**
  175. * Try a memorized or statically defined path if any are known
  176. *
  177. * Under the hood this is done periodically based on ZT_TRY_MEMORIZED_PATH_INTERVAL.
  178. *
  179. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  180. * @param now Current time
  181. */
  182. void tryMemorizedPath(void *tPtr,int64_t now);
  183. /**
  184. * Send pings or keepalives depending on configured timeouts
  185. *
  186. * This also cleans up some internal data structures. It's called periodically from Node.
  187. *
  188. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  189. * @param now Current time
  190. * @param inetAddressFamily Keep this address family alive, or -1 for any
  191. * @return 0 if nothing sent or bit mask: bit 0x1 if IPv4 sent, bit 0x2 if IPv6 sent (0x3 means both sent)
  192. */
  193. unsigned int doPingAndKeepalive(void *tPtr,int64_t now);
  194. /**
  195. * Process a cluster redirect sent by this peer
  196. *
  197. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  198. * @param originatingPath Path from which redirect originated
  199. * @param remoteAddress Remote address
  200. * @param now Current time
  201. */
  202. void clusterRedirect(void *tPtr,const SharedPtr<Path> &originatingPath,const InetAddress &remoteAddress,const int64_t now);
  203. /**
  204. * Reset paths within a given IP scope and address family
  205. *
  206. * Resetting a path involves sending an ECHO to it and then deactivating
  207. * it until or unless it responds. This is done when we detect a change
  208. * to our external IP or another system change that might invalidate
  209. * many or all current paths.
  210. *
  211. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  212. * @param scope IP scope
  213. * @param inetAddressFamily Family e.g. AF_INET
  214. * @param now Current time
  215. */
  216. void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now);
  217. /**
  218. * @param now Current time
  219. * @return All known paths to this peer
  220. */
  221. inline std::vector< SharedPtr<Path> > paths(const int64_t now) const
  222. {
  223. std::vector< SharedPtr<Path> > pp;
  224. Mutex::Lock _l(_paths_m);
  225. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  226. if (!_paths[i].p) break;
  227. pp.push_back(_paths[i].p);
  228. }
  229. return pp;
  230. }
  231. /**
  232. * @return Time of last receive of anything, whether direct or relayed
  233. */
  234. inline int64_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 int64_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 int64_t isActive(int64_t now) const { return ((now - _lastNontrivialReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  243. /**
  244. * @return Latency in milliseconds of best path or 0xffff if unknown / no paths
  245. */
  246. inline unsigned int latency(const int64_t now) const
  247. {
  248. SharedPtr<Path> bp(getBestPath(now,false));
  249. if (bp)
  250. return bp->latency();
  251. return 0xffff;
  252. }
  253. /**
  254. * This computes a quality score for relays and root servers
  255. *
  256. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  257. * receive the worst possible quality (max unsigned int). Otherwise the
  258. * quality is a product of latency and the number of potential missed
  259. * pings. This causes roots and relays to switch over a bit faster if they
  260. * fail.
  261. *
  262. * @return Relay quality score computed from latency and other factors, lower is better
  263. */
  264. inline unsigned int relayQuality(const int64_t now) const
  265. {
  266. const uint64_t tsr = now - _lastReceive;
  267. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  268. return (~(unsigned int)0);
  269. unsigned int l = latency(now);
  270. if (!l)
  271. l = 0xffff;
  272. return (l * (((unsigned int)tsr / (ZT_PEER_PING_PERIOD + 1000)) + 1));
  273. }
  274. /**
  275. * @return 256-bit secret symmetric encryption key
  276. */
  277. inline const unsigned char *key() const { return _key; }
  278. /**
  279. * Set the currently known remote version of this peer's client
  280. *
  281. * @param vproto Protocol version
  282. * @param vmaj Major version
  283. * @param vmin Minor version
  284. * @param vrev Revision
  285. */
  286. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  287. {
  288. _vProto = (uint16_t)vproto;
  289. _vMajor = (uint16_t)vmaj;
  290. _vMinor = (uint16_t)vmin;
  291. _vRevision = (uint16_t)vrev;
  292. }
  293. inline unsigned int remoteVersionProtocol() const { return _vProto; }
  294. inline unsigned int remoteVersionMajor() const { return _vMajor; }
  295. inline unsigned int remoteVersionMinor() const { return _vMinor; }
  296. inline unsigned int remoteVersionRevision() const { return _vRevision; }
  297. inline bool remoteVersionKnown() const { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  298. /**
  299. * @return True if peer has received a trust established packet (e.g. common network membership) in the past ZT_TRUST_EXPIRATION ms
  300. */
  301. inline bool trustEstablished(const int64_t now) const { return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
  302. /**
  303. * Rate limit gate for VERB_PUSH_DIRECT_PATHS
  304. */
  305. inline bool rateGatePushDirectPaths(const int64_t now)
  306. {
  307. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  308. ++_directPathPushCutoffCount;
  309. else _directPathPushCutoffCount = 0;
  310. _lastDirectPathPushReceive = now;
  311. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  312. }
  313. /**
  314. * Rate limit gate for VERB_NETWORK_CREDENTIALS
  315. */
  316. inline bool rateGateCredentialsReceived(const int64_t now)
  317. {
  318. if ((now - _lastCredentialsReceived) <= ZT_PEER_CREDENTIALS_CUTOFF_TIME)
  319. ++_credentialsCutoffCount;
  320. else _credentialsCutoffCount = 0;
  321. _lastCredentialsReceived = now;
  322. return (_directPathPushCutoffCount < ZT_PEER_CREDEITIALS_CUTOFF_LIMIT);
  323. }
  324. /**
  325. * Rate limit gate for sending of ERROR_NEED_MEMBERSHIP_CERTIFICATE
  326. */
  327. inline bool rateGateRequestCredentials(const int64_t now)
  328. {
  329. if ((now - _lastCredentialRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  330. _lastCredentialRequestSent = now;
  331. return true;
  332. }
  333. return false;
  334. }
  335. /**
  336. * Rate limit gate for inbound WHOIS requests
  337. */
  338. inline bool rateGateInboundWhoisRequest(const int64_t now)
  339. {
  340. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  341. _lastWhoisRequestReceived = now;
  342. return true;
  343. }
  344. return false;
  345. }
  346. /**
  347. * Rate limit gate for inbound ECHO requests
  348. */
  349. inline bool rateGateEchoRequest(const int64_t now)
  350. {
  351. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  352. _lastEchoRequestReceived = now;
  353. return true;
  354. }
  355. return false;
  356. }
  357. /**
  358. * Rate gate incoming requests for network COM
  359. */
  360. inline bool rateGateIncomingComRequest(const int64_t now)
  361. {
  362. if ((now - _lastComRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  363. _lastComRequestReceived = now;
  364. return true;
  365. }
  366. return false;
  367. }
  368. /**
  369. * Rate gate outgoing requests for network COM
  370. */
  371. inline bool rateGateOutgoingComRequest(const int64_t now)
  372. {
  373. if ((now - _lastComRequestSent) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  374. _lastComRequestSent = now;
  375. return true;
  376. }
  377. return false;
  378. }
  379. /**
  380. * Serialize a peer for storage in local cache
  381. *
  382. * This does not serialize everything, just non-ephemeral information.
  383. */
  384. template<unsigned int C>
  385. inline void serializeForCache(Buffer<C> &b) const
  386. {
  387. b.append((uint8_t)1);
  388. _id.serialize(b);
  389. b.append((uint16_t)_vProto);
  390. b.append((uint16_t)_vMajor);
  391. b.append((uint16_t)_vMinor);
  392. b.append((uint16_t)_vRevision);
  393. {
  394. Mutex::Lock _l(_paths_m);
  395. unsigned int pc = 0;
  396. for(unsigned int i=0;i<ZT_MAX_PEER_NETWORK_PATHS;++i) {
  397. if (_paths[i].p)
  398. ++pc;
  399. else break;
  400. }
  401. b.append((uint16_t)pc);
  402. for(unsigned int i=0;i<pc;++i)
  403. _paths[i].p->address().serialize(b);
  404. }
  405. }
  406. template<unsigned int C>
  407. inline static SharedPtr<Peer> deserializeFromCache(int64_t now,void *tPtr,Buffer<C> &b,const RuntimeEnvironment *renv)
  408. {
  409. try {
  410. unsigned int ptr = 0;
  411. if (b[ptr++] != 1)
  412. return SharedPtr<Peer>();
  413. Identity id;
  414. ptr += id.deserialize(b,ptr);
  415. if (!id)
  416. return SharedPtr<Peer>();
  417. SharedPtr<Peer> p(new Peer(renv,renv->identity,id));
  418. p->_vProto = b.template at<uint16_t>(ptr); ptr += 2;
  419. p->_vMajor = b.template at<uint16_t>(ptr); ptr += 2;
  420. p->_vMinor = b.template at<uint16_t>(ptr); ptr += 2;
  421. p->_vRevision = b.template at<uint16_t>(ptr); ptr += 2;
  422. // When we deserialize from the cache we don't actually restore paths. We
  423. // just try them and then re-learn them if they happen to still be up.
  424. // Paths are fairly ephemeral in the real world in most cases.
  425. const unsigned int tryPathCount = b.template at<uint16_t>(ptr); ptr += 2;
  426. for(unsigned int i=0;i<tryPathCount;++i) {
  427. InetAddress inaddr;
  428. try {
  429. ptr += inaddr.deserialize(b,ptr);
  430. if (inaddr)
  431. p->attemptToContactAt(tPtr,-1,inaddr,now,true,0);
  432. } catch ( ... ) {
  433. break;
  434. }
  435. }
  436. return p;
  437. } catch ( ... ) {
  438. return SharedPtr<Peer>();
  439. }
  440. }
  441. private:
  442. struct _PeerPath
  443. {
  444. _PeerPath() : lr(0),p(),priority(1) {}
  445. int64_t lr; // time of last valid ZeroTier packet
  446. SharedPtr<Path> p;
  447. long priority; // >= 1, higher is better
  448. };
  449. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  450. const RuntimeEnvironment *RR;
  451. int64_t _lastReceive; // direct or indirect
  452. int64_t _lastNontrivialReceive; // frames, things like netconf, etc.
  453. int64_t _lastTriedMemorizedPath;
  454. int64_t _lastDirectPathPushSent;
  455. int64_t _lastDirectPathPushReceive;
  456. int64_t _lastCredentialRequestSent;
  457. int64_t _lastWhoisRequestReceived;
  458. int64_t _lastEchoRequestReceived;
  459. int64_t _lastComRequestReceived;
  460. int64_t _lastComRequestSent;
  461. int64_t _lastCredentialsReceived;
  462. int64_t _lastTrustEstablishedPacketReceived;
  463. int64_t _lastSentFullHello;
  464. uint16_t _vProto;
  465. uint16_t _vMajor;
  466. uint16_t _vMinor;
  467. uint16_t _vRevision;
  468. _PeerPath _paths[ZT_MAX_PEER_NETWORK_PATHS];
  469. Mutex _paths_m;
  470. Identity _id;
  471. unsigned int _directPathPushCutoffCount;
  472. unsigned int _credentialsCutoffCount;
  473. AtomicCounter __refCount;
  474. };
  475. } // namespace ZeroTier
  476. // Add a swap() for shared ptr's to peers to speed up peer sorts
  477. namespace std {
  478. template<>
  479. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  480. {
  481. a.swap(b);
  482. }
  483. }
  484. #endif