Peer.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 "CertificateOfMembership.hpp"
  29. #include "Path.hpp"
  30. #include "Address.hpp"
  31. #include "Utils.hpp"
  32. #include "Identity.hpp"
  33. #include "InetAddress.hpp"
  34. #include "Packet.hpp"
  35. #include "SharedPtr.hpp"
  36. #include "AtomicCounter.hpp"
  37. #include "Hashtable.hpp"
  38. #include "Mutex.hpp"
  39. #include "NonCopyable.hpp"
  40. // Very rough computed estimate: (8 + 256 + 80 + (16 * 64) + (128 * 256) + (128 * 16))
  41. // 1048576 provides tons of headroom -- overflow would just cause peer not to be persisted
  42. #define ZT_PEER_SUGGESTED_SERIALIZATION_BUFFER_SIZE 1048576
  43. namespace ZeroTier {
  44. /**
  45. * Peer on P2P Network (virtual layer 1)
  46. */
  47. class Peer : NonCopyable
  48. {
  49. friend class SharedPtr<Peer>;
  50. private:
  51. Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  52. public:
  53. ~Peer() { Utils::burn(_key,sizeof(_key)); }
  54. /**
  55. * Construct a new peer
  56. *
  57. * @param renv Runtime environment
  58. * @param myIdentity Identity of THIS node (for key agreement)
  59. * @param peerIdentity Identity of peer
  60. * @throws std::runtime_error Key agreement with peer's identity failed
  61. */
  62. Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Identity &peerIdentity);
  63. /**
  64. * @return Time peer record was last used in any way
  65. */
  66. inline uint64_t lastUsed() const throw() { return _lastUsed; }
  67. /**
  68. * Log a use of this peer record (done by Topology when peers are looked up)
  69. *
  70. * @param now New time of last use
  71. */
  72. inline void use(uint64_t now) throw() { _lastUsed = now; }
  73. /**
  74. * @return This peer's ZT address (short for identity().address())
  75. */
  76. inline const Address &address() const throw() { return _id.address(); }
  77. /**
  78. * @return This peer's identity
  79. */
  80. inline const Identity &identity() const throw() { return _id; }
  81. /**
  82. * Log receipt of an authenticated packet
  83. *
  84. * This is called by the decode pipe when a packet is proven to be authentic
  85. * and appears to be valid.
  86. *
  87. * @param RR Runtime environment
  88. * @param localAddr Local address
  89. * @param remoteAddr Internet address of sender
  90. * @param hops ZeroTier (not IP) hops
  91. * @param packetId Packet ID
  92. * @param verb Packet verb
  93. * @param inRePacketId Packet ID in reply to (default: none)
  94. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  95. */
  96. void received(
  97. const InetAddress &localAddr,
  98. const InetAddress &remoteAddr,
  99. unsigned int hops,
  100. uint64_t packetId,
  101. Packet::Verb verb,
  102. uint64_t inRePacketId = 0,
  103. Packet::Verb inReVerb = Packet::VERB_NOP);
  104. /**
  105. * Get the current best direct path to this peer
  106. *
  107. * @param now Current time
  108. * @return Best path or NULL if there are no active direct paths
  109. */
  110. inline Path *getBestPath(uint64_t now) { return _getBestPath(now); }
  111. /**
  112. * Send via best path
  113. *
  114. * @param data Packet data
  115. * @param len Packet length
  116. * @param now Current time
  117. * @return Path used on success or NULL on failure
  118. */
  119. inline Path *send(const void *data,unsigned int len,uint64_t now)
  120. {
  121. Path *const bestPath = getBestPath(now);
  122. if (bestPath) {
  123. if (bestPath->send(RR,data,len,now))
  124. return bestPath;
  125. }
  126. return (Path *)0;
  127. }
  128. /**
  129. * Send a HELLO to this peer at a specified physical address
  130. *
  131. * This does not update any statistics. It's used to send initial HELLOs
  132. * for NAT traversal and path verification.
  133. *
  134. * @param localAddr Local address
  135. * @param atAddress Destination address
  136. * @param now Current time
  137. * @param ttl Desired IP TTL (default: 0 to leave alone)
  138. */
  139. void sendHELLO(const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now,unsigned int ttl = 0);
  140. /**
  141. * Send pings or keepalives depending on configured timeouts
  142. *
  143. * @param now Current time
  144. * @param inetAddressFamily Keep this address family alive, or 0 to simply pick current best ignoring family
  145. * @return True if at least one direct path seems alive
  146. */
  147. bool doPingAndKeepalive(uint64_t now,int inetAddressFamily);
  148. /**
  149. * Push direct paths back to self if we haven't done so in the configured timeout
  150. *
  151. * @param path Remote path to use to send the push
  152. * @param now Current time
  153. * @param force If true, push regardless of rate limit
  154. */
  155. void pushDirectPaths(Path *path,uint64_t now,bool force);
  156. /**
  157. * @return All known direct paths to this peer (active or inactive)
  158. */
  159. inline std::vector<Path> paths() const
  160. {
  161. std::vector<Path> pp;
  162. for(unsigned int p=0,np=_numPaths;p<np;++p)
  163. pp.push_back(_paths[p]);
  164. return pp;
  165. }
  166. /**
  167. * @return Time of last receive of anything, whether direct or relayed
  168. */
  169. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  170. /**
  171. * @return Time of most recent unicast frame received
  172. */
  173. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  174. /**
  175. * @return Time of most recent multicast frame received
  176. */
  177. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  178. /**
  179. * @return Time of most recent frame of any kind (unicast or multicast)
  180. */
  181. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  182. /**
  183. * @return True if this peer has sent us real network traffic recently
  184. */
  185. inline uint64_t activelyTransferringFrames(uint64_t now) const throw() { return ((now - lastFrame()) < ZT_PEER_ACTIVITY_TIMEOUT); }
  186. /**
  187. * @return Latency in milliseconds or 0 if unknown
  188. */
  189. inline unsigned int latency() const { return _latency; }
  190. /**
  191. * This computes a quality score for relays and root servers
  192. *
  193. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  194. * receive the worst possible quality (max unsigned int). Otherwise the
  195. * quality is a product of latency and the number of potential missed
  196. * pings. This causes roots and relays to switch over a bit faster if they
  197. * fail.
  198. *
  199. * @return Relay quality score computed from latency and other factors, lower is better
  200. */
  201. inline unsigned int relayQuality(const uint64_t now) const
  202. {
  203. const uint64_t tsr = now - _lastReceive;
  204. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  205. return (~(unsigned int)0);
  206. unsigned int l = _latency;
  207. if (!l)
  208. l = 0xffff;
  209. return (l * (((unsigned int)tsr / (ZT_PEER_DIRECT_PING_DELAY + 1000)) + 1));
  210. }
  211. /**
  212. * Update latency with a new direct measurment
  213. *
  214. * @param l Direct latency measurment in ms
  215. */
  216. inline void addDirectLatencyMeasurment(unsigned int l)
  217. {
  218. unsigned int ol = _latency;
  219. if ((ol > 0)&&(ol < 10000))
  220. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  221. else _latency = std::min(l,(unsigned int)65535);
  222. }
  223. /**
  224. * @param now Current time
  225. * @return True if this peer has at least one active direct path
  226. */
  227. inline bool hasActiveDirectPath(uint64_t now) const
  228. {
  229. for(unsigned int p=0;p<_numPaths;++p) {
  230. if (_paths[p].active(now))
  231. return true;
  232. }
  233. return false;
  234. }
  235. #ifdef ZT_ENABLE_CLUSTER
  236. /**
  237. * @param now Current time
  238. * @return True if this peer has at least one active direct path that is not cluster-suboptimal
  239. */
  240. inline bool hasClusterOptimalPath(uint64_t now) const
  241. {
  242. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  243. if ((_paths[p].active(now))&&(!_paths[p].isClusterSuboptimal()))
  244. return true;
  245. }
  246. return false;
  247. }
  248. #endif
  249. /**
  250. * @param now Current time
  251. * @param addr Remote address
  252. * @return True if peer currently has an active direct path to addr
  253. */
  254. inline bool hasActivePathTo(uint64_t now,const InetAddress &addr) const
  255. {
  256. for(unsigned int p=0;p<_numPaths;++p) {
  257. if ((_paths[p].active(now))&&(_paths[p].address() == addr))
  258. return true;
  259. }
  260. return false;
  261. }
  262. /**
  263. * Reset paths within a given scope
  264. *
  265. * @param scope IP scope of paths to reset
  266. * @param now Current time
  267. * @return True if at least one path was forgotten
  268. */
  269. bool resetWithinScope(InetAddress::IpScope scope,uint64_t now);
  270. /**
  271. * @return 256-bit secret symmetric encryption key
  272. */
  273. inline const unsigned char *key() const throw() { return _key; }
  274. /**
  275. * Set the currently known remote version of this peer's client
  276. *
  277. * @param vproto Protocol version
  278. * @param vmaj Major version
  279. * @param vmin Minor version
  280. * @param vrev Revision
  281. */
  282. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  283. {
  284. _vProto = (uint16_t)vproto;
  285. _vMajor = (uint16_t)vmaj;
  286. _vMinor = (uint16_t)vmin;
  287. _vRevision = (uint16_t)vrev;
  288. }
  289. inline unsigned int remoteVersionProtocol() const throw() { return _vProto; }
  290. inline unsigned int remoteVersionMajor() const throw() { return _vMajor; }
  291. inline unsigned int remoteVersionMinor() const throw() { return _vMinor; }
  292. inline unsigned int remoteVersionRevision() const throw() { return _vRevision; }
  293. inline bool remoteVersionKnown() const throw() { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  294. /**
  295. * Get most recently active path addresses for IPv4 and/or IPv6
  296. *
  297. * Note that v4 and v6 are not modified if they are not found, so
  298. * initialize these to a NULL address to be able to check.
  299. *
  300. * @param now Current time
  301. * @param v4 Result parameter to receive active IPv4 address, if any
  302. * @param v6 Result parameter to receive active IPv6 address, if any
  303. */
  304. void getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  305. /**
  306. * Check network COM agreement with this peer
  307. *
  308. * @param nwid Network ID
  309. * @param com Another certificate of membership
  310. * @return True if supplied COM agrees with ours, false if not or if we don't have one
  311. */
  312. bool networkMembershipCertificatesAgree(uint64_t nwid,const CertificateOfMembership &com) const;
  313. /**
  314. * Check the validity of the COM and add/update if valid and new
  315. *
  316. * @param nwid Network ID
  317. * @param com Externally supplied COM
  318. */
  319. bool validateAndSetNetworkMembershipCertificate(uint64_t nwid,const CertificateOfMembership &com);
  320. /**
  321. * @param nwid Network ID
  322. * @param now Current time
  323. * @param updateLastPushedTime If true, go ahead and update the last pushed time regardless of return value
  324. * @return Whether or not this peer needs another COM push from us
  325. */
  326. bool needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool updateLastPushedTime);
  327. /**
  328. * Perform periodic cleaning operations
  329. *
  330. * @param now Current time
  331. */
  332. void clean(uint64_t now);
  333. /**
  334. * Update direct path push stats and return true if we should respond
  335. *
  336. * This is a circuit breaker to make VERB_PUSH_DIRECT_PATHS not particularly
  337. * useful as a DDOS amplification attack vector. Otherwise a malicious peer
  338. * could send loads of these and cause others to bombard arbitrary IPs with
  339. * traffic.
  340. *
  341. * @param now Current time
  342. * @return True if we should respond
  343. */
  344. inline bool shouldRespondToDirectPathPush(const uint64_t now)
  345. {
  346. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  347. ++_directPathPushCutoffCount;
  348. else _directPathPushCutoffCount = 0;
  349. _lastDirectPathPushReceive = now;
  350. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  351. }
  352. /**
  353. * Find a common set of addresses by which two peers can link, if any
  354. *
  355. * @param a Peer A
  356. * @param b Peer B
  357. * @param now Current time
  358. * @return Pair: B's address (to send to A), A's address (to send to B)
  359. */
  360. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  361. {
  362. std::pair<InetAddress,InetAddress> v4,v6;
  363. b.getBestActiveAddresses(now,v4.first,v6.first);
  364. a.getBestActiveAddresses(now,v4.second,v6.second);
  365. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  366. return v6;
  367. else if ((v4.first)&&(v4.second))
  368. return v4;
  369. else return std::pair<InetAddress,InetAddress>();
  370. }
  371. template<unsigned int C>
  372. inline void serialize(Buffer<C> &b) const
  373. {
  374. Mutex::Lock _l(_networkComs_m);
  375. const unsigned int recSizePos = b.size();
  376. b.addSize(4); // space for uint32_t field length
  377. b.append((uint16_t)1); // version of serialized Peer data
  378. _id.serialize(b,false);
  379. b.append((uint64_t)_lastUsed);
  380. b.append((uint64_t)_lastReceive);
  381. b.append((uint64_t)_lastUnicastFrame);
  382. b.append((uint64_t)_lastMulticastFrame);
  383. b.append((uint64_t)_lastAnnouncedTo);
  384. b.append((uint64_t)_lastDirectPathPushSent);
  385. b.append((uint64_t)_lastDirectPathPushReceive);
  386. b.append((uint64_t)_lastPathSort);
  387. b.append((uint16_t)_vProto);
  388. b.append((uint16_t)_vMajor);
  389. b.append((uint16_t)_vMinor);
  390. b.append((uint16_t)_vRevision);
  391. b.append((uint32_t)_latency);
  392. b.append((uint16_t)_directPathPushCutoffCount);
  393. b.append((uint16_t)_numPaths);
  394. for(unsigned int i=0;i<_numPaths;++i)
  395. _paths[i].serialize(b);
  396. b.append((uint32_t)_networkComs.size());
  397. {
  398. uint64_t *k = (uint64_t *)0;
  399. _NetworkCom *v = (_NetworkCom *)0;
  400. Hashtable<uint64_t,_NetworkCom>::Iterator i(const_cast<Peer *>(this)->_networkComs);
  401. while (i.next(k,v)) {
  402. b.append((uint64_t)*k);
  403. b.append((uint64_t)v->ts);
  404. v->com.serialize(b);
  405. }
  406. }
  407. b.append((uint32_t)_lastPushedComs.size());
  408. {
  409. uint64_t *k = (uint64_t *)0;
  410. uint64_t *v = (uint64_t *)0;
  411. Hashtable<uint64_t,uint64_t>::Iterator i(const_cast<Peer *>(this)->_lastPushedComs);
  412. while (i.next(k,v)) {
  413. b.append((uint64_t)*k);
  414. b.append((uint64_t)*v);
  415. }
  416. }
  417. b.template setAt<uint32_t>(recSizePos,(uint32_t)(b.size() - (recSizePos + 4))); // set size
  418. }
  419. /**
  420. * Create a new Peer from a serialized instance
  421. *
  422. * @param renv Runtime environment
  423. * @param myIdentity This node's identity
  424. * @param b Buffer containing serialized Peer data
  425. * @param p Pointer to current position in buffer, will be updated in place as buffer is read (value/result)
  426. * @return New instance of Peer or NULL if serialized data was corrupt or otherwise invalid (may also throw an exception via Buffer)
  427. */
  428. template<unsigned int C>
  429. static inline SharedPtr<Peer> deserializeNew(const RuntimeEnvironment *renv,const Identity &myIdentity,const Buffer<C> &b,unsigned int &p)
  430. {
  431. const unsigned int recSize = b.template at<uint32_t>(p); p += 4;
  432. if ((p + recSize) > b.size())
  433. return SharedPtr<Peer>(); // size invalid
  434. if (b.template at<uint16_t>(p) != 1)
  435. return SharedPtr<Peer>(); // version mismatch
  436. p += 2;
  437. Identity npid;
  438. p += npid.deserialize(b,p);
  439. if (!npid)
  440. return SharedPtr<Peer>();
  441. SharedPtr<Peer> np(new Peer(renv,myIdentity,npid));
  442. np->_lastUsed = b.template at<uint64_t>(p); p += 8;
  443. np->_lastReceive = b.template at<uint64_t>(p); p += 8;
  444. np->_lastUnicastFrame = b.template at<uint64_t>(p); p += 8;
  445. np->_lastMulticastFrame = b.template at<uint64_t>(p); p += 8;
  446. np->_lastAnnouncedTo = b.template at<uint64_t>(p); p += 8;
  447. np->_lastDirectPathPushSent = b.template at<uint64_t>(p); p += 8;
  448. np->_lastDirectPathPushReceive = b.template at<uint64_t>(p); p += 8;
  449. np->_lastPathSort = b.template at<uint64_t>(p); p += 8;
  450. np->_vProto = b.template at<uint16_t>(p); p += 2;
  451. np->_vMajor = b.template at<uint16_t>(p); p += 2;
  452. np->_vMinor = b.template at<uint16_t>(p); p += 2;
  453. np->_vRevision = b.template at<uint16_t>(p); p += 2;
  454. np->_latency = b.template at<uint32_t>(p); p += 4;
  455. np->_directPathPushCutoffCount = b.template at<uint16_t>(p); p += 2;
  456. const unsigned int numPaths = b.template at<uint16_t>(p); p += 2;
  457. for(unsigned int i=0;i<numPaths;++i) {
  458. if (i < ZT_MAX_PEER_NETWORK_PATHS) {
  459. p += np->_paths[np->_numPaths++].deserialize(b,p);
  460. } else {
  461. // Skip any paths beyond max, but still read stream
  462. Path foo;
  463. p += foo.deserialize(b,p);
  464. }
  465. }
  466. const unsigned int numNetworkComs = b.template at<uint32_t>(p); p += 4;
  467. for(unsigned int i=0;i<numNetworkComs;++i) {
  468. _NetworkCom &c = np->_networkComs[b.template at<uint64_t>(p)]; p += 8;
  469. c.ts = b.template at<uint64_t>(p); p += 8;
  470. p += c.com.deserialize(b,p);
  471. }
  472. const unsigned int numLastPushed = b.template at<uint32_t>(p); p += 4;
  473. for(unsigned int i=0;i<numLastPushed;++i) {
  474. const uint64_t nwid = b.template at<uint64_t>(p); p += 8;
  475. const uint64_t ts = b.template at<uint64_t>(p); p += 8;
  476. np->_lastPushedComs.set(nwid,ts);
  477. }
  478. return np;
  479. }
  480. private:
  481. bool _checkPath(Path &p,const uint64_t now);
  482. Path *_getBestPath(const uint64_t now);
  483. Path *_getBestPath(const uint64_t now,int inetAddressFamily);
  484. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH]; // computed with key agreement, not serialized
  485. const RuntimeEnvironment *RR;
  486. uint64_t _lastUsed;
  487. uint64_t _lastReceive; // direct or indirect
  488. uint64_t _lastUnicastFrame;
  489. uint64_t _lastMulticastFrame;
  490. uint64_t _lastAnnouncedTo;
  491. uint64_t _lastDirectPathPushSent;
  492. uint64_t _lastDirectPathPushReceive;
  493. uint64_t _lastPathSort;
  494. uint16_t _vProto;
  495. uint16_t _vMajor;
  496. uint16_t _vMinor;
  497. uint16_t _vRevision;
  498. Identity _id;
  499. Path _paths[ZT_MAX_PEER_NETWORK_PATHS];
  500. unsigned int _numPaths;
  501. unsigned int _latency;
  502. unsigned int _directPathPushCutoffCount;
  503. struct _NetworkCom
  504. {
  505. _NetworkCom() {}
  506. _NetworkCom(uint64_t t,const CertificateOfMembership &c) : ts(t),com(c) {}
  507. uint64_t ts;
  508. CertificateOfMembership com;
  509. };
  510. Hashtable<uint64_t,_NetworkCom> _networkComs;
  511. Hashtable<uint64_t,uint64_t> _lastPushedComs;
  512. Mutex _networkComs_m;
  513. AtomicCounter __refCount;
  514. };
  515. } // namespace ZeroTier
  516. // Add a swap() for shared ptr's to peers to speed up peer sorts
  517. namespace std {
  518. template<>
  519. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  520. {
  521. a.swap(b);
  522. }
  523. }
  524. #endif