Node.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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<ZT_InterfaceAddress> directPaths() const
  151. {
  152. Mutex::Lock _l(_localInterfaceAddresses_m);
  153. return _localInterfaceAddresses;
  154. }
  155. void setInterfaceAddresses(const ZT_InterfaceAddress *addrs,unsigned int addrCount);
  156. 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); }
  157. 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); }
  158. ZT_ALWAYS_INLINE bool online() const { return _online; }
  159. 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); }
  160. 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); }
  161. 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); }
  162. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress);
  163. 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 ); }
  164. ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
  165. ZT_ALWAYS_INLINE const Identity &identity() const { return _RR.identity; }
  166. /**
  167. * Register that we are expecting a reply to a packet ID
  168. *
  169. * This only uses the most significant bits of the packet ID, both to save space
  170. * and to avoid using the higher bits that can be modified during armor() to
  171. * mask against the packet send counter used for QoS detection.
  172. *
  173. * @param packetId Packet ID to expect reply to
  174. */
  175. ZT_ALWAYS_INLINE void expectReplyTo(const uint64_t packetId)
  176. {
  177. const unsigned long pid2 = (unsigned long)(packetId >> 32);
  178. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  179. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
  180. }
  181. /**
  182. * Check whether a given packet ID is something we are expecting a reply to
  183. *
  184. * This only uses the most significant bits of the packet ID, both to save space
  185. * and to avoid using the higher bits that can be modified during armor() to
  186. * mask against the packet send counter used for QoS detection.
  187. *
  188. * @param packetId Packet ID to check
  189. * @return True if we're expecting a reply
  190. */
  191. ZT_ALWAYS_INLINE bool expectingReplyTo(const uint64_t packetId) const
  192. {
  193. const uint32_t pid2 = (uint32_t)(packetId >> 32);
  194. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  195. for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
  196. if (_expectingRepliesTo[bucket][i] == pid2)
  197. return true;
  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. ZT_ALWAYS_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);
  220. ZT_ALWAYS_INLINE void setMultipathMode(uint8_t mode) { _multipathMode = mode; }
  221. ZT_ALWAYS_INLINE uint8_t getMultipathMode() { return _multipathMode; }
  222. ZT_ALWAYS_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. return false;
  230. }
  231. private:
  232. RuntimeEnvironment _RR;
  233. RuntimeEnvironment *RR;
  234. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  235. ZT_Node_Callbacks _cb;
  236. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  237. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  238. uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  239. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  240. int64_t _lastIdentityVerification[16384];
  241. /* Map that remembers if we have recently sent a network config to someone
  242. * querying us as a controller. This is an optimization to allow network
  243. * controllers to know whether to treat things like multicast queries the
  244. * way authorized members would be treated without requiring an extra cert
  245. * validation. */
  246. struct _LocalControllerAuth
  247. {
  248. uint64_t nwid,address;
  249. ZT_ALWAYS_INLINE _LocalControllerAuth(const uint64_t nwid_,const Address &address_) : nwid(nwid_),address(address_.toInt()) {}
  250. ZT_ALWAYS_INLINE unsigned long hashCode() const { return (unsigned long)(nwid ^ address); }
  251. ZT_ALWAYS_INLINE bool operator==(const _LocalControllerAuth &a) const { return ((a.nwid == nwid)&&(a.address == address)); }
  252. ZT_ALWAYS_INLINE bool operator!=(const _LocalControllerAuth &a) const { return ((a.nwid != nwid)||(a.address != address)); }
  253. };
  254. Hashtable< _LocalControllerAuth,int64_t > _localControllerAuthorizations;
  255. Mutex _localControllerAuthorizations_m;
  256. Hashtable< uint64_t,SharedPtr<Network> > _networks;
  257. Mutex _networks_m;
  258. std::vector<ZT_InterfaceAddress> _localInterfaceAddresses;
  259. Mutex _localInterfaceAddresses_m;
  260. Mutex _backgroundTasksLock;
  261. uint8_t _multipathMode;
  262. volatile int64_t _now;
  263. int64_t _lastPing;
  264. int64_t _lastHousekeepingRun;
  265. int64_t _lastNetworkHousekeepingRun;
  266. int64_t _lastDynamicRootUpdate;
  267. bool _online;
  268. };
  269. } // namespace ZeroTier
  270. #endif