Peer.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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 localAddr Local address
  152. * @param toAddress Remote address to send push to (usually from path)
  153. * @param now Current time
  154. * @param force If true, push regardless of rate limit
  155. * @return True if something was actually sent
  156. */
  157. bool pushDirectPaths(const InetAddress &localAddr,const InetAddress &toAddress,uint64_t now,bool force);
  158. /**
  159. * @return All known direct paths to this peer (active or inactive)
  160. */
  161. inline std::vector<Path> paths() const
  162. {
  163. std::vector<Path> pp;
  164. for(unsigned int p=0,np=_numPaths;p<np;++p)
  165. pp.push_back(_paths[p]);
  166. return pp;
  167. }
  168. /**
  169. * @return Time of last receive of anything, whether direct or relayed
  170. */
  171. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  172. /**
  173. * @return Time of most recent unicast frame received
  174. */
  175. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  176. /**
  177. * @return Time of most recent multicast frame received
  178. */
  179. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  180. /**
  181. * @return Time of most recent frame of any kind (unicast or multicast)
  182. */
  183. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  184. /**
  185. * @return True if this peer has sent us real network traffic recently
  186. */
  187. inline uint64_t activelyTransferringFrames(uint64_t now) const throw() { return ((now - lastFrame()) < ZT_PEER_ACTIVITY_TIMEOUT); }
  188. /**
  189. * @return Latency in milliseconds or 0 if unknown
  190. */
  191. inline unsigned int latency() const { return _latency; }
  192. /**
  193. * This computes a quality score for relays and root servers
  194. *
  195. * If we haven't heard anything from these in ZT_PEER_ACTIVITY_TIMEOUT, they
  196. * receive the worst possible quality (max unsigned int). Otherwise the
  197. * quality is a product of latency and the number of potential missed
  198. * pings. This causes roots and relays to switch over a bit faster if they
  199. * fail.
  200. *
  201. * @return Relay quality score computed from latency and other factors, lower is better
  202. */
  203. inline unsigned int relayQuality(const uint64_t now) const
  204. {
  205. const uint64_t tsr = now - _lastReceive;
  206. if (tsr >= ZT_PEER_ACTIVITY_TIMEOUT)
  207. return (~(unsigned int)0);
  208. unsigned int l = _latency;
  209. if (!l)
  210. l = 0xffff;
  211. return (l * (((unsigned int)tsr / (ZT_PEER_DIRECT_PING_DELAY + 1000)) + 1));
  212. }
  213. /**
  214. * Update latency with a new direct measurment
  215. *
  216. * @param l Direct latency measurment in ms
  217. */
  218. inline void addDirectLatencyMeasurment(unsigned int l)
  219. {
  220. unsigned int ol = _latency;
  221. if ((ol > 0)&&(ol < 10000))
  222. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  223. else _latency = std::min(l,(unsigned int)65535);
  224. }
  225. /**
  226. * @param now Current time
  227. * @return True if this peer has at least one active direct path
  228. */
  229. inline bool hasActiveDirectPath(uint64_t now) const
  230. {
  231. for(unsigned int p=0;p<_numPaths;++p) {
  232. if (_paths[p].active(now))
  233. return true;
  234. }
  235. return false;
  236. }
  237. #ifdef ZT_ENABLE_CLUSTER
  238. /**
  239. * @param now Current time
  240. * @return True if this peer has at least one active direct path that is not cluster-suboptimal
  241. */
  242. inline bool hasClusterOptimalPath(uint64_t now) const
  243. {
  244. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  245. if ((_paths[p].active(now))&&(!_paths[p].isClusterSuboptimal()))
  246. return true;
  247. }
  248. return false;
  249. }
  250. #endif
  251. /**
  252. * @param now Current time
  253. * @param addr Remote address
  254. * @return True if peer currently has an active direct path to addr
  255. */
  256. inline bool hasActivePathTo(uint64_t now,const InetAddress &addr) const
  257. {
  258. for(unsigned int p=0;p<_numPaths;++p) {
  259. if ((_paths[p].active(now))&&(_paths[p].address() == addr))
  260. return true;
  261. }
  262. return false;
  263. }
  264. /**
  265. * Reset paths within a given scope
  266. *
  267. * @param scope IP scope of paths to reset
  268. * @param now Current time
  269. * @return True if at least one path was forgotten
  270. */
  271. bool resetWithinScope(InetAddress::IpScope scope,uint64_t now);
  272. /**
  273. * @return 256-bit secret symmetric encryption key
  274. */
  275. inline const unsigned char *key() const throw() { return _key; }
  276. /**
  277. * Set the currently known remote version of this peer's client
  278. *
  279. * @param vproto Protocol version
  280. * @param vmaj Major version
  281. * @param vmin Minor version
  282. * @param vrev Revision
  283. */
  284. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  285. {
  286. _vProto = (uint16_t)vproto;
  287. _vMajor = (uint16_t)vmaj;
  288. _vMinor = (uint16_t)vmin;
  289. _vRevision = (uint16_t)vrev;
  290. }
  291. inline unsigned int remoteVersionProtocol() const throw() { return _vProto; }
  292. inline unsigned int remoteVersionMajor() const throw() { return _vMajor; }
  293. inline unsigned int remoteVersionMinor() const throw() { return _vMinor; }
  294. inline unsigned int remoteVersionRevision() const throw() { return _vRevision; }
  295. inline bool remoteVersionKnown() const throw() { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  296. /**
  297. * Get most recently active path addresses for IPv4 and/or IPv6
  298. *
  299. * Note that v4 and v6 are not modified if they are not found, so
  300. * initialize these to a NULL address to be able to check.
  301. *
  302. * @param now Current time
  303. * @param v4 Result parameter to receive active IPv4 address, if any
  304. * @param v6 Result parameter to receive active IPv6 address, if any
  305. */
  306. void getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  307. /**
  308. * Check network COM agreement with this peer
  309. *
  310. * @param nwid Network ID
  311. * @param com Another certificate of membership
  312. * @return True if supplied COM agrees with ours, false if not or if we don't have one
  313. */
  314. bool networkMembershipCertificatesAgree(uint64_t nwid,const CertificateOfMembership &com) const;
  315. /**
  316. * Check the validity of the COM and add/update if valid and new
  317. *
  318. * @param nwid Network ID
  319. * @param com Externally supplied COM
  320. */
  321. bool validateAndSetNetworkMembershipCertificate(uint64_t nwid,const CertificateOfMembership &com);
  322. /**
  323. * @param nwid Network ID
  324. * @param now Current time
  325. * @param updateLastPushedTime If true, go ahead and update the last pushed time regardless of return value
  326. * @return Whether or not this peer needs another COM push from us
  327. */
  328. bool needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool updateLastPushedTime);
  329. /**
  330. * Perform periodic cleaning operations
  331. *
  332. * @param now Current time
  333. */
  334. void clean(uint64_t now);
  335. /**
  336. * Update direct path push stats and return true if we should respond
  337. *
  338. * This is a circuit breaker to make VERB_PUSH_DIRECT_PATHS not particularly
  339. * useful as a DDOS amplification attack vector. Otherwise a malicious peer
  340. * could send loads of these and cause others to bombard arbitrary IPs with
  341. * traffic.
  342. *
  343. * @param now Current time
  344. * @return True if we should respond
  345. */
  346. inline bool shouldRespondToDirectPathPush(const uint64_t now)
  347. {
  348. if ((now - _lastDirectPathPushReceive) <= ZT_PUSH_DIRECT_PATHS_CUTOFF_TIME)
  349. ++_directPathPushCutoffCount;
  350. else _directPathPushCutoffCount = 0;
  351. _lastDirectPathPushReceive = now;
  352. return (_directPathPushCutoffCount < ZT_PUSH_DIRECT_PATHS_CUTOFF_LIMIT);
  353. }
  354. /**
  355. * Find a common set of addresses by which two peers can link, if any
  356. *
  357. * @param a Peer A
  358. * @param b Peer B
  359. * @param now Current time
  360. * @return Pair: B's address (to send to A), A's address (to send to B)
  361. */
  362. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  363. {
  364. std::pair<InetAddress,InetAddress> v4,v6;
  365. b.getBestActiveAddresses(now,v4.first,v6.first);
  366. a.getBestActiveAddresses(now,v4.second,v6.second);
  367. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  368. return v6;
  369. else if ((v4.first)&&(v4.second))
  370. return v4;
  371. else return std::pair<InetAddress,InetAddress>();
  372. }
  373. template<unsigned int C>
  374. inline void serialize(Buffer<C> &b) const
  375. {
  376. Mutex::Lock _l(_networkComs_m);
  377. const unsigned int recSizePos = b.size();
  378. b.addSize(4); // space for uint32_t field length
  379. b.append((uint16_t)1); // version of serialized Peer data
  380. _id.serialize(b,false);
  381. b.append((uint64_t)_lastUsed);
  382. b.append((uint64_t)_lastReceive);
  383. b.append((uint64_t)_lastUnicastFrame);
  384. b.append((uint64_t)_lastMulticastFrame);
  385. b.append((uint64_t)_lastAnnouncedTo);
  386. b.append((uint64_t)_lastDirectPathPushSent);
  387. b.append((uint64_t)_lastDirectPathPushReceive);
  388. b.append((uint64_t)_lastPathSort);
  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. b.append((uint32_t)_latency);
  394. b.append((uint16_t)_directPathPushCutoffCount);
  395. b.append((uint16_t)_numPaths);
  396. for(unsigned int i=0;i<_numPaths;++i)
  397. _paths[i].serialize(b);
  398. b.append((uint32_t)_networkComs.size());
  399. {
  400. uint64_t *k = (uint64_t *)0;
  401. _NetworkCom *v = (_NetworkCom *)0;
  402. Hashtable<uint64_t,_NetworkCom>::Iterator i(const_cast<Peer *>(this)->_networkComs);
  403. while (i.next(k,v)) {
  404. b.append((uint64_t)*k);
  405. b.append((uint64_t)v->ts);
  406. v->com.serialize(b);
  407. }
  408. }
  409. b.append((uint32_t)_lastPushedComs.size());
  410. {
  411. uint64_t *k = (uint64_t *)0;
  412. uint64_t *v = (uint64_t *)0;
  413. Hashtable<uint64_t,uint64_t>::Iterator i(const_cast<Peer *>(this)->_lastPushedComs);
  414. while (i.next(k,v)) {
  415. b.append((uint64_t)*k);
  416. b.append((uint64_t)*v);
  417. }
  418. }
  419. b.template setAt<uint32_t>(recSizePos,(uint32_t)(b.size() - (recSizePos + 4))); // set size
  420. }
  421. /**
  422. * Create a new Peer from a serialized instance
  423. *
  424. * @param renv Runtime environment
  425. * @param myIdentity This node's identity
  426. * @param b Buffer containing serialized Peer data
  427. * @param p Pointer to current position in buffer, will be updated in place as buffer is read (value/result)
  428. * @return New instance of Peer or NULL if serialized data was corrupt or otherwise invalid (may also throw an exception via Buffer)
  429. */
  430. template<unsigned int C>
  431. static inline SharedPtr<Peer> deserializeNew(const RuntimeEnvironment *renv,const Identity &myIdentity,const Buffer<C> &b,unsigned int &p)
  432. {
  433. const unsigned int recSize = b.template at<uint32_t>(p); p += 4;
  434. if ((p + recSize) > b.size())
  435. return SharedPtr<Peer>(); // size invalid
  436. if (b.template at<uint16_t>(p) != 1)
  437. return SharedPtr<Peer>(); // version mismatch
  438. p += 2;
  439. Identity npid;
  440. p += npid.deserialize(b,p);
  441. if (!npid)
  442. return SharedPtr<Peer>();
  443. SharedPtr<Peer> np(new Peer(renv,myIdentity,npid));
  444. np->_lastUsed = b.template at<uint64_t>(p); p += 8;
  445. np->_lastReceive = b.template at<uint64_t>(p); p += 8;
  446. np->_lastUnicastFrame = b.template at<uint64_t>(p); p += 8;
  447. np->_lastMulticastFrame = b.template at<uint64_t>(p); p += 8;
  448. np->_lastAnnouncedTo = b.template at<uint64_t>(p); p += 8;
  449. np->_lastDirectPathPushSent = b.template at<uint64_t>(p); p += 8;
  450. np->_lastDirectPathPushReceive = b.template at<uint64_t>(p); p += 8;
  451. np->_lastPathSort = b.template at<uint64_t>(p); p += 8;
  452. np->_vProto = b.template at<uint16_t>(p); p += 2;
  453. np->_vMajor = b.template at<uint16_t>(p); p += 2;
  454. np->_vMinor = b.template at<uint16_t>(p); p += 2;
  455. np->_vRevision = b.template at<uint16_t>(p); p += 2;
  456. np->_latency = b.template at<uint32_t>(p); p += 4;
  457. np->_directPathPushCutoffCount = b.template at<uint16_t>(p); p += 2;
  458. const unsigned int numPaths = b.template at<uint16_t>(p); p += 2;
  459. for(unsigned int i=0;i<numPaths;++i) {
  460. if (i < ZT_MAX_PEER_NETWORK_PATHS) {
  461. p += np->_paths[np->_numPaths++].deserialize(b,p);
  462. } else {
  463. // Skip any paths beyond max, but still read stream
  464. Path foo;
  465. p += foo.deserialize(b,p);
  466. }
  467. }
  468. const unsigned int numNetworkComs = b.template at<uint32_t>(p); p += 4;
  469. for(unsigned int i=0;i<numNetworkComs;++i) {
  470. _NetworkCom &c = np->_networkComs[b.template at<uint64_t>(p)]; p += 8;
  471. c.ts = b.template at<uint64_t>(p); p += 8;
  472. p += c.com.deserialize(b,p);
  473. }
  474. const unsigned int numLastPushed = b.template at<uint32_t>(p); p += 4;
  475. for(unsigned int i=0;i<numLastPushed;++i) {
  476. const uint64_t nwid = b.template at<uint64_t>(p); p += 8;
  477. const uint64_t ts = b.template at<uint64_t>(p); p += 8;
  478. np->_lastPushedComs.set(nwid,ts);
  479. }
  480. return np;
  481. }
  482. private:
  483. bool _checkPath(Path &p,const uint64_t now);
  484. Path *_getBestPath(const uint64_t now);
  485. Path *_getBestPath(const uint64_t now,int inetAddressFamily);
  486. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH]; // computed with key agreement, not serialized
  487. const RuntimeEnvironment *RR;
  488. uint64_t _lastUsed;
  489. uint64_t _lastReceive; // direct or indirect
  490. uint64_t _lastUnicastFrame;
  491. uint64_t _lastMulticastFrame;
  492. uint64_t _lastAnnouncedTo;
  493. uint64_t _lastDirectPathPushSent;
  494. uint64_t _lastDirectPathPushReceive;
  495. uint64_t _lastPathSort;
  496. uint16_t _vProto;
  497. uint16_t _vMajor;
  498. uint16_t _vMinor;
  499. uint16_t _vRevision;
  500. Identity _id;
  501. Path _paths[ZT_MAX_PEER_NETWORK_PATHS];
  502. unsigned int _numPaths;
  503. unsigned int _latency;
  504. unsigned int _directPathPushCutoffCount;
  505. struct _NetworkCom
  506. {
  507. _NetworkCom() {}
  508. _NetworkCom(uint64_t t,const CertificateOfMembership &c) : ts(t),com(c) {}
  509. uint64_t ts;
  510. CertificateOfMembership com;
  511. };
  512. Hashtable<uint64_t,_NetworkCom> _networkComs;
  513. Hashtable<uint64_t,uint64_t> _lastPushedComs;
  514. Mutex _networkComs_m;
  515. AtomicCounter __refCount;
  516. };
  517. } // namespace ZeroTier
  518. // Add a swap() for shared ptr's to peers to speed up peer sorts
  519. namespace std {
  520. template<>
  521. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  522. {
  523. a.swap(b);
  524. }
  525. }
  526. #endif