Node.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. ZT_ResultCode join(uint64_t nwid,void *uptr,void *tptr);
  72. ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
  73. ZT_ResultCode multicastSubscribe(void *tptr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  74. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  75. uint64_t address() const;
  76. void status(ZT_NodeStatus *status) const;
  77. ZT_PeerList *peers() const;
  78. ZT_VirtualNetworkConfig *networkConfig(uint64_t nwid) const;
  79. ZT_VirtualNetworkList *networks() const;
  80. void freeQueryResult(void *qr);
  81. int addLocalInterfaceAddress(const struct sockaddr_storage *addr);
  82. void clearLocalInterfaceAddresses();
  83. int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
  84. void setController(void *networkControllerInstance);
  85. // Internal functions ------------------------------------------------------
  86. inline int64_t now() const { return _now; }
  87. inline bool putPacket(void *tPtr,const int64_t localSocket,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0)
  88. {
  89. return (_cb.wirePacketSendFunction(
  90. reinterpret_cast<ZT_Node *>(this),
  91. _uPtr,
  92. tPtr,
  93. localSocket,
  94. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  95. data,
  96. len,
  97. ttl) == 0);
  98. }
  99. 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)
  100. {
  101. _cb.virtualNetworkFrameFunction(
  102. reinterpret_cast<ZT_Node *>(this),
  103. _uPtr,
  104. tPtr,
  105. nwid,
  106. nuptr,
  107. source.toInt(),
  108. dest.toInt(),
  109. etherType,
  110. vlanId,
  111. data,
  112. len);
  113. }
  114. inline SharedPtr<Network> network(uint64_t nwid) const
  115. {
  116. Mutex::Lock _l(_networks_m);
  117. const SharedPtr<Network> *n = _networks.get(nwid);
  118. if (n)
  119. return *n;
  120. return SharedPtr<Network>();
  121. }
  122. inline bool belongsToNetwork(uint64_t nwid) const
  123. {
  124. Mutex::Lock _l(_networks_m);
  125. return _networks.contains(nwid);
  126. }
  127. inline std::vector< SharedPtr<Network> > allNetworks() const
  128. {
  129. std::vector< SharedPtr<Network> > nw;
  130. Mutex::Lock _l(_networks_m);
  131. Hashtable< uint64_t,SharedPtr<Network> >::Iterator i(*const_cast< Hashtable< uint64_t,SharedPtr<Network> > * >(&_networks));
  132. uint64_t *k = (uint64_t *)0;
  133. SharedPtr<Network> *v = (SharedPtr<Network> *)0;
  134. while (i.next(k,v))
  135. nw.push_back(*v);
  136. return nw;
  137. }
  138. inline std::vector<InetAddress> directPaths() const
  139. {
  140. Mutex::Lock _l(_localInterfaceAddresses_m);
  141. return _localInterfaceAddresses;
  142. }
  143. 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); }
  144. inline int configureVirtualNetworkPort(void *tPtr,uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) { return _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,nwid,nuptr,op,nc); }
  145. inline bool online() const { return _online; }
  146. 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); }
  147. 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); }
  148. 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); }
  149. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Address &ztaddr,const int64_t localSocket,const InetAddress &remoteAddress);
  150. 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 ); }
  151. ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
  152. inline const Identity &identity() const { return _RR.identity; }
  153. /**
  154. * Register that we are expecting a reply to a packet ID
  155. *
  156. * This only uses the most significant bits of the packet ID, both to save space
  157. * and to avoid using the higher bits that can be modified during armor() to
  158. * mask against the packet send counter used for QoS detection.
  159. *
  160. * @param packetId Packet ID to expect reply to
  161. */
  162. inline void expectReplyTo(const uint64_t packetId)
  163. {
  164. const unsigned long pid2 = (unsigned long)(packetId >> 32);
  165. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  166. _expectingRepliesTo[bucket][_expectingRepliesToBucketPtr[bucket]++ & ZT_EXPECTING_REPLIES_BUCKET_MASK2] = (uint32_t)pid2;
  167. }
  168. /**
  169. * Check whether a given packet ID is something we are expecting a reply to
  170. *
  171. * This only uses the most significant bits of the packet ID, both to save space
  172. * and to avoid using the higher bits that can be modified during armor() to
  173. * mask against the packet send counter used for QoS detection.
  174. *
  175. * @param packetId Packet ID to check
  176. * @return True if we're expecting a reply
  177. */
  178. inline bool expectingReplyTo(const uint64_t packetId) const
  179. {
  180. const uint32_t pid2 = (uint32_t)(packetId >> 32);
  181. const unsigned long bucket = (unsigned long)(pid2 & ZT_EXPECTING_REPLIES_BUCKET_MASK1);
  182. for(unsigned long i=0;i<=ZT_EXPECTING_REPLIES_BUCKET_MASK2;++i) {
  183. if (_expectingRepliesTo[bucket][i] == pid2)
  184. return true;
  185. }
  186. return false;
  187. }
  188. /**
  189. * Check whether we should do potentially expensive identity verification (rate limit)
  190. *
  191. * @param now Current time
  192. * @param from Source address of packet
  193. * @return True if within rate limits
  194. */
  195. inline bool rateGateIdentityVerification(const int64_t now,const InetAddress &from)
  196. {
  197. unsigned long iph = from.rateGateHash();
  198. if ((now - _lastIdentityVerification[iph]) >= ZT_IDENTITY_VALIDATION_SOURCE_RATE_LIMIT) {
  199. _lastIdentityVerification[iph] = now;
  200. return true;
  201. }
  202. return false;
  203. }
  204. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  205. virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
  206. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  207. inline void setMultipathMode(uint8_t mode) { _multipathMode = mode; }
  208. inline uint8_t getMultipathMode() { return _multipathMode; }
  209. inline bool localControllerHasAuthorized(const int64_t now,const uint64_t nwid,const Address &addr) const
  210. {
  211. _localControllerAuthorizations_m.lock();
  212. const int64_t *const at = _localControllerAuthorizations.get(_LocalControllerAuth(nwid,addr));
  213. _localControllerAuthorizations_m.unlock();
  214. if (at)
  215. return ((now - *at) < (ZT_NETWORK_AUTOCONF_DELAY * 3));
  216. return false;
  217. }
  218. private:
  219. RuntimeEnvironment _RR;
  220. RuntimeEnvironment *RR;
  221. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  222. ZT_Node_Callbacks _cb;
  223. // For tracking packet IDs to filter out OK/ERROR replies to packets we did not send
  224. uint8_t _expectingRepliesToBucketPtr[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1];
  225. uint32_t _expectingRepliesTo[ZT_EXPECTING_REPLIES_BUCKET_MASK1 + 1][ZT_EXPECTING_REPLIES_BUCKET_MASK2 + 1];
  226. // Time of last identity verification indexed by InetAddress.rateGateHash() -- used in IncomingPacket::_doHELLO() via rateGateIdentityVerification()
  227. int64_t _lastIdentityVerification[16384];
  228. /* Map that remembers if we have recently sent a network config to someone
  229. * querying us as a controller. This is an optimization to allow network
  230. * controllers to know whether to treat things like multicast queries the
  231. * way authorized members would be treated without requiring an extra cert
  232. * validation. */
  233. struct _LocalControllerAuth
  234. {
  235. uint64_t nwid,address;
  236. _LocalControllerAuth(const uint64_t nwid_,const Address &address_) : nwid(nwid_),address(address_.toInt()) {}
  237. inline unsigned long hashCode() const { return (unsigned long)(nwid ^ address); }
  238. inline bool operator==(const _LocalControllerAuth &a) const { return ((a.nwid == nwid)&&(a.address == address)); }
  239. inline bool operator!=(const _LocalControllerAuth &a) const { return ((a.nwid != nwid)||(a.address != address)); }
  240. };
  241. Hashtable< _LocalControllerAuth,int64_t > _localControllerAuthorizations;
  242. Mutex _localControllerAuthorizations_m;
  243. // Curreently joined networks
  244. Hashtable< uint64_t,SharedPtr<Network> > _networks;
  245. Mutex _networks_m;
  246. // Local interface addresses as reported by the code harnessing this Node
  247. std::vector<InetAddress> _localInterfaceAddresses;
  248. Mutex _localInterfaceAddresses_m;
  249. // Lock to ensure processBackgroundTasks never gets run concurrently
  250. Mutex _backgroundTasksLock;
  251. uint8_t _multipathMode;
  252. volatile int64_t _now;
  253. int64_t _lastPing;
  254. int64_t _lastHousekeepingRun;
  255. int64_t _lastNetworkHousekeepingRun;
  256. bool _online;
  257. };
  258. } // namespace ZeroTier
  259. #endif