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