Peer.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 Time peer record was last used in any way
  61. */
  62. inline uint64_t lastUsed() const throw() { return _lastUsed; }
  63. /**
  64. * Log a use of this peer record (done by Topology when peers are looked up)
  65. *
  66. * @param now New time of last use
  67. */
  68. inline void use(uint64_t now) throw() { _lastUsed = now; }
  69. /**
  70. * @return This peer's ZT address (short for identity().address())
  71. */
  72. inline const Address &address() const throw() { return _id.address(); }
  73. /**
  74. * @return This peer's identity
  75. */
  76. inline const Identity &identity() const throw() { return _id; }
  77. /**
  78. * Log receipt of an authenticated packet
  79. *
  80. * This is called by the decode pipe when a packet is proven to be authentic
  81. * and appears to be valid.
  82. *
  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. const SharedPtr<Path> &path,
  93. unsigned int hops,
  94. uint64_t packetId,
  95. Packet::Verb verb,
  96. uint64_t inRePacketId,
  97. Packet::Verb inReVerb,
  98. const bool trustEstablished);
  99. /**
  100. * @param now Current time
  101. * @param addr Remote address
  102. * @return True if we have an active path to this destination
  103. */
  104. bool hasActivePathTo(uint64_t now,const InetAddress &addr) const;
  105. /**
  106. * Set which known path for an address family is optimal
  107. *
  108. * @param addr Address to make exclusive
  109. */
  110. inline void setClusterOptimal(const InetAddress &addr)
  111. {
  112. if (addr.ss_family == AF_INET) {
  113. _remoteClusterOptimal4 = (uint32_t)reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_addr.s_addr;
  114. } else if (addr.ss_family == AF_INET6) {
  115. memcpy(_remoteClusterOptimal6,reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_addr.s6_addr,16);
  116. }
  117. }
  118. /**
  119. * Send via best direct path
  120. *
  121. * @param data Packet data
  122. * @param len Packet length
  123. * @param now Current time
  124. * @param forceEvenIfDead If true, send even if the path is not 'alive'
  125. * @return True if we actually sent something
  126. */
  127. bool sendDirect(const void *data,unsigned int len,uint64_t now,bool forceEvenIfDead);
  128. /**
  129. * Get the best current direct path
  130. *
  131. * @param now Current time
  132. * @return Best current path or NULL if none
  133. */
  134. SharedPtr<Path> getBestPath(uint64_t now);
  135. /**
  136. * Send a HELLO to this peer at a specified physical address
  137. *
  138. * No statistics or sent times are updated here.
  139. *
  140. * @param localAddr Local address
  141. * @param atAddress Destination address
  142. * @param now Current time
  143. */
  144. void sendHELLO(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now);
  145. /**
  146. * Send pings or keepalives depending on configured timeouts
  147. *
  148. * @param now Current time
  149. * @param inetAddressFamily Keep this address family alive, or -1 for any
  150. * @return True if we have at least one direct path of the given family (or any if family is -1)
  151. */
  152. bool doPingAndKeepalive(uint64_t now,int inetAddressFamily);
  153. /**
  154. * @param now Current time
  155. * @return True if this peer has at least one active direct path
  156. */
  157. bool hasActiveDirectPath(uint64_t now) const;
  158. /**
  159. * Reset paths within a given scope
  160. *
  161. * @param scope IP scope of paths to reset
  162. * @param now Current time
  163. * @return True if at least one path was forgotten
  164. */
  165. bool resetWithinScope(InetAddress::IpScope scope,uint64_t now);
  166. /**
  167. * Get most recently active path addresses for IPv4 and/or IPv6
  168. *
  169. * Note that v4 and v6 are not modified if they are not found, so
  170. * initialize these to a NULL address to be able to check.
  171. *
  172. * @param now Current time
  173. * @param v4 Result parameter to receive active IPv4 address, if any
  174. * @param v6 Result parameter to receive active IPv6 address, if any
  175. */
  176. void getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  177. /**
  178. * Perform periodic cleaning operations
  179. *
  180. * @param now Current time
  181. */
  182. void clean(uint64_t now);
  183. /**
  184. * @return All known direct paths to this peer (active or inactive)
  185. */
  186. inline std::vector< SharedPtr<Path> > paths() const
  187. {
  188. std::vector< SharedPtr<Path> > pp;
  189. Mutex::Lock _l(_paths_m);
  190. for(unsigned int p=0,np=_numPaths;p<np;++p)
  191. pp.push_back(_paths[p].path);
  192. return pp;
  193. }
  194. /**
  195. * @return Time of last receive of anything, whether direct or relayed
  196. */
  197. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  198. /**
  199. * @return Time of most recent unicast frame received
  200. */
  201. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  202. /**
  203. * @return Time of most recent multicast frame received
  204. */
  205. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  206. /**
  207. * @return Time of most recent frame of any kind (unicast or multicast)
  208. */
  209. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  210. /**
  211. * @return True if this peer has sent us real network traffic recently
  212. */
  213. inline uint64_t activelyTransferringFrames(uint64_t now) const throw() { return ((now - lastFrame()) < 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 throw() { 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 throw() { return _vProto; }
  285. inline unsigned int remoteVersionMajor() const throw() { return _vMajor; }
  286. inline unsigned int remoteVersionMinor() const throw() { return _vMinor; }
  287. inline unsigned int remoteVersionRevision() const throw() { return _vRevision; }
  288. inline bool remoteVersionKnown() const throw() { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  289. /**
  290. * Update direct path push stats and return true if we should respond
  291. *
  292. * This is a circuit breaker to make VERB_PUSH_DIRECT_PATHS not particularly
  293. * useful as a DDOS amplification attack vector. Otherwise a malicious peer
  294. * could send loads of these and cause others to bombard arbitrary IPs with
  295. * traffic.
  296. *
  297. * @param now Current time
  298. * @return True if we should respond
  299. */
  300. inline bool shouldRespondToDirectPathPush(const uint64_t now)
  301. {
  302. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  303. ++_directPathPushCutoffCount;
  304. else _directPathPushCutoffCount = 0;
  305. _lastDirectPathPushReceive = now;
  306. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  307. }
  308. /**
  309. * Find a common set of addresses by which two peers can link, if any
  310. *
  311. * @param a Peer A
  312. * @param b Peer B
  313. * @param now Current time
  314. * @return Pair: B's address (to send to A), A's address (to send to B)
  315. */
  316. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  317. {
  318. std::pair<InetAddress,InetAddress> v4,v6;
  319. b.getBestActiveAddresses(now,v4.first,v6.first);
  320. a.getBestActiveAddresses(now,v4.second,v6.second);
  321. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  322. return v6;
  323. else if ((v4.first)&&(v4.second))
  324. return v4;
  325. else return std::pair<InetAddress,InetAddress>();
  326. }
  327. private:
  328. bool _pushDirectPaths(const SharedPtr<Path> &path,uint64_t now);
  329. inline uint64_t _pathScore(const unsigned int p) const
  330. {
  331. uint64_t s = ZT_PEER_PING_PERIOD;
  332. if (_paths[p].path->address().ss_family == AF_INET) {
  333. s += _paths[p].lastReceive + (uint64_t)(_paths[p].path->preferenceRank() * (ZT_PEER_PING_PERIOD / ZT_PATH_MAX_PREFERENCE_RANK)) + (uint64_t)(ZT_PEER_PING_PERIOD * (unsigned long)(reinterpret_cast<const struct sockaddr_in *>(&(_paths[p].path->address()))->sin_addr.s_addr == _remoteClusterOptimal4));
  334. } else if (_paths[p].path->address().ss_family == AF_INET6) {
  335. uint64_t clusterWeight = ZT_PEER_PING_PERIOD;
  336. const uint8_t *a = reinterpret_cast<const uint8_t *>(reinterpret_cast<const struct sockaddr_in6 *>(&(_paths[p].path->address()))->sin6_addr.s6_addr);
  337. for(long i=0;i<16;++i) {
  338. if (a[i] != _remoteClusterOptimal6[i]) {
  339. clusterWeight = 0;
  340. break;
  341. }
  342. }
  343. s += _paths[p].lastReceive + (uint64_t)(_paths[p].path->preferenceRank() * (ZT_PEER_PING_PERIOD / ZT_PATH_MAX_PREFERENCE_RANK)) + clusterWeight;
  344. } else {
  345. s += _paths[p].lastReceive + (uint64_t)(_paths[p].path->preferenceRank() * (ZT_PEER_PING_PERIOD / ZT_PATH_MAX_PREFERENCE_RANK));
  346. }
  347. #ifdef ZT_ENABLE_CLUSTER
  348. s -= ZT_PEER_PING_PERIOD * (uint64_t)_paths[p].localClusterSuboptimal;
  349. #endif
  350. return s;
  351. }
  352. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  353. uint8_t _remoteClusterOptimal6[16];
  354. uint64_t _lastUsed;
  355. uint64_t _lastReceive; // direct or indirect
  356. uint64_t _lastUnicastFrame;
  357. uint64_t _lastMulticastFrame;
  358. uint64_t _lastAnnouncedTo;
  359. uint64_t _lastDirectPathPushSent;
  360. uint64_t _lastDirectPathPushReceive;
  361. const RuntimeEnvironment *RR;
  362. uint32_t _remoteClusterOptimal4;
  363. uint16_t _vProto;
  364. uint16_t _vMajor;
  365. uint16_t _vMinor;
  366. uint16_t _vRevision;
  367. Identity _id;
  368. struct {
  369. uint64_t lastReceive;
  370. SharedPtr<Path> path;
  371. #ifdef ZT_ENABLE_CLUSTER
  372. bool localClusterSuboptimal;
  373. #endif
  374. } _paths[ZT_MAX_PEER_NETWORK_PATHS];
  375. Mutex _paths_m;
  376. unsigned int _numPaths;
  377. unsigned int _latency;
  378. unsigned int _directPathPushCutoffCount;
  379. AtomicCounter __refCount;
  380. };
  381. } // namespace ZeroTier
  382. // Add a swap() for shared ptr's to peers to speed up peer sorts
  383. namespace std {
  384. template<>
  385. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  386. {
  387. a.swap(b);
  388. }
  389. }
  390. #endif