Node.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 <cstdio>
  16. #include <cstdlib>
  17. #include <cstring>
  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. class Locator;
  36. /**
  37. * Implementation of Node object as defined in CAPI
  38. *
  39. * The pointer returned by ZT_Node_new() is an instance of this class.
  40. */
  41. class Node : public NetworkController::Sender
  42. {
  43. public:
  44. Node(void *uPtr, void *tPtr, const struct ZT_Node_Callbacks *callbacks, int64_t now);
  45. virtual ~Node();
  46. // Get rid of alignment warnings on 32-bit Windows and possibly improve performance
  47. #ifdef __WINDOWS__
  48. void * operator new(size_t i) { return _mm_malloc(i,16); }
  49. void operator delete(void* p) { _mm_free(p); }
  50. #endif
  51. // Public API Functions ----------------------------------------------------
  52. ZT_ResultCode processWirePacket(
  53. void *tptr,
  54. int64_t now,
  55. int64_t localSocket,
  56. const struct sockaddr_storage *remoteAddress,
  57. const void *packetData,
  58. unsigned int packetLength,
  59. volatile int64_t *nextBackgroundTaskDeadline);
  60. ZT_ResultCode processVirtualNetworkFrame(
  61. void *tptr,
  62. int64_t now,
  63. uint64_t nwid,
  64. uint64_t sourceMac,
  65. uint64_t destMac,
  66. unsigned int etherType,
  67. unsigned int vlanId,
  68. const void *frameData,
  69. unsigned int frameLength,
  70. volatile int64_t *nextBackgroundTaskDeadline);
  71. ZT_ResultCode processBackgroundTasks(void *tPtr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline);
  72. ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
  73. ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
  74. ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  75. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  76. ZT_ResultCode addRoot(const char *identity);
  77. ZT_ResultCode removeRoot(const char *identity);
  78. uint64_t address() const;
  79. void status(ZT_NodeStatus *status) const;
  80. ZT_PeerList *peers() const;
  81. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  82. ZT_VirtualNetworkList *networks() const;
  83. void setNetworkUserPtr(uint64_t nwid,void *ptr);
  84. void freeQueryResult(void *qr);
  85. void setInterfaceAddresses(const ZT_InterfaceAddress *addrs,unsigned int addrCount);
  86. int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
  87. void setController(void *networkControllerInstance);
  88. // Internal functions ------------------------------------------------------
  89. ZT_ALWAYS_INLINE int64_t now() const { return _now; }
  90. ZT_ALWAYS_INLINE bool putPacket(void *tPtr,const int64_t localSocket,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  91. {
  92. return (_cb.wirePacketSendFunction(
  93. reinterpret_cast<ZT_Node *>(this),
  94. _uPtr,
  95. tPtr,
  96. localSocket,
  97. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  98. data,
  99. len,
  100. ttl) == 0);
  101. }
  102. 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)
  103. {
  104. _cb.virtualNetworkFrameFunction(
  105. reinterpret_cast<ZT_Node *>(this),
  106. _uPtr,
  107. tPtr,
  108. nwid,
  109. nuptr,
  110. source.toInt(),
  111. dest.toInt(),
  112. etherType,
  113. vlanId,
  114. data,
  115. len);
  116. }
  117. ZT_ALWAYS_INLINE SharedPtr<Network> network(uint64_t nwid) const
  118. {
  119. Mutex::Lock _l(_networks_m);
  120. const SharedPtr<Network> *n = _networks.get(nwid);
  121. if (n)
  122. return *n;
  123. return SharedPtr<Network>();
  124. }
  125. ZT_ALWAYS_INLINE std::vector<ZT_InterfaceAddress> directPaths() const
  126. {
  127. Mutex::Lock _l(_localInterfaceAddresses_m);
  128. return _localInterfaceAddresses;
  129. }
  130. 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); }
  131. 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); }
  132. ZT_ALWAYS_INLINE bool online() const { return _online; }
  133. 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); }
  134. 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); }
  135. 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); }
  136. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress);
  137. bool externalPathLookup(void *tPtr,const Identity &id,int family,InetAddress &addr);
  138. ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
  139. ZT_ALWAYS_INLINE const Identity &identity() const { return _RR.identity; }
  140. /**
  141. * Register that we are expecting a reply to a packet ID
  142. *
  143. * This only uses the most significant bits of the packet ID, both to save space
  144. * and to avoid using the higher bits that can be modified during armor() to
  145. * mask against the packet send counter used for QoS detection.
  146. *
  147. * @param packetId Packet ID to expect reply to
  148. */
  149. ZT_ALWAYS_INLINE void expectReplyTo(const uint64_t packetId)
  150. {
  151. const unsigned long pid2 = (unsigned long)(packetId >> 32U);
  152. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  153. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
  154. }
  155. /**
  156. * Check whether a given packet ID is something we are expecting a reply to
  157. *
  158. * This only uses the most significant bits of the packet ID, both to save space
  159. * and to avoid using the higher bits that can be modified during armor() to
  160. * mask against the packet send counter used for QoS detection.
  161. *
  162. * @param packetId Packet ID to check
  163. * @return True if we're expecting a reply
  164. */
  165. ZT_ALWAYS_INLINE bool expectingReplyTo(const uint64_t packetId) const
  166. {
  167. const uint32_t pid2 = (uint32_t)(packetId >> 32);
  168. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  169. for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
  170. if (_expectingRepliesTo[bucket][i] == pid2)
  171. return true;
  172. }
  173. return false;
  174. }
  175. /**
  176. * Check whether we should do potentially expensive identity verification (rate limit)
  177. *
  178. * @param now Current time
  179. * @param from Source address of packet
  180. * @return True if within rate limits
  181. */
  182. ZT_ALWAYS_INLINE bool rateGateIdentityVerification(const int64_t now,const InetAddress &from)
  183. {
  184. unsigned long iph = from.rateGateHash();
  185. if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
  186. _lastIdentityVerification[iph] = now;
  187. return true;
  188. }
  189. return false;
  190. }
  191. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  192. virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
  193. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  194. inline bool localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address &addr) const
  195. {
  196. _localControllerAuthorizations_m.lock();
  197. const int64_t *const at = _localControllerAuthorizations.get(_LocalControllerAuth(nwid,addr));
  198. _localControllerAuthorizations_m.unlock();
  199. if (at)
  200. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  201. return false;
  202. }
  203. inline void setMultipathMode(uint8_t mode) { _multipathMode = mode; }
  204. inline uint8_t getMultipathMode() { return _multipathMode; }
  205. private:
  206. RuntimeEnvironment _RR;
  207. RuntimeEnvironment *RR;
  208. ZT_Node_Callbacks _cb;
  209. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  210. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  211. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  212. uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  213. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  214. int64_t _lastIdentityVerification[16384];
  215. /* Map that remembers if we have recently sent a network config to someone
  216. * querying us as a controller. This is an optimization to allow network
  217. * controllers to know whether to treat things like multicast queries the
  218. * way authorized members would be treated without requiring an extra cert
  219. * validation. */
  220. struct _LocalControllerAuth
  221. {
  222. uint64_t nwid,address;
  223. ZT_ALWAYS_INLINE _LocalControllerAuth(const uint64_t nwid_,const Address &address_) : nwid(nwid_),address(address_.toInt()) {}
  224. ZT_ALWAYS_INLINE unsigned long hashCode() const { return (unsigned long)(nwid ^ address); }
  225. ZT_ALWAYS_INLINE bool operator==(const _LocalControllerAuth &a) const { return ((a.nwid == nwid)&&(a.address == address)); }
  226. ZT_ALWAYS_INLINE bool operator!=(const _LocalControllerAuth &a) const { return ((a.nwid != nwid)||(a.address != address)); }
  227. };
  228. Hashtable< _LocalControllerAuth,int64_t > _localControllerAuthorizations;
  229. Hashtable< uint64_t,SharedPtr<Network> > _networks;
  230. std::vector< ZT_InterfaceAddress > _localInterfaceAddresses;
  231. Mutex _localControllerAuthorizations_m;
  232. Mutex _networks_m;
  233. Mutex _localInterfaceAddresses_m;
  234. Mutex _backgroundTasksLock;
  235. uint8_t _multipathMode;
  236. volatile int64_t _now;
  237. int64_t _lastPing;
  238. int64_t _lastHousekeepingRun;
  239. int64_t _lastNetworkHousekeepingRun;
  240. int64_t _lastDynamicRootUpdate;
  241. bool _online;
  242. };
  243. } // namespace ZeroTier
  244. #endif