Peer.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_PEER_HPP
  28. #define ZT_PEER_HPP
  29. #include <stdint.h>
  30. #include "Constants.hpp"
  31. #include <algorithm>
  32. #include <utility>
  33. #include <vector>
  34. #include <stdexcept>
  35. #include "../include/ZeroTierOne.h"
  36. #include "RuntimeEnvironment.hpp"
  37. #include "CertificateOfMembership.hpp"
  38. #include "RemotePath.hpp"
  39. #include "Address.hpp"
  40. #include "Utils.hpp"
  41. #include "Identity.hpp"
  42. #include "InetAddress.hpp"
  43. #include "Packet.hpp"
  44. #include "SharedPtr.hpp"
  45. #include "AtomicCounter.hpp"
  46. #include "Hashtable.hpp"
  47. #include "Mutex.hpp"
  48. #include "NonCopyable.hpp"
  49. namespace ZeroTier {
  50. /**
  51. * Peer on P2P Network (virtual layer 1)
  52. */
  53. class Peer : NonCopyable
  54. {
  55. friend class SharedPtr<Peer>;
  56. private:
  57. Peer() {} // disabled to prevent bugs -- should not be constructed uninitialized
  58. public:
  59. ~Peer() { Utils::burn(_key,sizeof(_key)); }
  60. /**
  61. * Construct a new peer
  62. *
  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 Identity &myIdentity,const Identity &peerIdentity)
  68. throw(std::runtime_error);
  69. /**
  70. * @return Time peer record was last used in any way
  71. */
  72. inline uint64_t lastUsed() const throw() { return _lastUsed; }
  73. /**
  74. * Log a use of this peer record (done by Topology when peers are looked up)
  75. *
  76. * @param now New time of last use
  77. */
  78. inline void use(uint64_t now) throw() { _lastUsed = now; }
  79. /**
  80. * @return This peer's ZT address (short for identity().address())
  81. */
  82. inline const Address &address() const throw() { return _id.address(); }
  83. /**
  84. * @return This peer's identity
  85. */
  86. inline const Identity &identity() const throw() { return _id; }
  87. /**
  88. * Log receipt of an authenticated packet
  89. *
  90. * This is called by the decode pipe when a packet is proven to be authentic
  91. * and appears to be valid.
  92. *
  93. * @param RR Runtime environment
  94. * @param localAddr Local address
  95. * @param remoteAddr Internet address of sender
  96. * @param hops ZeroTier (not IP) hops
  97. * @param packetId Packet ID
  98. * @param verb Packet verb
  99. * @param inRePacketId Packet ID in reply to (default: none)
  100. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  101. */
  102. void received(
  103. const RuntimeEnvironment *RR,
  104. const InetAddress &localAddr,
  105. const InetAddress &remoteAddr,
  106. unsigned int hops,
  107. uint64_t packetId,
  108. Packet::Verb verb,
  109. uint64_t inRePacketId = 0,
  110. Packet::Verb inReVerb = Packet::VERB_NOP);
  111. /**
  112. * Get the best direct path to this peer
  113. *
  114. * @param now Current time
  115. * @return Best path or NULL if there are no active (or fixed) direct paths
  116. */
  117. inline RemotePath *getBestPath(uint64_t now)
  118. {
  119. Mutex::Lock _l(_lock);
  120. return _getBestPath(now);
  121. }
  122. /**
  123. * Send via best path
  124. *
  125. * @param RR Runtime environment
  126. * @param data Packet data
  127. * @param len Packet length
  128. * @param now Current time
  129. * @return Path used on success or NULL on failure
  130. */
  131. inline RemotePath *send(const RuntimeEnvironment *RR,const void *data,unsigned int len,uint64_t now)
  132. {
  133. RemotePath *bestPath = getBestPath(now);
  134. if (bestPath) {
  135. if (bestPath->send(RR,data,len,now))
  136. return bestPath;
  137. }
  138. return (RemotePath *)0;
  139. }
  140. /**
  141. * Send a HELLO to this peer at a specified physical address
  142. *
  143. * This does not update any statistics. It's used to send initial HELLOs
  144. * for NAT traversal and path verification.
  145. *
  146. * @param RR Runtime environment
  147. * @param localAddr Local address
  148. * @param atAddress Destination address
  149. * @param now Current time
  150. */
  151. void attemptToContactAt(const RuntimeEnvironment *RR,const InetAddress &localAddr,const InetAddress &atAddress,uint64_t now);
  152. /**
  153. * Send pings or keepalives depending on configured timeouts
  154. *
  155. * @param RR Runtime environment
  156. * @param now Current time
  157. */
  158. void doPingAndKeepalive(const RuntimeEnvironment *RR,uint64_t now);
  159. /**
  160. * Push direct paths if we haven't done so in [rate limit] milliseconds
  161. *
  162. * @param RR Runtime environment
  163. * @param path Remote path to use to send the push
  164. * @param now Current time
  165. * @param force If true, push regardless of rate limit
  166. */
  167. void pushDirectPaths(const RuntimeEnvironment *RR,RemotePath *path,uint64_t now,bool force);
  168. /**
  169. * @return All known direct paths to this peer
  170. */
  171. inline std::vector<RemotePath> paths() const
  172. {
  173. std::vector<RemotePath> pp;
  174. Mutex::Lock _l(_lock);
  175. for(unsigned int p=0,np=_numPaths;p<np;++p)
  176. pp.push_back(_paths[p]);
  177. return pp;
  178. }
  179. /**
  180. * @return Time of last direct packet receive for any path
  181. */
  182. inline uint64_t lastDirectReceive() const
  183. throw()
  184. {
  185. Mutex::Lock _l(_lock);
  186. uint64_t x = 0;
  187. for(unsigned int p=0,np=_numPaths;p<np;++p)
  188. x = std::max(x,_paths[p].lastReceived());
  189. return x;
  190. }
  191. /**
  192. * @return Time of last direct packet send for any path
  193. */
  194. inline uint64_t lastDirectSend() const
  195. throw()
  196. {
  197. Mutex::Lock _l(_lock);
  198. uint64_t x = 0;
  199. for(unsigned int p=0,np=_numPaths;p<np;++p)
  200. x = std::max(x,_paths[p].lastSend());
  201. return x;
  202. }
  203. /**
  204. * @return Time of last receive of anything, whether direct or relayed
  205. */
  206. inline uint64_t lastReceive() const throw() { return _lastReceive; }
  207. /**
  208. * @return Time of most recent unicast frame received
  209. */
  210. inline uint64_t lastUnicastFrame() const throw() { return _lastUnicastFrame; }
  211. /**
  212. * @return Time of most recent multicast frame received
  213. */
  214. inline uint64_t lastMulticastFrame() const throw() { return _lastMulticastFrame; }
  215. /**
  216. * @return Time of most recent frame of any kind (unicast or multicast)
  217. */
  218. inline uint64_t lastFrame() const throw() { return std::max(_lastUnicastFrame,_lastMulticastFrame); }
  219. /**
  220. * @return Time we last announced state TO this peer, such as multicast LIKEs
  221. */
  222. inline uint64_t lastAnnouncedTo() const throw() { return _lastAnnouncedTo; }
  223. /**
  224. * @return True if peer has received an actual data frame within ZT_PEER_ACTIVITY_TIMEOUT milliseconds
  225. */
  226. inline uint64_t alive(uint64_t now) const throw() { return ((now - lastFrame()) < ZT_PEER_ACTIVITY_TIMEOUT); }
  227. /**
  228. * @return Current latency or 0 if unknown (max: 65535)
  229. */
  230. inline unsigned int latency() const
  231. throw()
  232. {
  233. unsigned int l = _latency;
  234. return std::min(l,(unsigned int)65535);
  235. }
  236. /**
  237. * Update latency with a new direct measurment
  238. *
  239. * @param l Direct latency measurment in ms
  240. */
  241. inline void addDirectLatencyMeasurment(unsigned int l)
  242. throw()
  243. {
  244. unsigned int ol = _latency;
  245. if ((ol > 0)&&(ol < 10000))
  246. _latency = (ol + std::min(l,(unsigned int)65535)) / 2;
  247. else _latency = std::min(l,(unsigned int)65535);
  248. }
  249. /**
  250. * @return True if this peer has at least one direct IP address path
  251. */
  252. inline bool hasDirectPath() const throw() { return (_numPaths != 0); }
  253. /**
  254. * @param now Current time
  255. * @return True if this peer has at least one active or fixed direct path
  256. */
  257. inline bool hasActiveDirectPath(uint64_t now) const
  258. throw()
  259. {
  260. Mutex::Lock _l(_lock);
  261. for(unsigned int p=0,np=_numPaths;p<np;++p) {
  262. if (_paths[p].active(now))
  263. return true;
  264. }
  265. return false;
  266. }
  267. /**
  268. * Add a path (if we don't already have it)
  269. *
  270. * @param p New path to add
  271. * @param now Current time
  272. */
  273. void addPath(const RemotePath &newp,uint64_t now);
  274. /**
  275. * Clear paths
  276. *
  277. * @param fixedToo If true, clear fixed paths as well as learned ones
  278. */
  279. void clearPaths(bool fixedToo);
  280. /**
  281. * Reset paths within a given scope
  282. *
  283. * For fixed paths in this scope, a packet is sent. Non-fixed paths in this
  284. * scope are forgotten.
  285. *
  286. * @param RR Runtime environment
  287. * @param scope IP scope of paths to reset
  288. * @param now Current time
  289. * @return True if at least one path was forgotten
  290. */
  291. bool resetWithinScope(const RuntimeEnvironment *RR,InetAddress::IpScope scope,uint64_t now);
  292. /**
  293. * @return 256-bit secret symmetric encryption key
  294. */
  295. inline const unsigned char *key() const throw() { return _key; }
  296. /**
  297. * Set the currently known remote version of this peer's client
  298. *
  299. * @param vproto Protocol version
  300. * @param vmaj Major version
  301. * @param vmin Minor version
  302. * @param vrev Revision
  303. */
  304. inline void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  305. {
  306. Mutex::Lock _l(_lock);
  307. _vProto = (uint16_t)vproto;
  308. _vMajor = (uint16_t)vmaj;
  309. _vMinor = (uint16_t)vmin;
  310. _vRevision = (uint16_t)vrev;
  311. }
  312. inline unsigned int remoteVersionProtocol() const throw() { return _vProto; }
  313. inline unsigned int remoteVersionMajor() const throw() { return _vMajor; }
  314. inline unsigned int remoteVersionMinor() const throw() { return _vMinor; }
  315. inline unsigned int remoteVersionRevision() const throw() { return _vRevision; }
  316. inline bool remoteVersionKnown() const throw() { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  317. /**
  318. * Check whether this peer's version is both known and is at least what is specified
  319. *
  320. * @param major Major version to check against
  321. * @param minor Minor version
  322. * @param rev Revision
  323. * @return True if peer's version is at least supplied tuple
  324. */
  325. inline bool atLeastVersion(unsigned int major,unsigned int minor,unsigned int rev)
  326. throw()
  327. {
  328. Mutex::Lock _l(_lock);
  329. if ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)) {
  330. if (_vMajor > major)
  331. return true;
  332. else if (_vMajor == major) {
  333. if (_vMinor > minor)
  334. return true;
  335. else if (_vMinor == minor) {
  336. if (_vRevision >= rev)
  337. return true;
  338. }
  339. }
  340. }
  341. return false;
  342. }
  343. /**
  344. * Get most recently active path addresses for IPv4 and/or IPv6
  345. *
  346. * Note that v4 and v6 are not modified if they are not found, so
  347. * initialize these to a NULL address to be able to check.
  348. *
  349. * @param now Current time
  350. * @param v4 Result parameter to receive active IPv4 address, if any
  351. * @param v6 Result parameter to receive active IPv6 address, if any
  352. */
  353. void getBestActiveAddresses(uint64_t now,InetAddress &v4,InetAddress &v6) const;
  354. /**
  355. * Check network COM agreement with this peer
  356. *
  357. * @param nwid Network ID
  358. * @param com Another certificate of membership
  359. * @return True if supplied COM agrees with ours, false if not or if we don't have one
  360. */
  361. bool networkMembershipCertificatesAgree(uint64_t nwid,const CertificateOfMembership &com) const;
  362. /**
  363. * Check the validity of the COM and add/update if valid and new
  364. *
  365. * @param RR Runtime Environment
  366. * @param nwid Network ID
  367. * @param com Externally supplied COM
  368. */
  369. bool validateAndSetNetworkMembershipCertificate(const RuntimeEnvironment *RR,uint64_t nwid,const CertificateOfMembership &com);
  370. /**
  371. * @param nwid Network ID
  372. * @param now Current time
  373. * @param updateLastPushedTime If true, go ahead and update the last pushed time regardless of return value
  374. * @return Whether or not this peer needs another COM push from us
  375. */
  376. bool needsOurNetworkMembershipCertificate(uint64_t nwid,uint64_t now,bool updateLastPushedTime);
  377. /**
  378. * Perform periodic cleaning operations
  379. */
  380. void clean(const RuntimeEnvironment *RR,uint64_t now);
  381. /**
  382. * Find a common set of addresses by which two peers can link, if any
  383. *
  384. * @param a Peer A
  385. * @param b Peer B
  386. * @param now Current time
  387. * @return Pair: B's address (to send to A), A's address (to send to B)
  388. */
  389. static inline std::pair<InetAddress,InetAddress> findCommonGround(const Peer &a,const Peer &b,uint64_t now)
  390. {
  391. std::pair<InetAddress,InetAddress> v4,v6;
  392. b.getBestActiveAddresses(now,v4.first,v6.first);
  393. a.getBestActiveAddresses(now,v4.second,v6.second);
  394. if ((v6.first)&&(v6.second)) // prefer IPv6 if both have it since NAT-t is (almost) unnecessary
  395. return v6;
  396. else if ((v4.first)&&(v4.second))
  397. return v4;
  398. else return std::pair<InetAddress,InetAddress>();
  399. }
  400. private:
  401. void _sortPaths(const uint64_t now);
  402. RemotePath *_getBestPath(const uint64_t now);
  403. unsigned char _key[ZT_PEER_SECRET_KEY_LENGTH];
  404. uint64_t _lastUsed;
  405. uint64_t _lastReceive; // direct or indirect
  406. uint64_t _lastUnicastFrame;
  407. uint64_t _lastMulticastFrame;
  408. uint64_t _lastAnnouncedTo;
  409. uint64_t _lastPathConfirmationSent;
  410. uint64_t _lastDirectPathPush;
  411. uint64_t _lastPathSort;
  412. uint16_t _vProto;
  413. uint16_t _vMajor;
  414. uint16_t _vMinor;
  415. uint16_t _vRevision;
  416. Identity _id;
  417. RemotePath _paths[ZT_MAX_PEER_NETWORK_PATHS];
  418. unsigned int _numPaths;
  419. unsigned int _latency;
  420. struct _NetworkCom
  421. {
  422. _NetworkCom() {}
  423. _NetworkCom(uint64_t t,const CertificateOfMembership &c) : ts(t),com(c) {}
  424. uint64_t ts;
  425. CertificateOfMembership com;
  426. };
  427. Hashtable<uint64_t,_NetworkCom> _networkComs;
  428. Hashtable<uint64_t,uint64_t> _lastPushedComs;
  429. Mutex _lock;
  430. AtomicCounter __refCount;
  431. };
  432. } // namespace ZeroTier
  433. // Add a swap() for shared ptr's to peers to speed up peer sorts
  434. namespace std {
  435. template<>
  436. inline void swap(ZeroTier::SharedPtr<ZeroTier::Peer> &a,ZeroTier::SharedPtr<ZeroTier::Peer> &b)
  437. {
  438. a.swap(b);
  439. }
  440. }
  441. #endif