Node.hpp 12 KB

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