Node.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. * Copyright (c)2019 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: 2023-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. // Bit mask for "expecting reply" hash
  32. #define ZT_EXPECTING_REPLIES_BUCKET_MASK1 255
  33. #define ZT_EXPECTING_REPLIES_BUCKET_MASK2 31
  34. namespace ZeroTier {
  35. /**
  36. * Implementation of Node object as defined in CAPI
  37. *
  38. * The pointer returned by ZT_Node_new() is an instance of this class.
  39. */
  40. class Node : public NetworkController::Sender
  41. {
  42. public:
  43. Node(void *uptr,void *tptr,const struct ZT_Node_Callbacks *callbacks,int64_t now);
  44. virtual ~Node();
  45. // Get rid of alignment warnings on 32-bit Windows and possibly improve performance
  46. #ifdef __WINDOWS__
  47. void * operator new(size_t i) { return _mm_malloc(i,16); }
  48. void operator delete(void* p) { _mm_free(p); }
  49. #endif
  50. // Public API Functions ----------------------------------------------------
  51. ZT_ResultCode processWirePacket(
  52. void *tptr,
  53. int64_t now,
  54. int64_t localSocket,
  55. const struct sockaddr_storage *remoteAddress,
  56. const void *packetData,
  57. unsigned int packetLength,
  58. volatile int64_t *nextBackgroundTaskDeadline);
  59. ZT_ResultCode processVirtualNetworkFrame(
  60. void *tptr,
  61. int64_t now,
  62. uint64_t nwid,
  63. uint64_t sourceMac,
  64. uint64_t destMac,
  65. unsigned int etherType,
  66. unsigned int vlanId,
  67. const void *frameData,
  68. unsigned int frameLength,
  69. volatile int64_t *nextBackgroundTaskDeadline);
  70. ZT_ResultCode processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline);
  71. void processDNSResult(
  72. void *tptr,
  73. uintptr_t dnsRequestID,
  74. const char *name,
  75. enum ZT_DNSRecordType recordType,
  76. const void *result,
  77. unsigned int resultLength,
  78. int resultIsString);
  79. ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
  80. ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
  81. ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  82. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  83. ZT_RootList *listRoots(int64_t now);
  84. enum ZT_ResultCode setRoot(const char *name,const void *locator,unsigned int locatorSize);
  85. enum ZT_ResultCode removeRoot(const char *name);
  86. uint64_t address() const;
  87. void status(ZT_NodeStatus *status) const;
  88. ZT_PeerList *peers() const;
  89. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  90. ZT_VirtualNetworkList *networks() const;
  91. void setNetworkUserPtr(uint64_t nwid,void *ptr);
  92. void freeQueryResult(void *qr);
  93. int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
  94. void clearLocalInterfaceAddresses();
  95. int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
  96. void setController(void *networkControllerInstance);
  97. // Internal functions ------------------------------------------------------
  98. ZT_ALWAYS_INLINE int64_t now() const { return _now; }
  99. ZT_ALWAYS_INLINE bool putPacket(void *tPtr,const int64_t localSocket,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  100. {
  101. return (_cb.wirePacketSendFunction(
  102. reinterpret_cast<ZT_Node *>(this),
  103. _uPtr,
  104. tPtr,
  105. localSocket,
  106. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  107. data,
  108. len,
  109. ttl) == 0);
  110. }
  111. ZT_ALWAYS_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)
  112. {
  113. _cb.virtualNetworkFrameFunction(
  114. reinterpret_cast<ZT_Node *>(this),
  115. _uPtr,
  116. tPtr,
  117. nwid,
  118. nuptr,
  119. source.toInt(),
  120. dest.toInt(),
  121. etherType,
  122. vlanId,
  123. data,
  124. len);
  125. }
  126. ZT_ALWAYS_INLINE SharedPtr<Network> network(uint64_t nwid) const
  127. {
  128. Mutex::Lock _l(_networks_m);
  129. const SharedPtr<Network> *n = _networks.get(nwid);
  130. if (n)
  131. return *n;
  132. return SharedPtr<Network>();
  133. }
  134. ZT_ALWAYS_INLINE bool belongsToNetwork(uint64_t nwid) const
  135. {
  136. Mutex::Lock _l(_networks_m);
  137. return _networks.contains(nwid);
  138. }
  139. ZT_ALWAYS_INLINE std::vector< SharedPtr<Network> > allNetworks() const
  140. {
  141. std::vector< SharedPtr<Network> > nw;
  142. Mutex::Lock _l(_networks_m);
  143. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > * >(&_networks));
  144. uint64_t *k = (uint64_t *)0;
  145. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  146. while (i.next(k,v))
  147. nw.push_back(*v);
  148. return nw;
  149. }
  150. ZT_ALWAYS_INLINE std::vector<InetAddress> directPaths() const
  151. {
  152. Mutex::Lock _l(_localInterfaceAddresses_m);
  153. return _localInterfaceAddresses;
  154. }
  155. ZT_ALWAYS_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); }
  156. ZT_ALWAYS_INLINE void configureVirtualNetworkPort(void *tPtr,uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) { _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,nwid,nuptr,op,nc); }
  157. ZT_ALWAYS_INLINE bool online() const { return _online; }
  158. ZT_ALWAYS_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); }
  159. ZT_ALWAYS_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); }
  160. ZT_ALWAYS_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); }
  161. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress);
  162. ZT_ALWAYS_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 ); }
  163. ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
  164. ZT_ALWAYS_INLINE const Identity &identity() const { return _RR.identity; }
  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. ZT_ALWAYS_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. ZT_ALWAYS_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. return false;
  199. }
  200. /**
  201. * Check whether we should do potentially expensive identity verification (rate limit)
  202. *
  203. * @param now Current time
  204. * @param from Source address of packet
  205. * @return True if within rate limits
  206. */
  207. ZT_ALWAYS_INLINE bool rateGateIdentityVerification(const int64_t now,const InetAddress &from)
  208. {
  209. unsigned long iph = from.rateGateHash();
  210. if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
  211. _lastIdentityVerification[iph] = now;
  212. return true;
  213. }
  214. return false;
  215. }
  216. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  217. virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
  218. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  219. ZT_ALWAYS_INLINE void setMultipathMode(uint8_t mode) { _multipathMode = mode; }
  220. ZT_ALWAYS_INLINE uint8_t getMultipathMode() { return _multipathMode; }
  221. ZT_ALWAYS_INLINE bool localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address &addr) const
  222. {
  223. _localControllerAuthorizations_m.lock();
  224. const int64_t *const at = _localControllerAuthorizations.get(_LocalControllerAuth(nwid,addr));
  225. _localControllerAuthorizations_m.unlock();
  226. if (at)
  227. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  228. return false;
  229. }
  230. private:
  231. RuntimeEnvironment _RR;
  232. RuntimeEnvironment *RR;
  233. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  234. ZT_Node_Callbacks _cb;
  235. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  236. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  237. uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  238. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  239. int64_t _lastIdentityVerification[16384];
  240. /* Map that remembers if we have recently sent a network config to someone
  241. * querying us as a controller. This is an optimization to allow network
  242. * controllers to know whether to treat things like multicast queries the
  243. * way authorized members would be treated without requiring an extra cert
  244. * validation. */
  245. struct _LocalControllerAuth
  246. {
  247. uint64_t nwid,address;
  248. ZT_ALWAYS_INLINE _LocalControllerAuth(const uint64_t nwid_,const Address &address_) : nwid(nwid_),address(address_.toInt()) {}
  249. ZT_ALWAYS_INLINE unsigned long hashCode() const { return (unsigned long)(nwid ^ address); }
  250. ZT_ALWAYS_INLINE bool operator==(const _LocalControllerAuth &a) const { return ((a.nwid == nwid)&&(a.address == address)); }
  251. ZT_ALWAYS_INLINE bool operator!=(const _LocalControllerAuth &a) const { return ((a.nwid != nwid)||(a.address != address)); }
  252. };
  253. Hashtable< _LocalControllerAuth,int64_t > _localControllerAuthorizations;
  254. Mutex _localControllerAuthorizations_m;
  255. // Curreently joined networks
  256. Hashtable< uint64_t,SharedPtr<Network> > _networks;
  257. Mutex _networks_m;
  258. // Local interface addresses as reported by the code harnessing this Node
  259. std::vector<InetAddress> _localInterfaceAddresses;
  260. Mutex _localInterfaceAddresses_m;
  261. // Lock to ensure processBackgroundTasks never gets run concurrently
  262. Mutex _backgroundTasksLock;
  263. uint8_t _multipathMode;
  264. volatile int64_t _now;
  265. int64_t _lastPing;
  266. int64_t _lastHousekeepingRun;
  267. int64_t _lastNetworkHousekeepingRun;
  268. int64_t _lastDynamicRootUpdate;
  269. bool _online;
  270. };
  271. } // namespace ZeroTier
  272. #endif