Peer.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 "Packet.hpp"
  24. #include "SharedPtr.hpp"
  25. #include "AtomicCounter.hpp"
  26. #include "Hashtable.hpp"
  27. #include "Mutex.hpp"
  28. #include "Endpoint.hpp"
  29. #include "Locator.hpp"
  30. #include <vector>
  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. Peer(const RuntimeEnvironment *renv);
  54. ZT_ALWAYS_INLINE ~Peer() { Utils::burn(_key,sizeof(_key)); }
  55. /**
  56. * Initialize peer with an identity
  57. *
  58. * @param myIdentity This node's identity including secret key
  59. * @param peerIdentity The peer's identity
  60. * @return True if initialization was succcesful
  61. */
  62. bool init(const Identity &myIdentity,const Identity &peerIdentity);
  63. /**
  64. * @return This peer's ZT address (short for identity().address())
  65. */
  66. ZT_ALWAYS_INLINE const Address &address() const { return _id.address(); }
  67. /**
  68. * @return This peer's identity
  69. */
  70. ZT_ALWAYS_INLINE const Identity &identity() const { return _id; }
  71. /**
  72. * Log receipt of an authenticated packet
  73. *
  74. * This is called by the decode pipe when a packet is proven to be authentic
  75. * and appears to be valid.
  76. *
  77. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  78. * @param path Path over which packet was received
  79. * @param hops ZeroTier (not IP) hops
  80. * @param packetId Packet ID
  81. * @param verb Packet verb
  82. * @param inRePacketId Packet ID in reply to (default: none)
  83. * @param inReVerb Verb in reply to (for OK/ERROR, default: VERB_NOP)
  84. * @param networkId Network ID if this packet is related to a network, 0 otherwise
  85. */
  86. void received(
  87. void *tPtr,
  88. const SharedPtr<Path> &path,
  89. unsigned int hops,
  90. uint64_t packetId,
  91. unsigned int payloadLength,
  92. Packet::Verb verb,
  93. uint64_t inRePacketId,
  94. Packet::Verb inReVerb,
  95. uint64_t networkId);
  96. /**
  97. * Check whether a path to this peer should be tried if received via e.g. RENDEZVOUS OR PUSH_DIRECT_PATHS
  98. *
  99. * @param now Current time
  100. * @param suggestingPeer Peer suggesting path (may be this peer)
  101. * @param addr Remote address
  102. * @return True if we have an active path to this destination
  103. */
  104. bool shouldTryPath(void *tPtr,int64_t now,const SharedPtr<Peer> &suggestedBy,const InetAddress &addr) const;
  105. /**
  106. * Send a HELLO to this peer at a specified physical address
  107. *
  108. * No statistics or sent times are updated here.
  109. *
  110. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  111. * @param localSocket Local source socket
  112. * @param atAddress Destination address
  113. * @param now Current time
  114. */
  115. void sendHELLO(void *tPtr,int64_t localSocket,const InetAddress &atAddress,int64_t now);
  116. /**
  117. * Send ping to this peer
  118. *
  119. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  120. * @param now Current time
  121. * @param pingAllAddressTypes If true, try to keep a link up for each address type/family
  122. */
  123. void ping(void *tPtr,int64_t now,bool pingAllAddressTypes);
  124. /**
  125. * Reset paths within a given IP scope and address family
  126. *
  127. * Resetting a path involves sending an ECHO to it and then deactivating
  128. * it until or unless it responds. This is done when we detect a change
  129. * to our external IP or another system change that might invalidate
  130. * many or all current paths.
  131. *
  132. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  133. * @param scope IP scope
  134. * @param inetAddressFamily Family e.g. AF_INET
  135. * @param now Current time
  136. */
  137. void resetWithinScope(void *tPtr,InetAddress::IpScope scope,int inetAddressFamily,int64_t now);
  138. /**
  139. * Update peer latency information
  140. *
  141. * This is called from packet parsing code.
  142. *
  143. * @param l New latency measurment (in milliseconds)
  144. */
  145. void updateLatency(unsigned int l);
  146. /**
  147. * @return Bootstrap address or NULL if none
  148. */
  149. ZT_ALWAYS_INLINE const Endpoint &bootstrap() const { return _bootstrap; }
  150. /**
  151. * Set bootstrap endpoint
  152. *
  153. * @param ep Bootstrap endpoint
  154. */
  155. ZT_ALWAYS_INLINE void setBootstrap(const Endpoint &ep)
  156. {
  157. _lock.lock();
  158. _bootstrap = ep;
  159. _lock.unlock();
  160. }
  161. /**
  162. * @return Time of last receive of anything, whether direct or relayed
  163. */
  164. ZT_ALWAYS_INLINE int64_t lastReceive() const { return _lastReceive; }
  165. /**
  166. * @return True if we've heard from this peer in less than ZT_PEER_ACTIVITY_TIMEOUT
  167. */
  168. ZT_ALWAYS_INLINE bool alive(const int64_t now) const { return ((now - _lastReceive) < ZT_PEER_ACTIVITY_TIMEOUT); }
  169. /**
  170. * @return Latency in milliseconds of best/aggregate path or 0xffff if unknown
  171. */
  172. ZT_ALWAYS_INLINE unsigned int latency() const { return _latency; }
  173. /**
  174. * @return 256-bit secret symmetric encryption key
  175. */
  176. ZT_ALWAYS_INLINE const unsigned char *key() const { return _key; }
  177. /**
  178. * Set the currently known remote version of this peer's client
  179. *
  180. * @param vproto Protocol version
  181. * @param vmaj Major version
  182. * @param vmin Minor version
  183. * @param vrev Revision
  184. */
  185. ZT_ALWAYS_INLINE void setRemoteVersion(unsigned int vproto,unsigned int vmaj,unsigned int vmin,unsigned int vrev)
  186. {
  187. _vProto = (uint16_t)vproto;
  188. _vMajor = (uint16_t)vmaj;
  189. _vMinor = (uint16_t)vmin;
  190. _vRevision = (uint16_t)vrev;
  191. }
  192. ZT_ALWAYS_INLINE unsigned int remoteVersionProtocol() const { return _vProto; }
  193. ZT_ALWAYS_INLINE unsigned int remoteVersionMajor() const { return _vMajor; }
  194. ZT_ALWAYS_INLINE unsigned int remoteVersionMinor() const { return _vMinor; }
  195. ZT_ALWAYS_INLINE unsigned int remoteVersionRevision() const { return _vRevision; }
  196. ZT_ALWAYS_INLINE bool remoteVersionKnown() const { return ((_vMajor > 0)||(_vMinor > 0)||(_vRevision > 0)); }
  197. /**
  198. * Rate limit gate for inbound WHOIS requests
  199. */
  200. ZT_ALWAYS_INLINE bool rateGateInboundWhoisRequest(const int64_t now)
  201. {
  202. if ((now - _lastWhoisRequestReceived) >= ZT_PEER_WHOIS_RATE_LIMIT) {
  203. _lastWhoisRequestReceived = now;
  204. return true;
  205. }
  206. return false;
  207. }
  208. /**
  209. * Rate limit gate for inbound PUSH_DIRECT_PATHS requests
  210. */
  211. ZT_ALWAYS_INLINE bool rateGateInboundPushDirectPaths(const int64_t now)
  212. {
  213. if ((now - _lastPushDirectPathsReceived) >= ZT_DIRECT_PATH_PUSH_INTERVAL) {
  214. _lastPushDirectPathsReceived = now;
  215. return true;
  216. }
  217. return false;
  218. }
  219. /**
  220. * Rate limit gate for inbound ECHO requests
  221. */
  222. ZT_ALWAYS_INLINE bool rateGateEchoRequest(const int64_t now)
  223. {
  224. if ((now - _lastEchoRequestReceived) >= ZT_PEER_GENERAL_RATE_LIMIT) {
  225. _lastEchoRequestReceived = now;
  226. return true;
  227. }
  228. return false;
  229. }
  230. /**
  231. * Send directly if a direct path exists
  232. *
  233. * @param tPtr Thread pointer supplied by user
  234. * @param data Data to send
  235. * @param len Length of data
  236. * @param now Current time
  237. * @return True if packet appears to have been sent, false if no path or send failed
  238. */
  239. bool sendDirect(void *tPtr,const void *data,unsigned int len,int64_t now);
  240. /**
  241. * @return Current best path
  242. */
  243. SharedPtr<Path> path(int64_t now);
  244. /**
  245. * Get all paths
  246. *
  247. * @param paths Vector of paths with the first path being the current preferred path
  248. */
  249. void getAllPaths(std::vector< SharedPtr<Path> > &paths);
  250. /**
  251. * Save the latest version of this peer to the data store
  252. */
  253. void save(void *tPtr) const;
  254. // NOTE: peer marshal/unmarshal only saves/restores the identity, locator, most
  255. // recent bootstrap address, and version information.
  256. static ZT_ALWAYS_INLINE int marshalSizeMax() { return ZT_PEER_MARSHAL_SIZE_MAX; }
  257. int marshal(uint8_t data[ZT_PEER_MARSHAL_SIZE_MAX]) const;
  258. int unmarshal(const uint8_t *restrict data,int len);
  259. private:
  260. void _prioritizePaths(int64_t now);
  261. uint8_t _key[ZT_PEER_SECRET_KEY_LENGTH];
  262. const RuntimeEnvironment *RR;
  263. volatile int64_t _lastReceive;
  264. volatile int64_t _lastWhoisRequestReceived;
  265. volatile int64_t _lastEchoRequestReceived;
  266. volatile int64_t _lastPushDirectPathsReceived;
  267. volatile int64_t _lastAttemptedP2PInit;
  268. volatile int64_t _lastTriedStaticPath;
  269. volatile int64_t _lastPrioritizedPaths;
  270. volatile unsigned int _latency;
  271. AtomicCounter __refCount;
  272. RWMutex _lock; // locks _alivePathCount, _paths, _locator, and _bootstrap.
  273. unsigned int _alivePathCount;
  274. SharedPtr<Path> _paths[ZT_MAX_PEER_NETWORK_PATHS];
  275. Identity _id;
  276. Locator _locator;
  277. Endpoint _bootstrap; // right now only InetAddress endpoints are supported for bootstrap
  278. uint16_t _vProto;
  279. uint16_t _vMajor;
  280. uint16_t _vMinor;
  281. uint16_t _vRevision;
  282. };
  283. } // namespace ZeroTier
  284. #endif