Peer.hpp 12 KB

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