Peer.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_PEER_HPP
  14. #define ZT_PEER_HPP
  15. #include "Constants.hpp"
  16. #include "RuntimeEnvironment.hpp"
  17. #include "Node.hpp"
  18. #include "Path.hpp"
  19. #include "Address.hpp"
  20. #include "Utils.hpp"
  21. #include "Identity.hpp"
  22. #include "InetAddress.hpp"
  23. #include "SharedPtr.hpp"
  24. #include "Hashtable.hpp"
  25. #include "Mutex.hpp"
  26. #include "Endpoint.hpp"
  27. #include "Locator.hpp"
  28. #include "Protocol.hpp"
  29. #include <vector>
  30. #include <list>
  31. // version, identity, locator, bootstrap, version info, length of any additional fields
  32. #define ZT_PEER_MARSHAL_SIZE_MAX (1 + ZT_IDENTITY_MARSHAL_SIZE_MAX + ZT_LOCATOR_MARSHAL_SIZE_MAX + ZT_INETADDRESS_MARSHAL_SIZE_MAX + (2*4) + 2)
  33. namespace ZeroTier {
  34. class Topology;
  35. /**
  36. * Peer on P2P Network (virtual layer 1)
  37. */
  38. class Peer
  39. {
  40. friend class SharedPtr<Peer>;
  41. friend class Topology;
  42. private:
  43. ZT_ALWAYS_INLINE Peer() {}
  44. public:
  45. /**
  46. * Create an uninitialized peer
  47. *
  48. * The peer will need to be initialized with init() or unmarshal() before
  49. * it can be used.
  50. *
  51. * @param renv Runtime environment
  52. */
  53. explicit Peer(const RuntimeEnvironment *renv);
  54. ZT_ALWAYS_INLINE ~Peer() { Utils::burn(_key,sizeof(_key)); }
  55. /**
  56. * Initialize peer with an identity
  57. *
  58. * @param peerIdentity The peer's identity
  59. * @return True if initialization was succcesful
  60. */
  61. bool init(const Identity &peerIdentity);
  62. /**
  63. * @return This peer's ZT address (short for identity().address())
  64. */
  65. ZT_ALWAYS_INLINE const Address &address() const noexcept { return _id.address(); }
  66. /**
  67. * @return This peer's identity
  68. */
  69. ZT_ALWAYS_INLINE const Identity &identity() const noexcept { return _id; }
  70. /**
  71. * @return Copy of current locator
  72. */
  73. ZT_ALWAYS_INLINE Locator locator() const noexcept
  74. {
  75. RWMutex::RLock l(_lock);
  76. return _locator;
  77. }
  78. /**
  79. * Log receipt of an authenticated packet
  80. *
  81. * This is called by the decode pipe when a packet is proven to be authentic
  82. * and appears to be valid.
  83. *
  84. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  85. * @param path Path over which packet was received
  86. * @param hops ZeroTier (not IP) hops
  87. * @param packetId Packet ID
  88. * @param verb Packet verb
  89. * @param inReVerb In-reply verb for OK or ERROR verbs
  90. */
  91. void received(
  92. void *tPtr,
  93. const SharedPtr<Path> &path,
  94. unsigned int hops,
  95. uint64_t packetId,
  96. unsigned int payloadLength,
  97. Protocol::Verb verb,
  98. Protocol::Verb inReVerb);
  99. /**
  100. * Send a HELLO to this peer at a specified physical address
  101. *
  102. * No statistics or sent times are updated here.
  103. *
  104. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  105. * @param localSocket Local source socket
  106. * @param atAddress Destination address
  107. * @param now Current time
  108. */
  109. void sendHELLO(void *tPtr,int64_t localSocket,const InetAddress &atAddress,int64_t now);
  110. /**
  111. * Send a NOP message to e.g. probe a new link
  112. *
  113. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  114. * @param localSocket Local source socket
  115. * @param atAddress Destination address
  116. * @param now Current time
  117. */
  118. void sendNOP(void *tPtr,int64_t localSocket,const InetAddress &atAddress,int64_t now);
  119. /**
  120. * Send ping to this peer
  121. *
  122. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  123. * @param now Current time
  124. * @param pingAllAddressTypes If true, try to keep a link up for each address type/family
  125. */
  126. void ping(void *tPtr,int64_t now,bool pingAllAddressTypes);
  127. /**
  128. * Reset paths within a given IP scope and address family
  129. *
  130. * Resetting a path involves sending an ECHO to it and then deactivating
  131. * it until or unless it responds. This is done when we detect a change
  132. * to our external IP or another system change that might invalidate
  133. * many or all current paths.
  134. *
  135. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  136. * @param scope IP scope
  137. * @param inetAddressFamily Family e.g. AF_INET
  138. * @param now Current time
  139. */
  140. void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now);
  141. /**
  142. * Update peer latency information
  143. *
  144. * This is called from packet parsing code.
  145. *
  146. * @param l New latency measurment (in milliseconds)
  147. */
  148. void updateLatency(unsigned int l) noexcept;
  149. /**
  150. * @return Bootstrap address or NULL if none
  151. */
  152. ZT_ALWAYS_INLINE const Endpoint &bootstrap() const noexcept { return _bootstrap; }
  153. /**
  154. * Set bootstrap endpoint
  155. *
  156. * @param ep Bootstrap endpoint
  157. */
  158. ZT_ALWAYS_INLINE void setBootstrap(const Endpoint &ep) noexcept
  159. {
  160. _lock.lock();
  161. _bootstrap = ep;
  162. _lock.unlock();
  163. }
  164. /**
  165. * @return Time of last receive of anything, whether direct or relayed
  166. */
  167. ZT_ALWAYS_INLINE int64_t lastReceive() const noexcept { return _lastReceive; }
  168. /**
  169. * @return True if we've heard from this peer in less than ZT_PEER_ALIVE_TIMEOUT
  170. */
  171. ZT_ALWAYS_INLINE bool alive(const int64_t now) const noexcept { return ((now - _lastReceive) < ZT_PEER_ALIVE_TIMEOUT); }
  172. /**
  173. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  174. */
  175. ZT_ALWAYS_INLINE bool active(const int64_t now) const noexcept { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  176. /**
  177. * @return Latency in milliseconds of best/aggregate path or 0xffff if unknown
  178. */
  179. ZT_ALWAYS_INLINE unsigned int latency() const noexcept { return _latency; }
  180. /**
  181. * @return 256-bit secret symmetric encryption key
  182. */
  183. ZT_ALWAYS_INLINE const unsigned char *key() const noexcept { return _key; }
  184. /**
  185. * @return Preferred cipher suite for normal encrypted P2P communication
  186. */
  187. ZT_ALWAYS_INLINE uint8_t cipher() const noexcept
  188. {
  189. return ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012;
  190. }
  191. /**
  192. * @return Incoming probe packet (in big-endian byte order)
  193. 0 */
  194. ZT_ALWAYS_INLINE uint64_t incomingProbe() const noexcept { return _incomingProbe; }
  195. /**
  196. * Set the currently known remote version of this peer's client
  197. *
  198. * @param vproto Protocol version
  199. * @param vmaj Major version
  200. * @param vmin Minor version
  201. * @param vrev Revision
  202. */
  203. ZT_ALWAYS_INLINE void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev) noexcept
  204. {
  205. _vProto = (uint16_t)vproto;
  206. _vMajor = (uint16_t)vmaj;
  207. _vMinor = (uint16_t)vmin;
  208. _vRevision = (uint16_t)vrev;
  209. }
  210. ZT_ALWAYS_INLINE unsigned int remoteVersionProtocol() const noexcept { return _vProto; }
  211. ZT_ALWAYS_INLINE unsigned int remoteVersionMajor() const noexcept { return _vMajor; }
  212. ZT_ALWAYS_INLINE unsigned int remoteVersionMinor() const noexcept { return _vMinor; }
  213. ZT_ALWAYS_INLINE unsigned int remoteVersionRevision() const noexcept { return _vRevision; }
  214. ZT_ALWAYS_INLINE bool remoteVersionKnown() const noexcept { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  215. /**
  216. * Rate limit gate for inbound WHOIS requests
  217. */
  218. ZT_ALWAYS_INLINE bool rateGateInboundWhoisRequest(const int64_t now) noexcept
  219. {
  220. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  221. _lastWhoisRequestReceived = now;
  222. return true;
  223. }
  224. return false;
  225. }
  226. /**
  227. * Rate limit gate for inbound PUSH_DIRECT_PATHS requests
  228. */
  229. ZT_ALWAYS_INLINE bool rateGateInboundPushDirectPaths(const int64_t now) noexcept
  230. {
  231. if ((now - _lastPushDirectPathsReceived) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  232. _lastPushDirectPathsReceived = now;
  233. return true;
  234. }
  235. return false;
  236. }
  237. /**
  238. * Rate limit attempts in response to incoming short probe packets
  239. */
  240. ZT_ALWAYS_INLINE bool rateGateInboundProbe(const int64_t now) noexcept
  241. {
  242. if ((now - _lastProbeReceived) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  243. _lastProbeReceived = now;
  244. return true;
  245. }
  246. return false;
  247. }
  248. /**
  249. * Rate limit gate for inbound ECHO requests
  250. */
  251. ZT_ALWAYS_INLINE bool rateGateEchoRequest(const int64_t now) noexcept
  252. {
  253. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  254. _lastEchoRequestReceived = now;
  255. return true;
  256. }
  257. return false;
  258. }
  259. /**
  260. * @return Current best path
  261. */
  262. SharedPtr<Path> path(int64_t now);
  263. /**
  264. * @return True if there is at least one alive direct path
  265. */
  266. bool direct(int64_t now);
  267. /**
  268. * Get all paths
  269. *
  270. * @param paths Vector of paths with the first path being the current preferred path
  271. */
  272. void getAllPaths(std::vector< SharedPtr<Path> > &paths);
  273. /**
  274. * Save the latest version of this peer to the data store
  275. */
  276. void save(void *tPtr) const;
  277. /**
  278. * Attempt to contact this peer at a physical address
  279. *
  280. * This checks rate limits, path usability, sometimes deploys advanced NAT-t techniques, etc.
  281. *
  282. * @param tPtr External user pointer we pass around
  283. * @param ep Endpoint to attempt to contact
  284. * @param now Current time
  285. * @param behindSymmetric This peer may be behind a symmetric NAT (only meaningful for IPv4)
  286. * @param bfg1024 Use BFG1024 brute force symmetric NAT busting algorithm if applicable
  287. */
  288. void contact(void *tPtr,const Endpoint &ep,int64_t now,bool behindSymmetric,bool bfg1024);
  289. /**
  290. * Called by Node when an alarm set by this peer goes off
  291. *
  292. * @param tPtr External user pointer we pass around
  293. * @param now Current time
  294. */
  295. void alarm(void *tPtr,int64_t now);
  296. // NOTE: peer marshal/unmarshal only saves/restores the identity, locator, most
  297. // recent bootstrap address, and version information.
  298. static constexpr int marshalSizeMax() noexcept { return ZT_PEER_MARSHAL_SIZE_MAX; }
  299. int marshal(uint8_t data[ZT_PEER_MARSHAL_SIZE_MAX]) const noexcept;
  300. int unmarshal(const uint8_t *restrict data,int len) noexcept;
  301. private:
  302. void _prioritizePaths(int64_t now);
  303. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  304. const RuntimeEnvironment *RR;
  305. volatile int64_t _lastReceive;
  306. volatile int64_t _lastWhoisRequestReceived;
  307. volatile int64_t _lastEchoRequestReceived;
  308. volatile int64_t _lastPushDirectPathsReceived;
  309. volatile int64_t _lastProbeReceived;
  310. volatile int64_t _lastAttemptedP2PInit;
  311. volatile int64_t _lastTriedStaticPath;
  312. volatile int64_t _lastPrioritizedPaths;
  313. volatile int64_t _lastAttemptedAggressiveNATTraversal;
  314. volatile unsigned int _latency;
  315. std::atomic<int> __refCount;
  316. // Lock for non-volatile read/write fields
  317. RWMutex _lock;
  318. // Number of paths current alive as of last _prioritizePaths
  319. unsigned int _alivePathCount;
  320. // Direct paths sorted in descending order of preference (can be NULL, if first is NULL there's no direct path)
  321. SharedPtr<Path> _paths[ZT_MAX_PEER_NETWORK_PATHS];
  322. // Queue of batches of one or more physical addresses to try at some point in the future (for NAT traversal logic)
  323. struct _ContactQueueItem
  324. {
  325. ZT_ALWAYS_INLINE _ContactQueueItem() {}
  326. ZT_ALWAYS_INLINE _ContactQueueItem(const InetAddress &a,const uint16_t *pstart,const uint16_t *pend,const unsigned int apt) :
  327. address(a),
  328. ports(pstart,pend),
  329. alivePathThreshold(apt) {}
  330. ZT_ALWAYS_INLINE _ContactQueueItem(const InetAddress &a,const unsigned int apt) :
  331. address(a),
  332. ports(),
  333. alivePathThreshold(apt) {}
  334. InetAddress address;
  335. std::vector<uint16_t> ports; // if non-empty try these ports, otherwise use the one in address
  336. unsigned int alivePathThreshold; // skip and forget if alive path count is >= this
  337. };
  338. std::list<_ContactQueueItem> _contactQueue;
  339. Identity _id;
  340. uint64_t _incomingProbe;
  341. Locator _locator;
  342. Endpoint _bootstrap; // right now only InetAddress endpoints are supported for bootstrap
  343. uint16_t _vProto;
  344. uint16_t _vMajor;
  345. uint16_t _vMinor;
  346. uint16_t _vRevision;
  347. };
  348. } // namespace ZeroTier
  349. #endif