Node.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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: 2026-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_NODE_HPP
  14. #define ZT_NODE_HPP
  15. #include "../include/ZeroTierOne.h"
  16. #include "Bond.hpp"
  17. #include "Constants.hpp"
  18. #include "Hashtable.hpp"
  19. #include "InetAddress.hpp"
  20. #include "MAC.hpp"
  21. #include "Mutex.hpp"
  22. #include "Network.hpp"
  23. #include "NetworkController.hpp"
  24. #include "Path.hpp"
  25. #include "RuntimeEnvironment.hpp"
  26. #include "Salsa20.hpp"
  27. #include "SelfAwareness.hpp"
  28. #include <map>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <vector>
  33. // Bit mask for "expecting reply" hash
  34. #define ZT_EXPECTING_REPLIES_BUCKET_MASK1 255
  35. #define ZT_EXPECTING_REPLIES_BUCKET_MASK2 31
  36. namespace ZeroTier {
  37. class World;
  38. /**
  39. * Implementation of Node object as defined in CAPI
  40. *
  41. * The pointer returned by ZT_Node_new() is an instance of this class.
  42. */
  43. class Node : public NetworkController::Sender {
  44. public:
  45. Node(void* uptr, void* tptr, const struct ZT_Node_Callbacks* callbacks, int64_t now);
  46. virtual ~Node();
  47. // Get rid of alignment warnings on 32-bit Windows and possibly improve performance
  48. #ifdef __WINDOWS__
  49. void* operator new(size_t i)
  50. {
  51. return _mm_malloc(i, 16);
  52. }
  53. void operator delete(void* p)
  54. {
  55. _mm_free(p);
  56. }
  57. #endif
  58. // Public API Functions ----------------------------------------------------
  59. ZT_ResultCode processWirePacket(void* tptr, int64_t now, int64_t localSocket, const struct sockaddr_storage* remoteAddress, const void* packetData, unsigned int packetLength, volatile int64_t* nextBackgroundTaskDeadline);
  60. ZT_ResultCode processVirtualNetworkFrame(
  61. void* tptr,
  62. int64_t now,
  63. uint64_t nwid,
  64. uint64_t sourceMac,
  65. uint64_t destMac,
  66. unsigned int etherType,
  67. unsigned int vlanId,
  68. const void* frameData,
  69. unsigned int frameLength,
  70. volatile int64_t* nextBackgroundTaskDeadline);
  71. ZT_ResultCode processBackgroundTasks(void* tptr, int64_t now, volatile int64_t* nextBackgroundTaskDeadline);
  72. ZT_ResultCode join(uint64_t nwid, void* uptr, void* tptr);
  73. ZT_ResultCode leave(uint64_t nwid, void** uptr, void* tptr);
  74. ZT_ResultCode multicastSubscribe(void* tptr, uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi);
  75. ZT_ResultCode multicastUnsubscribe(uint64_t nwid, uint64_t multicastGroup, unsigned long multicastAdi);
  76. ZT_ResultCode orbit(void* tptr, uint64_t moonWorldId, uint64_t moonSeed);
  77. ZT_ResultCode deorbit(void* tptr, uint64_t moonWorldId);
  78. uint64_t address() const;
  79. void status(ZT_NodeStatus* status) const;
  80. ZT_PeerList* peers() const;
  81. ZT_VirtualNetworkConfig* networkConfig(uint64_t nwid) const;
  82. ZT_VirtualNetworkList* networks() const;
  83. void freeQueryResult(void* qr);
  84. int addLocalInterfaceAddress(const struct sockaddr_storage* addr);
  85. void clearLocalInterfaceAddresses();
  86. int sendUserMessage(void* tptr, uint64_t dest, uint64_t typeId, const void* data, unsigned int len);
  87. void setNetconfMaster(void* networkControllerInstance);
  88. // Internal functions ------------------------------------------------------
  89. inline int64_t now() const
  90. {
  91. return _now;
  92. }
  93. inline bool putPacket(void* tPtr, const int64_t localSocket, const InetAddress& addr, const void* data, unsigned int len, unsigned int ttl = 0)
  94. {
  95. return (_cb.wirePacketSendFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, localSocket, reinterpret_cast<const struct sockaddr_storage*>(&addr), data, len, ttl) == 0);
  96. }
  97. inline void putFrame(void* tPtr, uint64_t nwid, void** nuptr, const MAC& source, const MAC& dest, unsigned int etherType, unsigned int vlanId, const void* data, unsigned int len)
  98. {
  99. _cb.virtualNetworkFrameFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, nwid, nuptr, source.toInt(), dest.toInt(), etherType, vlanId, data, len);
  100. }
  101. inline SharedPtr<Network> network(uint64_t nwid) const
  102. {
  103. Mutex::Lock _l(_networks_m);
  104. const SharedPtr<Network>* n = _networks.get(nwid);
  105. if (n) {
  106. return *n;
  107. }
  108. return SharedPtr<Network>();
  109. }
  110. inline bool belongsToNetwork(uint64_t nwid) const
  111. {
  112. Mutex::Lock _l(_networks_m);
  113. return _networks.contains(nwid);
  114. }
  115. inline std::vector<SharedPtr<Network> > allNetworks() const
  116. {
  117. std::vector<SharedPtr<Network> > nw;
  118. Mutex::Lock _l(_networks_m);
  119. Hashtable<uint64_t, SharedPtr<Network> >::Iterator i(*const_cast<Hashtable<uint64_t, SharedPtr<Network> >*>(&_networks));
  120. uint64_t* k = (uint64_t*)0;
  121. SharedPtr<Network>* v = (SharedPtr<Network>*)0;
  122. while (i.next(k, v)) {
  123. nw.push_back(*v);
  124. }
  125. return nw;
  126. }
  127. inline std::vector<InetAddress> directPaths() const
  128. {
  129. Mutex::Lock _l(_directPaths_m);
  130. return _directPaths;
  131. }
  132. inline void postEvent(void* tPtr, ZT_Event ev, const void* md = (const void*)0)
  133. {
  134. _cb.eventCallback(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, ev, md);
  135. }
  136. inline int configureVirtualNetworkPort(void* tPtr, uint64_t nwid, void** nuptr, ZT_VirtualNetworkConfigOperation op, const ZT_VirtualNetworkConfig* nc)
  137. {
  138. return _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, nwid, nuptr, op, nc);
  139. }
  140. inline bool online() const
  141. {
  142. return _online;
  143. }
  144. inline int stateObjectGet(void* const tPtr, ZT_StateObjectType type, const uint64_t id[2], void* const data, const unsigned int maxlen)
  145. {
  146. return _cb.stateGetFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, type, id, data, maxlen);
  147. }
  148. inline void stateObjectPut(void* const tPtr, ZT_StateObjectType type, const uint64_t id[2], const void* const data, const unsigned int len)
  149. {
  150. _cb.statePutFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, type, id, data, (int)len);
  151. }
  152. inline void stateObjectDelete(void* const tPtr, ZT_StateObjectType type, const uint64_t id[2])
  153. {
  154. _cb.statePutFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, type, id, (const void*)0, -1);
  155. }
  156. bool shouldUsePathForZeroTierTraffic(void* tPtr, const Address& ztaddr, const int64_t localSocket, const InetAddress& remoteAddress);
  157. inline bool externalPathLookup(void* tPtr, const Address& ztaddr, int family, InetAddress& addr)
  158. {
  159. return ((_cb.pathLookupFunction) ? (_cb.pathLookupFunction(reinterpret_cast<ZT_Node*>(this), _uPtr, tPtr, ztaddr.toInt(), family, reinterpret_cast<struct sockaddr_storage*>(&addr)) != 0) : false);
  160. }
  161. uint64_t prng();
  162. ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage* pathNetwork, const ZT_PhysicalPathConfiguration* pathConfig);
  163. World planet() const;
  164. std::vector<World> moons() const;
  165. inline const Identity& identity() const
  166. {
  167. return _RR.identity;
  168. }
  169. inline const std::vector<InetAddress> SurfaceAddresses() const
  170. {
  171. return _RR.sa->whoami();
  172. }
  173. inline Bond* bondController() const
  174. {
  175. return _RR.bc;
  176. }
  177. /**
  178. * Register that we are expecting a reply to a packet ID
  179. *
  180. * This only uses the most significant bits of the packet ID, both to save space
  181. * and to avoid using the higher bits that can be modified during armor() to
  182. * mask against the packet send counter used for QoS detection.
  183. *
  184. * @param packetId Packet ID to expect reply to
  185. */
  186. inline void expectReplyTo(const uint64_t packetId)
  187. {
  188. const unsigned long pid2 = (unsigned long)(packetId >> 32);
  189. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  190. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
  191. }
  192. /**
  193. * Check whether a given packet ID is something we are expecting a reply to
  194. *
  195. * This only uses the most significant bits of the packet ID, both to save space
  196. * and to avoid using the higher bits that can be modified during armor() to
  197. * mask against the packet send counter used for QoS detection.
  198. *
  199. * @param packetId Packet ID to check
  200. * @return True if we're expecting a reply
  201. */
  202. inline bool expectingReplyTo(const uint64_t packetId) const
  203. {
  204. const uint32_t pid2 = (uint32_t)(packetId >> 32);
  205. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  206. for (unsigned long i = 0; i <= ZT_EXPECTING_REPLIES_BUCKET_MASK2; ++i) {
  207. if (_expectingRepliesTo[bucket][i] == pid2) {
  208. return true;
  209. }
  210. }
  211. return false;
  212. }
  213. /**
  214. * Check whether we should do potentially expensive identity verification (rate limit)
  215. *
  216. * @param now Current time
  217. * @param from Source address of packet
  218. * @return True if within rate limits
  219. */
  220. inline bool rateGateIdentityVerification(const int64_t now, const InetAddress& from)
  221. {
  222. unsigned long iph = from.rateGateHash();
  223. if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
  224. _lastIdentityVerification[iph] = now;
  225. return true;
  226. }
  227. return false;
  228. }
  229. virtual void ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address& destination, const NetworkConfig& nc, bool sendLegacyFormatConfig);
  230. virtual void ncSendRevocation(const Address& destination, const Revocation& rev);
  231. virtual void ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address& destination, NetworkController::ErrorCode errorCode, const void* errorData, unsigned int errorDataSize);
  232. inline const Address& remoteTraceTarget() const
  233. {
  234. return _remoteTraceTarget;
  235. }
  236. inline Trace::Level remoteTraceLevel() const
  237. {
  238. return _remoteTraceLevel;
  239. }
  240. inline bool localControllerHasAuthorized(const int64_t now, const uint64_t nwid, const Address& addr) const
  241. {
  242. _localControllerAuthorizations_m.lock();
  243. const int64_t* const at = _localControllerAuthorizations.get(_LocalControllerAuth(nwid, addr));
  244. _localControllerAuthorizations_m.unlock();
  245. if (at) {
  246. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  247. }
  248. return false;
  249. }
  250. inline void statsLogVerb(const unsigned int v, const unsigned int bytes)
  251. {
  252. ++_stats.inVerbCounts[v];
  253. _stats.inVerbBytes[v] += (uint64_t)bytes;
  254. }
  255. inline void setLowBandwidthMode(bool isEnabled)
  256. {
  257. _lowBandwidthMode = isEnabled;
  258. }
  259. inline bool lowBandwidthModeEnabled()
  260. {
  261. return _lowBandwidthMode;
  262. }
  263. void initMultithreading(unsigned int concurrency, bool cpuPinningEnabled);
  264. public:
  265. RuntimeEnvironment _RR;
  266. RuntimeEnvironment* RR;
  267. void* _uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  268. ZT_Node_Callbacks _cb;
  269. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  270. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  271. uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  272. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  273. int64_t _lastIdentityVerification[16384];
  274. // Statistics about stuff happening
  275. volatile ZT_NodeStatistics _stats;
  276. // Map that remembers if we have recently sent a network config to someone
  277. // querying us as a controller.
  278. struct _LocalControllerAuth {
  279. uint64_t nwid, address;
  280. _LocalControllerAuth(const uint64_t nwid_, const Address& address_) : nwid(nwid_), address(address_.toInt())
  281. {
  282. }
  283. inline unsigned long hashCode() const
  284. {
  285. return (unsigned long)(nwid ^ address);
  286. }
  287. inline bool operator==(const _LocalControllerAuth& a) const
  288. {
  289. return ((a.nwid == nwid) && (a.address == address));
  290. }
  291. inline bool operator!=(const _LocalControllerAuth& a) const
  292. {
  293. return ((a.nwid != nwid) || (a.address != address));
  294. }
  295. };
  296. Hashtable<_LocalControllerAuth, int64_t> _localControllerAuthorizations;
  297. Mutex _localControllerAuthorizations_m;
  298. Hashtable<uint64_t, SharedPtr<Network> > _networks;
  299. Mutex _networks_m;
  300. std::vector<InetAddress> _directPaths;
  301. Mutex _directPaths_m;
  302. Mutex _backgroundTasksLock;
  303. Address _remoteTraceTarget;
  304. enum Trace::Level _remoteTraceLevel;
  305. volatile int64_t _now;
  306. int64_t _lastPingCheck;
  307. int64_t _lastGratuitousPingCheck;
  308. int64_t _lastHousekeepingRun;
  309. int64_t _lastMemoizedTraceSettings;
  310. volatile int64_t _prngState[2];
  311. bool _online;
  312. bool _lowBandwidthMode;
  313. };
  314. } // namespace ZeroTier
  315. #endif