Peer.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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
  153. {
  154. RWMutex::RLock l(_lock);
  155. return _bootstrap;
  156. }
  157. /**
  158. * Set bootstrap endpoint
  159. *
  160. * @param ep Bootstrap endpoint
  161. */
  162. ZT_ALWAYS_INLINE void setBootstrap(const Endpoint &ep) noexcept
  163. {
  164. RWMutex::Lock l(_lock);
  165. _bootstrap = ep;
  166. }
  167. /**
  168. * @return Time of last receive of anything, whether direct or relayed
  169. */
  170. ZT_ALWAYS_INLINE int64_t lastReceive() const noexcept { return _lastReceive; }
  171. /**
  172. * @return True if we've heard from this peer in less than ZT_PEER_ALIVE_TIMEOUT
  173. */
  174. ZT_ALWAYS_INLINE bool alive(const int64_t now) const noexcept { return ((now - _lastReceive) < ZT_PEER_ALIVE_TIMEOUT); }
  175. /**
  176. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  177. */
  178. ZT_ALWAYS_INLINE bool active(const int64_t now) const noexcept { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  179. /**
  180. * @return Latency in milliseconds of best/aggregate path or 0xffff if unknown
  181. */
  182. ZT_ALWAYS_INLINE unsigned int latency() const noexcept { return _latency; }
  183. /**
  184. * @return 256-bit secret symmetric encryption key
  185. */
  186. ZT_ALWAYS_INLINE const unsigned char *key() const noexcept { return _key; }
  187. /**
  188. * @return Preferred cipher suite for normal encrypted P2P communication
  189. */
  190. ZT_ALWAYS_INLINE uint8_t cipher() const noexcept
  191. {
  192. return ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012;
  193. }
  194. /**
  195. * @return Incoming probe packet (in big-endian byte order)
  196. 0 */
  197. ZT_ALWAYS_INLINE uint64_t incomingProbe() const noexcept { return _incomingProbe; }
  198. /**
  199. * Set the currently known remote version of this peer's client
  200. *
  201. * @param vproto Protocol version
  202. * @param vmaj Major version
  203. * @param vmin Minor version
  204. * @param vrev Revision
  205. */
  206. ZT_ALWAYS_INLINE void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev) noexcept
  207. {
  208. _vProto = (uint16_t)vproto;
  209. _vMajor = (uint16_t)vmaj;
  210. _vMinor = (uint16_t)vmin;
  211. _vRevision = (uint16_t)vrev;
  212. }
  213. ZT_ALWAYS_INLINE unsigned int remoteVersionProtocol() const noexcept { return _vProto; }
  214. ZT_ALWAYS_INLINE unsigned int remoteVersionMajor() const noexcept { return _vMajor; }
  215. ZT_ALWAYS_INLINE unsigned int remoteVersionMinor() const noexcept { return _vMinor; }
  216. ZT_ALWAYS_INLINE unsigned int remoteVersionRevision() const noexcept { return _vRevision; }
  217. ZT_ALWAYS_INLINE bool remoteVersionKnown() const noexcept { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  218. /**
  219. * Rate limit gate for inbound WHOIS requests
  220. */
  221. ZT_ALWAYS_INLINE bool rateGateInboundWhoisRequest(const int64_t now) noexcept
  222. {
  223. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  224. _lastWhoisRequestReceived = now;
  225. return true;
  226. }
  227. return false;
  228. }
  229. /**
  230. * Rate limit gate for inbound PUSH_DIRECT_PATHS requests
  231. */
  232. ZT_ALWAYS_INLINE bool rateGateInboundPushDirectPaths(const int64_t now) noexcept
  233. {
  234. if ((now - _lastPushDirectPathsReceived) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  235. _lastPushDirectPathsReceived = now;
  236. return true;
  237. }
  238. return false;
  239. }
  240. /**
  241. * Rate limit attempts in response to incoming short probe packets
  242. */
  243. ZT_ALWAYS_INLINE bool rateGateInboundProbe(const int64_t now) noexcept
  244. {
  245. if ((now - _lastProbeReceived) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  246. _lastProbeReceived = now;
  247. return true;
  248. }
  249. return false;
  250. }
  251. /**
  252. * Rate limit gate for inbound ECHO requests
  253. */
  254. ZT_ALWAYS_INLINE bool rateGateEchoRequest(const int64_t now) noexcept
  255. {
  256. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  257. _lastEchoRequestReceived = now;
  258. return true;
  259. }
  260. return false;
  261. }
  262. /**
  263. * @return Current best path
  264. */
  265. SharedPtr<Path> path(int64_t now);
  266. /**
  267. * @return True if there is at least one alive direct path
  268. */
  269. bool direct(int64_t now);
  270. /**
  271. * Get all paths
  272. *
  273. * @param paths Vector of paths with the first path being the current preferred path
  274. */
  275. void getAllPaths(std::vector< SharedPtr<Path> > &paths);
  276. /**
  277. * Save the latest version of this peer to the data store
  278. */
  279. void save(void *tPtr) const;
  280. /**
  281. * Attempt to contact this peer at a physical address, subject to internal checks
  282. *
  283. * @param tPtr External user pointer we pass around
  284. * @param ep Endpoint to attempt to contact
  285. * @param now Current time
  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 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. // The last time various things happened, for rate limiting and periodic events.
  306. std::atomic<int64_t> _lastReceive;
  307. std::atomic<int64_t> _lastWhoisRequestReceived;
  308. std::atomic<int64_t> _lastEchoRequestReceived;
  309. std::atomic<int64_t> _lastPushDirectPathsReceived;
  310. std::atomic<int64_t> _lastProbeReceived;
  311. std::atomic<int64_t> _lastAttemptedP2PInit;
  312. std::atomic<int64_t> _lastTriedStaticPath;
  313. std::atomic<int64_t> _lastPrioritizedPaths;
  314. std::atomic<int64_t> _lastAttemptedAggressiveNATTraversal;
  315. // Latency in milliseconds
  316. std::atomic<unsigned int> _latency;
  317. // For SharedPtr<>
  318. std::atomic<int> __refCount;
  319. // Read/write mutex for non-atomic non-const fields.
  320. RWMutex _lock;
  321. // Number of paths current alive as of last _prioritizePaths
  322. unsigned int _alivePathCount;
  323. // Direct paths sorted in descending order of preference (can be NULL, if first is NULL there's no direct path)
  324. SharedPtr<Path> _paths[ZT_MAX_PEER_NETWORK_PATHS];
  325. // Queue of batches of one or more physical addresses to try at some point in the future (for NAT traversal logic)
  326. struct _ContactQueueItem
  327. {
  328. ZT_ALWAYS_INLINE _ContactQueueItem() {}
  329. ZT_ALWAYS_INLINE _ContactQueueItem(const InetAddress &a,const uint16_t *pstart,const uint16_t *pend,const unsigned int apt) :
  330. address(a),
  331. ports(pstart,pend),
  332. alivePathThreshold(apt) {}
  333. ZT_ALWAYS_INLINE _ContactQueueItem(const InetAddress &a,const unsigned int apt) :
  334. address(a),
  335. ports(),
  336. alivePathThreshold(apt) {}
  337. InetAddress address;
  338. std::vector<uint16_t> ports; // if non-empty try these ports, otherwise use the one in address
  339. unsigned int alivePathThreshold; // skip and forget if alive path count is >= this
  340. };
  341. std::list<_ContactQueueItem> _contactQueue;
  342. Identity _id;
  343. uint64_t _incomingProbe;
  344. Locator _locator;
  345. Endpoint _bootstrap; // right now only InetAddress endpoints are supported for bootstrap
  346. uint16_t _vProto;
  347. uint16_t _vMajor;
  348. uint16_t _vMinor;
  349. uint16_t _vRevision;
  350. };
  351. } // namespace ZeroTier
  352. #endif