Peer.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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_ADDRESS_LENGTH + ZT_PEER_SECRET_KEY_LENGTH + 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_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_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_INLINE Address address() const noexcept { return _id.address(); }
  66. /**
  67. * @return This peer's identity
  68. */
  69. ZT_INLINE const Identity &identity() const noexcept { return _id; }
  70. /**
  71. * @return Copy of current locator
  72. */
  73. ZT_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. * @return Number of bytes sent
  109. */
  110. unsigned int sendHELLO(void *tPtr,int64_t localSocket,const InetAddress &atAddress,int64_t now);
  111. /**
  112. * Send a NOP message to e.g. probe a new link
  113. *
  114. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  115. * @param localSocket Local source socket
  116. * @param atAddress Destination address
  117. * @param now Current time
  118. * @return Number of bytes sent
  119. */
  120. unsigned int sendNOP(void *tPtr,int64_t localSocket,const InetAddress &atAddress,int64_t now);
  121. /**
  122. * Send ping to this peer
  123. *
  124. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  125. * @param now Current time
  126. * @param pingAllAddressTypes If true, try to keep a link up for each address type/family
  127. */
  128. void ping(void *tPtr,int64_t now,bool pingAllAddressTypes);
  129. /**
  130. * Reset paths within a given IP scope and address family
  131. *
  132. * Resetting a path involves sending an ECHO to it and then deactivating
  133. * it until or unless it responds. This is done when we detect a change
  134. * to our external IP or another system change that might invalidate
  135. * many or all current paths.
  136. *
  137. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  138. * @param scope IP scope
  139. * @param inetAddressFamily Family e.g. AF_INET
  140. * @param now Current time
  141. */
  142. void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now);
  143. /**
  144. * Update peer latency information
  145. *
  146. * This is called from packet parsing code.
  147. *
  148. * @param l New latency measurment (in milliseconds)
  149. */
  150. void updateLatency(unsigned int l) noexcept;
  151. /**
  152. * @return Bootstrap address or NULL if none
  153. */
  154. ZT_INLINE const Endpoint &bootstrap() const noexcept
  155. {
  156. RWMutex::RLock l(_lock);
  157. return _bootstrap;
  158. }
  159. /**
  160. * Set bootstrap endpoint
  161. *
  162. * @param ep Bootstrap endpoint
  163. */
  164. ZT_INLINE void setBootstrap(const Endpoint &ep) noexcept
  165. {
  166. RWMutex::Lock l(_lock);
  167. _bootstrap = ep;
  168. }
  169. /**
  170. * @return Time of last receive of anything, whether direct or relayed
  171. */
  172. ZT_INLINE int64_t lastReceive() const noexcept { return _lastReceive; }
  173. /**
  174. * @return True if we've heard from this peer in less than ZT_PEER_ALIVE_TIMEOUT
  175. */
  176. ZT_INLINE bool alive(const int64_t now) const noexcept { return ((now - _lastReceive) < ZT_PEER_ALIVE_TIMEOUT); }
  177. /**
  178. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  179. */
  180. ZT_INLINE bool active(const int64_t now) const noexcept { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  181. /**
  182. * @return Latency in milliseconds of best/aggregate path or 0xffff if unknown
  183. */
  184. ZT_INLINE unsigned int latency() const noexcept { return _latency; }
  185. /**
  186. * @return 256-bit secret symmetric encryption key
  187. */
  188. ZT_INLINE const unsigned char *key() const noexcept { return _key; }
  189. /**
  190. * @return Preferred cipher suite for normal encrypted P2P communication
  191. */
  192. ZT_INLINE uint8_t cipher() const noexcept
  193. {
  194. return ZT_PROTO_CIPHER_SUITE__POLY1305_SALSA2012;
  195. }
  196. /**
  197. * @return Incoming probe packet (in big-endian byte order)
  198. 0 */
  199. ZT_INLINE uint64_t incomingProbe() const noexcept { return _incomingProbe; }
  200. /**
  201. * Set the currently known remote version of this peer's client
  202. *
  203. * @param vproto Protocol version
  204. * @param vmaj Major version
  205. * @param vmin Minor version
  206. * @param vrev Revision
  207. */
  208. ZT_INLINE void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev) noexcept
  209. {
  210. _vProto = (uint16_t)vproto;
  211. _vMajor = (uint16_t)vmaj;
  212. _vMinor = (uint16_t)vmin;
  213. _vRevision = (uint16_t)vrev;
  214. }
  215. ZT_INLINE unsigned int remoteVersionProtocol() const noexcept { return _vProto; }
  216. ZT_INLINE unsigned int remoteVersionMajor() const noexcept { return _vMajor; }
  217. ZT_INLINE unsigned int remoteVersionMinor() const noexcept { return _vMinor; }
  218. ZT_INLINE unsigned int remoteVersionRevision() const noexcept { return _vRevision; }
  219. ZT_INLINE bool remoteVersionKnown() const noexcept { return ((_vMajor > 0) || (_vMinor > 0) || (_vRevision > 0)); }
  220. /**
  221. * Rate limit gate for inbound WHOIS requests
  222. */
  223. ZT_INLINE bool rateGateInboundWhoisRequest(const int64_t now) noexcept
  224. {
  225. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  226. _lastWhoisRequestReceived = now;
  227. return true;
  228. }
  229. return false;
  230. }
  231. /**
  232. * Rate limit gate for inbound PUSH_DIRECT_PATHS requests
  233. */
  234. ZT_INLINE bool rateGateInboundPushDirectPaths(const int64_t now) noexcept
  235. {
  236. if ((now - _lastPushDirectPathsReceived) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  237. _lastPushDirectPathsReceived = now;
  238. return true;
  239. }
  240. return false;
  241. }
  242. /**
  243. * Rate limit attempts in response to incoming short probe packets
  244. */
  245. ZT_INLINE bool rateGateInboundProbe(const int64_t now) noexcept
  246. {
  247. if ((now - _lastProbeReceived) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  248. _lastProbeReceived = now;
  249. return true;
  250. }
  251. return false;
  252. }
  253. /**
  254. * Rate limit gate for inbound ECHO requests
  255. */
  256. ZT_INLINE bool rateGateEchoRequest(const int64_t now) noexcept
  257. {
  258. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  259. _lastEchoRequestReceived = now;
  260. return true;
  261. }
  262. return false;
  263. }
  264. /**
  265. * @return Current best path
  266. */
  267. SharedPtr<Path> path(int64_t now);
  268. /**
  269. * @return True if there is at least one alive direct path
  270. */
  271. bool direct(int64_t now);
  272. /**
  273. * Get all paths
  274. *
  275. * @param paths Vector of paths with the first path being the current preferred path
  276. */
  277. void getAllPaths(std::vector< SharedPtr<Path> > &paths);
  278. /**
  279. * Save the latest version of this peer to the data store
  280. */
  281. void save(void *tPtr) const;
  282. /**
  283. * Attempt to contact this peer at a physical address, subject to internal checks
  284. *
  285. * @param tPtr External user pointer we pass around
  286. * @param ep Endpoint to attempt to contact
  287. * @param now Current time
  288. * @param bfg1024 Use BFG1024 brute force symmetric NAT busting algorithm if applicable
  289. */
  290. void contact(void *tPtr,const Endpoint &ep,int64_t now,bool bfg1024);
  291. /**
  292. * Called by Node when an alarm set by this peer goes off
  293. *
  294. * @param tPtr External user pointer we pass around
  295. * @param now Current time
  296. */
  297. void alarm(void *tPtr,int64_t now);
  298. // NOTE: peer marshal/unmarshal only saves/restores the identity, locator, most
  299. // recent bootstrap address, and version information.
  300. static constexpr int marshalSizeMax() noexcept { return ZT_PEER_MARSHAL_SIZE_MAX; }
  301. int marshal(uint8_t data[ZT_PEER_MARSHAL_SIZE_MAX]) const noexcept;
  302. int unmarshal(const uint8_t *restrict data,int len) noexcept;
  303. private:
  304. void _prioritizePaths(int64_t now);
  305. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  306. const RuntimeEnvironment *RR;
  307. // The last time various things happened, for rate limiting and periodic events.
  308. std::atomic<int64_t> _lastReceive;
  309. std::atomic<int64_t> _lastWhoisRequestReceived;
  310. std::atomic<int64_t> _lastEchoRequestReceived;
  311. std::atomic<int64_t> _lastPushDirectPathsReceived;
  312. std::atomic<int64_t> _lastProbeReceived;
  313. std::atomic<int64_t> _lastAttemptedP2PInit;
  314. std::atomic<int64_t> _lastTriedStaticPath;
  315. std::atomic<int64_t> _lastPrioritizedPaths;
  316. std::atomic<int64_t> _lastAttemptedAggressiveNATTraversal;
  317. // Latency in milliseconds
  318. std::atomic<unsigned int> _latency;
  319. // For SharedPtr<>
  320. std::atomic<int> __refCount;
  321. // Read/write mutex for non-atomic non-const fields.
  322. RWMutex _lock;
  323. // Number of paths current alive as of last _prioritizePaths
  324. unsigned int _alivePathCount;
  325. // Direct paths sorted in descending order of preference (can be NULL, if first is NULL there's no direct path)
  326. SharedPtr<Path> _paths[ZT_MAX_PEER_NETWORK_PATHS];
  327. // Queue of batches of one or more physical addresses to try at some point in the future (for NAT traversal logic)
  328. struct _ContactQueueItem
  329. {
  330. ZT_INLINE _ContactQueueItem() {}
  331. ZT_INLINE _ContactQueueItem(const InetAddress &a,const uint16_t *pstart,const uint16_t *pend,const unsigned int apt) :
  332. address(a),
  333. ports(pstart,pend),
  334. alivePathThreshold(apt) {}
  335. ZT_INLINE _ContactQueueItem(const InetAddress &a,const unsigned int apt) :
  336. address(a),
  337. ports(),
  338. alivePathThreshold(apt) {}
  339. InetAddress address;
  340. std::vector<uint16_t> ports; // if non-empty try these ports, otherwise use the one in address
  341. unsigned int alivePathThreshold; // skip and forget if alive path count is >= this
  342. };
  343. std::list<_ContactQueueItem> _contactQueue;
  344. Identity _id;
  345. uint64_t _incomingProbe;
  346. Locator _locator;
  347. Endpoint _bootstrap; // right now only InetAddress endpoints are supported for bootstrap
  348. uint16_t _vProto;
  349. uint16_t _vMajor;
  350. uint16_t _vMinor;
  351. uint16_t _vRevision;
  352. };
  353. } // namespace ZeroTier
  354. #endif