Node.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * Copyright (c)2013-2020 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: 2024-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 "Constants.hpp"
  16. #include "RuntimeEnvironment.hpp"
  17. #include "InetAddress.hpp"
  18. #include "Mutex.hpp"
  19. #include "MAC.hpp"
  20. #include "Network.hpp"
  21. #include "Path.hpp"
  22. #include "Salsa20.hpp"
  23. #include "NetworkController.hpp"
  24. #include "Buf.hpp"
  25. #include "Map.hpp"
  26. #include <cstdio>
  27. #include <cstdlib>
  28. #include <cstring>
  29. #include <vector>
  30. #include <map>
  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. /**
  47. * Perform any operations that should be done prior to deleting a Node
  48. *
  49. * This is technically optional but recommended.
  50. *
  51. * @param tPtr Thread pointer to pass through to callbacks
  52. */
  53. void shutdown(void *tPtr);
  54. // Get rid of alignment warnings on 32-bit Windows and possibly improve performance
  55. #ifdef __WINDOWS__
  56. void * operator new(size_t i) { return _mm_malloc(i,16); }
  57. void operator delete(void* p) { _mm_free(p); }
  58. #endif
  59. // Public API Functions ---------------------------------------------------------------------------------------------
  60. ZT_ResultCode processWirePacket(
  61. void *tPtr,
  62. int64_t now,
  63. int64_t localSocket,
  64. const struct sockaddr_storage *remoteAddress,
  65. SharedPtr<Buf> &packetData,
  66. unsigned int packetLength,
  67. volatile int64_t *nextBackgroundTaskDeadline);
  68. ZT_ResultCode processVirtualNetworkFrame(
  69. void *tPtr,
  70. int64_t now,
  71. uint64_t nwid,
  72. uint64_t sourceMac,
  73. uint64_t destMac,
  74. unsigned int etherType,
  75. unsigned int vlanId,
  76. SharedPtr<Buf> &frameData,
  77. unsigned int frameLength,
  78. volatile int64_t *nextBackgroundTaskDeadline);
  79. ZT_ResultCode processBackgroundTasks(void *tPtr, int64_t now, volatile int64_t *nextBackgroundTaskDeadline);
  80. ZT_ResultCode join(uint64_t nwid,const ZT_Fingerprint *controllerFingerprint,void *uptr,void *tptr);
  81. ZT_ResultCode leave(uint64_t nwid,void **uptr,void *tptr);
  82. ZT_ResultCode multicastSubscribe(void *tPtr,uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  83. ZT_ResultCode multicastUnsubscribe(uint64_t nwid,uint64_t multicastGroup,unsigned long multicastAdi);
  84. ZT_ResultCode addRoot(void *tPtr,const ZT_Identity *identity,const sockaddr_storage *bootstrap);
  85. ZT_ResultCode removeRoot(void *tPtr,const ZT_Identity *identity);
  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. void setInterfaceAddresses(const ZT_InterfaceAddress *addrs,unsigned int addrCount);
  94. int sendUserMessage(void *tptr,uint64_t dest,uint64_t typeId,const void *data,unsigned int len);
  95. void setController(void *networkControllerInstance);
  96. // Internal functions -----------------------------------------------------------------------------------------------
  97. /**
  98. * @return Most recent time value supplied to core via API
  99. */
  100. ZT_INLINE int64_t now() const noexcept { return _now; }
  101. /**
  102. * Send packet to to the physical wire via callback
  103. *
  104. * @param tPtr Thread pointer
  105. * @param localSocket Local socket or -1 to use all/any
  106. * @param addr Destination address
  107. * @param data Data to send
  108. * @param len Length in bytes
  109. * @param ttl TTL or 0 for default/max
  110. * @return True if send appears successful
  111. */
  112. ZT_INLINE bool putPacket(void *tPtr,const int64_t localSocket,const InetAddress &addr,const void *data,unsigned int len,unsigned int ttl = 0) noexcept
  113. {
  114. return (_cb.wirePacketSendFunction(
  115. reinterpret_cast<ZT_Node *>(this),
  116. _uPtr,
  117. tPtr,
  118. localSocket,
  119. reinterpret_cast<const struct sockaddr_storage *>(&addr),
  120. data,
  121. len,
  122. ttl) == 0);
  123. }
  124. /**
  125. * Inject frame into virtual Ethernet tap
  126. *
  127. * @param tPtr Thread pointer
  128. * @param nwid Network ID
  129. * @param nuptr Network-associated user pointer
  130. * @param source Source MAC address
  131. * @param dest Destination MAC address
  132. * @param etherType 16-bit Ethernet type
  133. * @param vlanId Ethernet VLAN ID (currently unused)
  134. * @param data Ethernet frame data
  135. * @param len Ethernet frame length in bytes
  136. */
  137. ZT_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) noexcept
  138. {
  139. _cb.virtualNetworkFrameFunction(
  140. reinterpret_cast<ZT_Node *>(this),
  141. _uPtr,
  142. tPtr,
  143. nwid,
  144. nuptr,
  145. source.toInt(),
  146. dest.toInt(),
  147. etherType,
  148. vlanId,
  149. data,
  150. len);
  151. }
  152. /**
  153. * @param nwid Network ID
  154. * @return Network associated with ID
  155. */
  156. ZT_INLINE SharedPtr<Network> network(uint64_t nwid) const noexcept
  157. {
  158. RWMutex::RLock l(_networks_m);
  159. const SharedPtr<Network> *const n = _networks.get(nwid);
  160. if (n)
  161. return *n;
  162. return SharedPtr<Network>();
  163. }
  164. /**
  165. * @return Known local interface addresses for this node
  166. */
  167. ZT_INLINE std::vector<ZT_InterfaceAddress> localInterfaceAddresses() const
  168. {
  169. Mutex::Lock _l(_localInterfaceAddresses_m);
  170. return _localInterfaceAddresses;
  171. }
  172. /**
  173. * Post an event via external callback
  174. *
  175. * @param tPtr Thread pointer
  176. * @param ev Event object
  177. * @param md Event data or NULL if none
  178. */
  179. ZT_INLINE void postEvent(void *tPtr,ZT_Event ev,const void *md = nullptr) noexcept
  180. {
  181. _cb.eventCallback(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,ev,md);
  182. }
  183. /**
  184. * Post network port configuration via external callback
  185. *
  186. * @param tPtr Thread pointer
  187. * @param nwid Network ID
  188. * @param nuptr Network-associated user pointer
  189. * @param op Config operation or event type
  190. * @param nc Network config info
  191. */
  192. ZT_INLINE void configureVirtualNetworkPort(void *tPtr,uint64_t nwid,void **nuptr,ZT_VirtualNetworkConfigOperation op,const ZT_VirtualNetworkConfig *nc) noexcept
  193. {
  194. _cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,nwid,nuptr,op,nc);
  195. }
  196. /**
  197. * @return True if node appears online
  198. */
  199. ZT_INLINE bool online() const noexcept { return _online; }
  200. /**
  201. * Get a state object
  202. *
  203. * @param tPtr Thread pointer
  204. * @param type Object type to get
  205. * @param id Object ID
  206. * @return Vector containing data or empty vector if not found or empty
  207. */
  208. std::vector<uint8_t> stateObjectGet(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2]);
  209. /**
  210. * Store a state object
  211. *
  212. * @param tPtr Thread pointer
  213. * @param type Object type to get
  214. * @param id Object ID
  215. * @param data Data to store
  216. * @param len Length of data
  217. */
  218. ZT_INLINE void stateObjectPut(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2],const void *const data,const unsigned int len) noexcept
  219. {
  220. if (_cb.statePutFunction)
  221. _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,data,(int)len);
  222. }
  223. /**
  224. * Delete a state object
  225. *
  226. * @param tPtr Thread pointer
  227. * @param type Object type to delete
  228. * @param id Object ID
  229. */
  230. ZT_INLINE void stateObjectDelete(void *const tPtr,ZT_StateObjectType type,const uint64_t id[2]) noexcept
  231. {
  232. if (_cb.statePutFunction)
  233. _cb.statePutFunction(reinterpret_cast<ZT_Node *>(this),_uPtr,tPtr,type,id,(const void *)0,-1);
  234. }
  235. /**
  236. * Check whether a path should be used for ZeroTier traffic
  237. *
  238. * This performs internal checks and also calls out to an external callback if one is defined.
  239. *
  240. * @param tPtr Thread pointer
  241. * @param id Identity of peer
  242. * @param localSocket Local socket or -1 if unknown
  243. * @param remoteAddress Remote address
  244. * @return True if path should be used
  245. */
  246. bool shouldUsePathForZeroTierTraffic(void *tPtr,const Identity &id,int64_t localSocket,const InetAddress &remoteAddress);
  247. /**
  248. * Query callback for a physical address for a peer
  249. *
  250. * @param tPtr Thread pointer
  251. * @param id Full identity of ZeroTier node
  252. * @param family Desired address family or -1 for any
  253. * @param addr Buffer to store address (result paramter)
  254. * @return True if addr was filled with something
  255. */
  256. bool externalPathLookup(void *tPtr,const Identity &id,int family,InetAddress &addr);
  257. /**
  258. * Set physical path configuration
  259. *
  260. * @param pathNetwork Physical path network/netmask bits (CIDR notation)
  261. * @param pathConfig Path configuration
  262. * @return Return to pass through to external API
  263. */
  264. ZT_ResultCode setPhysicalPathConfiguration(const struct sockaddr_storage *pathNetwork,const ZT_PhysicalPathConfiguration *pathConfig);
  265. /**
  266. * @return This node's identity
  267. */
  268. ZT_INLINE const Identity &identity() const noexcept { return _RR.identity; }
  269. /**
  270. * @return True if aggressive NAT-traversal mechanisms like scanning of <1024 ports are enabled
  271. */
  272. ZT_INLINE bool natMustDie() const noexcept { return _natMustDie; }
  273. /**
  274. * Wake any peers with the given address by calling their alarm() methods at or after the specified time
  275. *
  276. * @param peerAddress Peer address
  277. * @param triggerTime Time alarm should go off
  278. */
  279. ZT_INLINE void setPeerAlarm(const Address &peerAddress,const int64_t triggerTime)
  280. {
  281. RWMutex::Lock l(_peerAlarms_l);
  282. int64_t &t = _peerAlarms[peerAddress];
  283. if ((t <= 0)||(t > triggerTime))
  284. t = triggerTime;
  285. }
  286. /**
  287. * Check whether a local controller has authorized a member on a network
  288. *
  289. * This is used by controllers to avoid needless certificate checks when we already
  290. * know if this has occurred. It's a bit of a hack but saves a massive amount of
  291. * controller CPU. It's easiest to put this here, and it imposes no overhead on
  292. * non-controllers.
  293. *
  294. * @param now Current time
  295. * @param nwid Network ID
  296. * @param addr Member address to check
  297. * @return True if member has been authorized
  298. */
  299. bool localControllerHasAuthorized(int64_t now,uint64_t nwid,const Address &addr) const;
  300. // Implementation of NetworkController::Sender interface
  301. virtual void ncSendConfig(uint64_t nwid,uint64_t requestPacketId,const Address &destination,const NetworkConfig &nc,bool sendLegacyFormatConfig);
  302. virtual void ncSendRevocation(const Address &destination,const Revocation &rev);
  303. virtual void ncSendError(uint64_t nwid,uint64_t requestPacketId,const Address &destination,NetworkController::ErrorCode errorCode);
  304. private:
  305. RuntimeEnvironment _RR;
  306. void *_objects;
  307. RuntimeEnvironment *RR;
  308. ZT_Node_Callbacks _cb;
  309. void *_uPtr; // _uptr (lower case) is reserved in Visual Studio :P
  310. // Addresses of peers that want to have their alarm() function called at some point in the future.
  311. // These behave like weak references in that the node looks them up in Topology and calls alarm()
  312. // in each peer if that peer object is still held in memory. Calling alarm() unnecessarily on a peer
  313. // is harmless. This just exists as an optimization to prevent having to iterate through all peers
  314. // on every processBackgroundTasks call. A simple map<> is used here because there are usually only
  315. // a few of these, if any.
  316. std::map<Address,int64_t> _peerAlarms;
  317. RWMutex _peerAlarms_l;
  318. // Map that remembers if we have recently sent a network config to someone
  319. // querying us as a controller. This is an optimization to allow network
  320. // controllers to know whether to treat things like multicast queries the
  321. // way authorized members would be treated without requiring an extra cert
  322. // validation.
  323. struct _LocalControllerAuth
  324. {
  325. uint64_t nwid,address;
  326. ZT_INLINE _LocalControllerAuth(const uint64_t nwid_,const Address &address_) noexcept: nwid(nwid_),address(address_.toInt()) {}
  327. ZT_INLINE unsigned long hashCode() const noexcept { return (unsigned long)(nwid + address); }
  328. ZT_INLINE bool operator==(const _LocalControllerAuth &a) const noexcept { return ((a.nwid == nwid) && (a.address == address)); }
  329. ZT_INLINE bool operator!=(const _LocalControllerAuth &a) const noexcept { return ((a.nwid != nwid) || (a.address != address)); }
  330. ZT_INLINE bool operator<(const _LocalControllerAuth &a) const noexcept { return ((a.nwid < nwid) || ((a.nwid == nwid)&&(a.address < address))); }
  331. };
  332. Map<_LocalControllerAuth,int64_t> _localControllerAuthorizations;
  333. Mutex _localControllerAuthorizations_m;
  334. // Networks are stored in a flat hash table that is resized on any network ID collision. This makes
  335. // network lookup by network ID a few bitwise ops and an array index.
  336. Map< uint64_t,SharedPtr<Network> > _networks;
  337. RWMutex _networks_m;
  338. // These are local interface addresses that have been configured via the API
  339. // and can be pushed to other nodes.
  340. std::vector< ZT_InterfaceAddress > _localInterfaceAddresses;
  341. Mutex _localInterfaceAddresses_m;
  342. // This is locked while running processBackgroundTasks to ensure that calls to it are not concurrent.
  343. Mutex _backgroundTasksLock;
  344. volatile int64_t _now;
  345. volatile int64_t _lastPing;
  346. volatile int64_t _lastHousekeepingRun;
  347. volatile int64_t _lastNetworkHousekeepingRun;
  348. volatile int64_t _lastPathKeepaliveCheck;
  349. volatile bool _natMustDie;
  350. volatile bool _online;
  351. };
  352. } // namespace ZeroTier
  353. #endif