Node.hpp 12 KB

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