2
0

Node.hpp 12 KB

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