Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 "Membership.hpp"
  38. #include "Mutex.hpp"
  39. #include "NonCopyable.hpp"
  40. #include "LockingPtr.hpp"
  41. namespace ZeroTier {
  42. /**
  43. * Peer on P2P Network (virtual layer 1)
  44. */
  45. class Peer : NonCopyable
  46. {
  47. friend class SharedPtr<Peer>;
  48. private:
  49. Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  50. public:
  51. ~Peer() { Utils::burn(_key,sizeof(_key)); }
  52. /**
  53. * Construct a new peer
  54. *
  55. * @param renv Runtime environment
  56. * @param myIdentity Identity of THIS node (for key agreement)
  57. * @param peerIdentity Identity of peer
  58. * @throws std::runtime_error Key agreement with peer's identity failed
  59. */
  60. Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity);
  61. /**
  62. * @return Time peer record was last used in any way
  63. */
  64. inline uint64_t lastUsed() const throw() { return _lastUsed; }
  65. /**
  66. * Log a use of this peer record (done by Topology when peers are looked up)
  67. *
  68. * @param now New time of last use
  69. */
  70. inline void use(uint64_t now) throw() { _lastUsed = now; }
  71. /**
  72. * @return This peer's ZT address (short for identity().address())
  73. */
  74. inline const Address &address() const throw() { return _id.address(); }
  75. /**
  76. * @return This peer's identity
  77. */
  78. inline const Identity &identity() const throw() { return _id; }
  79. /**
  80. * Log receipt of an authenticated packet
  81. *
  82. * This is called by the decode pipe when a packet is proven to be authentic
  83. * and appears to be valid.
  84. *
  85. * @param RR Runtime environment
  86. * @param localAddr Local address
  87. * @param remoteAddr Internet address of sender
  88. * @param hops ZeroTier (not IP) hops
  89. * @param packetId Packet ID
  90. * @param verb Packet verb
  91. * @param inRePacketId Packet ID in reply to (default: none)
  92. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  93. */
  94. void received(
  95. const InetAddress &localAddr,
  96. const InetAddress &remoteAddr,
  97. unsigned int hops,
  98. uint64_t packetId,
  99. Packet::Verb verb,
  100. uint64_t inRePacketId = 0,
  101. Packet::Verb inReVerb = Packet::VERB_NOP);
  102. /**
  103. * Get the current best direct path to this peer
  104. *
  105. * @param now Current time
  106. * @return Best path or NULL if there are no active direct paths
  107. */
  108. inline Path *getBestPath(uint64_t now) { return _getBestPath(now); }
  109. /**
  110. * @param now Current time
  111. * @param addr Remote address
  112. * @return True if we have an active path to this destination
  113. */
  114. inline bool hasActivePathTo(uint64_t now,const InetAddress &addr) const
  115. {
  116. for(unsigned int p=0;p<_numPaths;++p) {
  117. if ((_paths[p].active(now))&&(_paths[p].address() == addr))
  118. return true;
  119. }
  120. return false;
  121. }
  122. /**
  123. * Set all paths in the same ss_family that are not this one to cluster suboptimal
  124. *
  125. * Addresses in other families are not affected.
  126. *
  127. * @param addr Address to make exclusive
  128. */
  129. inline void setClusterOptimalPathForAddressFamily(const InetAddress &addr)
  130. {
  131. for(unsigned int p=0;p<_numPaths;++p) {
  132. if (_paths[p].address().ss_family == addr.ss_family) {
  133. _paths[p].setClusterSuboptimal(_paths[p].address() != addr);
  134. }
  135. }
  136. }
  137. /**
  138. * Send via best path
  139. *
  140. * @param data Packet data
  141. * @param len Packet length
  142. * @param now Current time
  143. * @return Path used on success or NULL on failure
  144. */
  145. inline Path *send(const void *data,unsigned int len,uint64_t now)
  146. {
  147. Path *const bestPath = getBestPath(now);
  148. if (bestPath) {
  149. if (bestPath->send(RR,data,len,now))
  150. return bestPath;
  151. }
  152. return (Path *)0;
  153. }
  154. /**
  155. * Send a HELLO to this peer at a specified physical address
  156. *
  157. * This does not update any statistics. It's used to send initial HELLOs
  158. * for NAT traversal and path verification.
  159. *
  160. * @param localAddr Local address
  161. * @param atAddress Destination address
  162. * @param now Current time
  163. * @param ttl Desired IP TTL (default: 0 to leave alone)
  164. */
  165. void sendHELLO(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int ttl = 0);
  166. /**
  167. * Send pings or keepalives depending on configured timeouts
  168. *
  169. * @param now Current time
  170. * @param inetAddressFamily Keep this address family alive, or 0 to simply pick current best ignoring family
  171. * @return True if at least one direct path seems alive
  172. */
  173. bool doPingAndKeepalive(uint64_t now,int inetAddressFamily);
  174. /**
  175. * Push direct paths back to self if we haven't done so in the configured timeout
  176. *
  177. * @param localAddr Local address
  178. * @param toAddress Remote address to send push to (usually from path)
  179. * @param now Current time
  180. * @param force If true, push regardless of rate limit
  181. * @param includePrivatePaths If true, include local interface address paths (should only be done to peers with a trust relationship)
  182. * @return True if something was actually sent
  183. */
  184. bool pushDirectPaths(const InetAddress &localAddr,const InetAddress &toAddress,uint64_t now,bool force,bool includePrivatePaths);
  185. /**
  186. * @return All known direct paths to this peer (active or inactive)
  187. */
  188. inline std::vector<Path> paths() const
  189. {
  190. std::vector<Path> pp;
  191. for(unsigned int p=0,np=_numPaths;p<np;++p)
  192. pp.push_back(_paths[p]);
  193. return pp;
  194. }
  195. /**
  196. * @return Time of last receive of anything, whether direct or relayed
  197. */
  198. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  199. /**
  200. * @return Time of most recent unicast frame received
  201. */
  202. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  203. /**
  204. * @return Time of most recent multicast frame received
  205. */
  206. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  207. /**
  208. * @return Time of most recent frame of any kind (unicast or multicast)
  209. */
  210. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  211. /**
  212. * @return True if this peer has sent us real network traffic recently
  213. */
  214. inline uint64_t activelyTransferringFrames(uint64_t now) const throw() { return ((now - lastFrame()) < ZT_PEER_ACTIVITY_TIMEOUT); }
  215. /**
  216. * @return Latency in milliseconds or 0 if unknown
  217. */
  218. inline unsigned int latency() const { return _latency; }
  219. /**
  220. * This computes a quality score for relays and root servers
  221. *
  222. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  223. * receive the worst possible quality (max unsigned int). Otherwise the
  224. * quality is a product of latency and the number of potential missed
  225. * pings. This causes roots and relays to switch over a bit faster if they
  226. * fail.
  227. *
  228. * @return Relay quality score computed from latency and other factors, lower is better
  229. */
  230. inline unsigned int relayQuality(const uint64_t now) const
  231. {
  232. const uint64_t tsr = now - _lastReceive;
  233. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  234. return (~(unsigned int)0);
  235. unsigned int l = _latency;
  236. if (!l)
  237. l = 0xffff;
  238. return (l * (((unsigned int)tsr / (ZT_PEER_DIRECT_PING_DELAY + 1000)) + 1));
  239. }
  240. /**
  241. * Update latency with a new direct measurment
  242. *
  243. * @param l Direct latency measurment in ms
  244. */
  245. inline void addDirectLatencyMeasurment(unsigned int l)
  246. {
  247. unsigned int ol = _latency;
  248. if ((ol > 0)&&(ol < 10000))
  249. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  250. else _latency = std::min(l,(unsigned int)65535);
  251. }
  252. /**
  253. * @param now Current time
  254. * @return True if this peer has at least one active direct path
  255. */
  256. inline bool hasActiveDirectPath(uint64_t now) const
  257. {
  258. for(unsigned int p=0;p<_numPaths;++p) {
  259. if (_paths[p].active(now))
  260. return true;
  261. }
  262. return false;
  263. }
  264. #ifdef ZT_ENABLE_CLUSTER
  265. /**
  266. * @param now Current time
  267. * @return True if this peer has at least one active direct path that is not cluster-suboptimal
  268. */
  269. inline bool hasClusterOptimalPath(uint64_t now) const
  270. {
  271. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  272. if ((_paths[p].active(now))&&(!_paths[p].isClusterSuboptimal()))
  273. return true;
  274. }
  275. return false;
  276. }
  277. #endif
  278. /**
  279. * Reset paths within a given scope
  280. *
  281. * @param scope IP scope of paths to reset
  282. * @param now Current time
  283. * @return True if at least one path was forgotten
  284. */
  285. bool resetWithinScope(InetAddress::IpScope scope,uint64_t now);
  286. /**
  287. * @return 256-bit secret symmetric encryption key
  288. */
  289. inline const unsigned char *key() const throw() { return _key; }
  290. /**
  291. * Set the currently known remote version of this peer's client
  292. *
  293. * @param vproto Protocol version
  294. * @param vmaj Major version
  295. * @param vmin Minor version
  296. * @param vrev Revision
  297. */
  298. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  299. {
  300. _vProto = (uint16_t)vproto;
  301. _vMajor = (uint16_t)vmaj;
  302. _vMinor = (uint16_t)vmin;
  303. _vRevision = (uint16_t)vrev;
  304. }
  305. inline unsigned int remoteVersionProtocol() const throw() { return _vProto; }
  306. inline unsigned int remoteVersionMajor() const throw() { return _vMajor; }
  307. inline unsigned int remoteVersionMinor() const throw() { return _vMinor; }
  308. inline unsigned int remoteVersionRevision() const throw() { return _vRevision; }
  309. inline bool remoteVersionKnown() const throw() { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  310. /**
  311. * Get most recently active path addresses for IPv4 and/or IPv6
  312. *
  313. * Note that v4 and v6 are not modified if they are not found, so
  314. * initialize these to a NULL address to be able to check.
  315. *
  316. * @param now Current time
  317. * @param v4 Result parameter to receive active IPv4 address, if any
  318. * @param v6 Result parameter to receive active IPv6 address, if any
  319. */
  320. void getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  321. /**
  322. * Perform periodic cleaning operations
  323. *
  324. * @param now Current time
  325. */
  326. void clean(uint64_t now);
  327. /**
  328. * Update direct path push stats and return true if we should respond
  329. *
  330. * This is a circuit breaker to make VERB_PUSH_DIRECT_PATHS not particularly
  331. * useful as a DDOS amplification attack vector. Otherwise a malicious peer
  332. * could send loads of these and cause others to bombard arbitrary IPs with
  333. * traffic.
  334. *
  335. * @param now Current time
  336. * @return True if we should respond
  337. */
  338. inline bool shouldRespondToDirectPathPush(const uint64_t now)
  339. {
  340. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  341. ++_directPathPushCutoffCount;
  342. else _directPathPushCutoffCount = 0;
  343. _lastDirectPathPushReceive = now;
  344. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  345. }
  346. /**
  347. * Get the membership record for this network, possibly creating if missing
  348. *
  349. * @param networkId Network ID
  350. * @param createIfMissing If true, create a Membership record if there isn't one
  351. * @return Single-scope locking pointer (see LockingPtr.hpp) to Membership or NULL if not found and createIfMissing is false
  352. */
  353. inline LockingPtr<Membership> membership(const uint64_t networkId,bool createIfMissing)
  354. {
  355. _memberships_m.lock();
  356. try {
  357. if (createIfMissing) {
  358. return LockingPtr<Membership>(&(_memberships[networkId]),&_memberships_m);
  359. } else {
  360. Membership *m = _memberships.get(networkId);
  361. if (m) {
  362. return LockingPtr<Membership>(m,&_memberships_m);
  363. } else {
  364. _memberships_m.unlock();
  365. return LockingPtr<Membership>();
  366. }
  367. }
  368. } catch ( ... ) {
  369. _memberships_m.unlock();
  370. throw;
  371. }
  372. }
  373. /**
  374. * Find a common set of addresses by which two peers can link, if any
  375. *
  376. * @param a Peer A
  377. * @param b Peer B
  378. * @param now Current time
  379. * @return Pair: B's address (to send to A), A's address (to send to B)
  380. */
  381. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  382. {
  383. std::pair<InetAddress,InetAddress> v4,v6;
  384. b.getBestActiveAddresses(now,v4.first,v6.first);
  385. a.getBestActiveAddresses(now,v4.second,v6.second);
  386. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  387. return v6;
  388. else if ((v4.first)&&(v4.second))
  389. return v4;
  390. else return std::pair<InetAddress,InetAddress>();
  391. }
  392. private:
  393. void _doDeadPathDetection(Path &p,const uint64_t now);
  394. Path *_getBestPath(const uint64_t now);
  395. Path *_getBestPath(const uint64_t now,int inetAddressFamily);
  396. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  397. const RuntimeEnvironment *RR;
  398. uint64_t _lastUsed;
  399. uint64_t _lastReceive; // direct or indirect
  400. uint64_t _lastUnicastFrame;
  401. uint64_t _lastMulticastFrame;
  402. uint64_t _lastAnnouncedTo;
  403. uint64_t _lastDirectPathPushSent;
  404. uint64_t _lastDirectPathPushReceive;
  405. uint64_t _lastPathSort;
  406. uint16_t _vProto;
  407. uint16_t _vMajor;
  408. uint16_t _vMinor;
  409. uint16_t _vRevision;
  410. Identity _id;
  411. Path _paths[ZT_MAX_PEER_NETWORK_PATHS];
  412. unsigned int _numPaths;
  413. unsigned int _latency;
  414. unsigned int _directPathPushCutoffCount;
  415. Hashtable<uint64_t,Membership> _memberships;
  416. Mutex _memberships_m;
  417. AtomicCounter __refCount;
  418. };
  419. } // namespace ZeroTier
  420. // Add a swap() for shared ptr's to peers to speed up peer sorts
  421. namespace std {
  422. template<>
  423. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  424. {
  425. a.swap(b);
  426. }
  427. }
  428. #endif