Node.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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: 2025-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 "Containers.hpp"
  26. namespace ZeroTier {
  27. /**
  28. * Implementation of Node object as defined in CAPI
  29. *
  30. * The pointer returned by ZT_Node_new() is an instance of this class.
  31. */
  32. class Node : public NetworkController::Sender
  33. {
  34. public:
  35. // Get rid of alignment warnings on 32-bit Windows
  36. #ifdef __WINDOWS__
  37. void * operator new(size_t i) { return _mm_malloc(i,16); }
  38. void operator delete(void* p) { _mm_free(p); }
  39. #endif
  40. Node(void *uPtr, void *tPtr, const struct ZT_Node_Callbacks *callbacks, int64_t now);
  41. virtual ~Node();
  42. void shutdown(void *tPtr);
  43. // Public API Functions ---------------------------------------------------------------------------------------------
  44. ZT_ResultCode processWirePacket(
  45. void *tPtr,
  46. int64_t now,
  47. int64_t localSocket,
  48. const struct sockaddr_storage *remoteAddress,
  49. SharedPtr< Buf > &packetData,
  50. unsigned int packetLength,
  51. volatile int64_t *nextBackgroundTaskDeadline);
  52. ZT_ResultCode processVirtualNetworkFrame(
  53. void *tPtr,
  54. int64_t now,
  55. uint64_t nwid,
  56. uint64_t sourceMac,
  57. uint64_t destMac,
  58. unsigned int etherType,
  59. unsigned int vlanId,
  60. SharedPtr< Buf > &frameData,
  61. unsigned int frameLength,
  62. volatile int64_t *nextBackgroundTaskDeadline);
  63. ZT_ResultCode processHTTPResponse(
  64. void *tptr,
  65. int64_t now,
  66. void *requestId,
  67. int responseCode,
  68. const char **headerNames,
  69. const char **headerValues,
  70. const void *body,
  71. unsigned int bodySize,
  72. unsigned int flags);
  73. ZT_ResultCode processBackgroundTasks(
  74. void *tPtr,
  75. int64_t now,
  76. volatile int64_t *nextBackgroundTaskDeadline);
  77. ZT_ResultCode join(
  78. uint64_t nwid,
  79. const ZT_Fingerprint *controllerFingerprint,
  80. void *uptr,
  81. void *tptr);
  82. ZT_ResultCode leave(
  83. uint64_t nwid,
  84. void **uptr,
  85. void *tptr);
  86. ZT_ResultCode multicastSubscribe(
  87. void *tPtr,
  88. uint64_t nwid,
  89. uint64_t multicastGroup,
  90. unsigned long multicastAdi);
  91. ZT_ResultCode multicastUnsubscribe(
  92. uint64_t nwid,
  93. uint64_t multicastGroup,
  94. unsigned long multicastAdi);
  95. uint64_t address() const;
  96. void status(
  97. ZT_NodeStatus *status) const;
  98. ZT_PeerList *peers() const;
  99. ZT_VirtualNetworkConfig *networkConfig(
  100. uint64_t nwid) const;
  101. ZT_VirtualNetworkList *networks() const;
  102. void setNetworkUserPtr(
  103. uint64_t nwid,
  104. void *ptr);
  105. void setInterfaceAddresses(
  106. const ZT_InterfaceAddress *addrs,
  107. unsigned int addrCount);
  108. ZT_ResultCode addPeer(
  109. void *tptr,
  110. const ZT_Identity *identity);
  111. int tryPeer(
  112. void *tptr,
  113. const ZT_Fingerprint *fp,
  114. const ZT_Endpoint *endpoint,
  115. int retries);
  116. ZT_CertificateError addCertificate(
  117. void *tptr,
  118. int64_t now,
  119. unsigned int localTrust,
  120. const ZT_Certificate *cert,
  121. const void *certData,
  122. unsigned int certSize);
  123. ZT_ResultCode deleteCertificate(
  124. void *tptr,
  125. const void *serialNo);
  126. ZT_CertificateList *listCertificates();
  127. int sendUserMessage(
  128. void *tptr,
  129. uint64_t dest,
  130. uint64_t typeId,
  131. const void *data,
  132. unsigned int len);
  133. void setController(
  134. void *networkControllerInstance);
  135. // Internal functions -----------------------------------------------------------------------------------------------
  136. /**
  137. * @return Most recent time value supplied to core via API
  138. */
  139. ZT_INLINE int64_t now() const noexcept
  140. { return m_now; }
  141. /**
  142. * Send packet to to the physical wire via callback
  143. *
  144. * @param tPtr Thread pointer
  145. * @param localSocket Local socket or -1 to use all/any
  146. * @param addr Destination address
  147. * @param data Data to send
  148. * @param len Length in bytes
  149. * @param ttl TTL or 0 for default/max
  150. * @return True if send appears successful
  151. */
  152. ZT_INLINE bool putPacket(void *tPtr, const int64_t localSocket, const InetAddress &addr, const void *data, unsigned int len, unsigned int ttl = 0) noexcept
  153. {
  154. return (m_cb.wirePacketSendFunction(
  155. reinterpret_cast<ZT_Node *>(this),
  156. m_uPtr,
  157. tPtr,
  158. localSocket,
  159. &addr.as.ss,
  160. data,
  161. len,
  162. ttl) == 0);
  163. }
  164. /**
  165. * Inject frame into virtual Ethernet tap
  166. *
  167. * @param tPtr Thread pointer
  168. * @param nwid Network ID
  169. * @param nuptr Network-associated user pointer
  170. * @param source Source MAC address
  171. * @param dest Destination MAC address
  172. * @param etherType 16-bit Ethernet type
  173. * @param vlanId Ethernet VLAN ID (currently unused)
  174. * @param data Ethernet frame data
  175. * @param len Ethernet frame length in bytes
  176. */
  177. 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
  178. {
  179. m_cb.virtualNetworkFrameFunction(
  180. reinterpret_cast<ZT_Node *>(this),
  181. m_uPtr,
  182. tPtr,
  183. nwid,
  184. nuptr,
  185. source.toInt(),
  186. dest.toInt(),
  187. etherType,
  188. vlanId,
  189. data,
  190. len);
  191. }
  192. /**
  193. * @param nwid Network ID
  194. * @return Network associated with ID
  195. */
  196. ZT_INLINE SharedPtr< Network > network(const uint64_t nwid) const noexcept
  197. {
  198. RWMutex::RLock l(m_networks_l);
  199. Map< uint64_t, SharedPtr< Network > >::const_iterator n(m_networks.find(nwid));
  200. if (likely(n != m_networks.end()))
  201. return n->second;
  202. return SharedPtr< Network >();
  203. }
  204. /**
  205. * @return Known local interface addresses for this node
  206. */
  207. ZT_INLINE Vector< ZT_InterfaceAddress > localInterfaceAddresses() const
  208. {
  209. Mutex::Lock _l(m_localInterfaceAddresses_m);
  210. return m_localInterfaceAddresses;
  211. }
  212. /**
  213. * Post an event via external callback
  214. *
  215. * @param tPtr Thread pointer
  216. * @param ev Event object
  217. * @param md Event data or NULL if none
  218. */
  219. ZT_INLINE void postEvent(void *tPtr, ZT_Event ev, const void *md = nullptr) noexcept
  220. { m_cb.eventCallback(reinterpret_cast<ZT_Node *>(this), m_uPtr, tPtr, ev, md); }
  221. /**
  222. * Post network port configuration via external callback
  223. *
  224. * @param tPtr Thread pointer
  225. * @param nwid Network ID
  226. * @param nuptr Network-associated user pointer
  227. * @param op Config operation or event type
  228. * @param nc Network config info
  229. */
  230. ZT_INLINE void configureVirtualNetworkPort(void *tPtr, uint64_t nwid, void **nuptr, ZT_VirtualNetworkConfigOperation op, const ZT_VirtualNetworkConfig *nc) noexcept
  231. { m_cb.virtualNetworkConfigFunction(reinterpret_cast<ZT_Node *>(this), m_uPtr, tPtr, nwid, nuptr, op, nc); }
  232. /**
  233. * @return True if node appears online
  234. */
  235. ZT_INLINE bool online() const noexcept
  236. { return m_online; }
  237. /**
  238. * Get a state object
  239. *
  240. * @param tPtr Thread pointer
  241. * @param type Object type to get
  242. * @param id Object ID or NULL if this type does not use one
  243. * @return Vector containing data or empty vector if not found or empty
  244. */
  245. Vector< uint8_t > stateObjectGet(void *tPtr, ZT_StateObjectType type, const uint64_t *id);
  246. /**
  247. * Store a state object
  248. *
  249. * @param tPtr Thread pointer
  250. * @param type Object type to get
  251. * @param id Object ID
  252. * @param data Data to store
  253. * @param len Length of data
  254. */
  255. ZT_INLINE void stateObjectPut(void *const tPtr, ZT_StateObjectType type, const uint64_t id[2], const void *const data, const unsigned int len) noexcept
  256. {
  257. if (m_cb.statePutFunction)
  258. m_cb.statePutFunction(reinterpret_cast<ZT_Node *>(this), m_uPtr, tPtr, type, id, data, (int)len);
  259. }
  260. /**
  261. * Delete a state object
  262. *
  263. * @param tPtr Thread pointer
  264. * @param type Object type to delete
  265. * @param id Object ID
  266. */
  267. ZT_INLINE void stateObjectDelete(void *const tPtr, ZT_StateObjectType type, const uint64_t id[2]) noexcept
  268. {
  269. if (m_cb.statePutFunction)
  270. m_cb.statePutFunction(reinterpret_cast<ZT_Node *>(this), m_uPtr, tPtr, type, id, nullptr, -1);
  271. }
  272. /**
  273. * Check whether a path should be used for ZeroTier traffic
  274. *
  275. * This performs internal checks and also calls out to an external callback if one is defined.
  276. *
  277. * @param tPtr Thread pointer
  278. * @param id Identity of peer
  279. * @param localSocket Local socket or -1 if unknown
  280. * @param remoteAddress Remote address
  281. * @return True if path should be used
  282. */
  283. bool shouldUsePathForZeroTierTraffic(void *tPtr, const Identity &id, int64_t localSocket, const InetAddress &remoteAddress);
  284. /**
  285. * Query callback for a physical address for a peer
  286. *
  287. * @param tPtr Thread pointer
  288. * @param id Full identity of ZeroTier node
  289. * @param family Desired address family or -1 for any
  290. * @param addr Buffer to store address (result paramter)
  291. * @return True if addr was filled with something
  292. */
  293. bool externalPathLookup(void *tPtr, const Identity &id, int family, InetAddress &addr);
  294. /**
  295. * @return This node's identity
  296. */
  297. ZT_INLINE const Identity &identity() const noexcept
  298. { return m_RR.identity; }
  299. /**
  300. * Check whether a local controller has authorized a member on a network
  301. *
  302. * This is used by controllers to avoid needless certificate checks when we already
  303. * know if this has occurred. It's a bit of a hack but saves a massive amount of
  304. * controller CPU. It's easiest to put this here, and it imposes no overhead on
  305. * non-controllers.
  306. *
  307. * @param now Current time
  308. * @param nwid Network ID
  309. * @param addr Member address to check
  310. * @return True if member has been authorized
  311. */
  312. bool localControllerHasAuthorized(int64_t now, uint64_t nwid, const Address &addr) const;
  313. // Implementation of NetworkController::Sender interface
  314. virtual void ncSendConfig(uint64_t nwid, uint64_t requestPacketId, const Address &destination, const NetworkConfig &nc, bool sendLegacyFormatConfig);
  315. virtual void ncSendRevocation(const Address &destination, const RevocationCredential &rev);
  316. virtual void ncSendError(uint64_t nwid, uint64_t requestPacketId, const Address &destination, NetworkController::ErrorCode errorCode);
  317. private:
  318. RuntimeEnvironment m_RR;
  319. RuntimeEnvironment *const RR;
  320. // Pointer to a struct defined in Node that holds instances of core objects.
  321. void *m_objects;
  322. // Function pointers to C callbacks supplied via the API.
  323. ZT_Node_Callbacks m_cb;
  324. // A user-specified opaque pointer passed back via API callbacks.
  325. void *m_uPtr;
  326. // Cache that remembers whether or not the locally running network controller (if any) has authorized
  327. // someone on their most recent query. This is used by the network controller as a memoization optimization
  328. // to elide unnecessary signature verifications. It might get moved in the future since this is sort of a
  329. // weird place to put it.
  330. struct p_LocalControllerAuth
  331. {
  332. uint64_t nwid, address;
  333. ZT_INLINE p_LocalControllerAuth(const uint64_t nwid_, const Address &address_) noexcept: nwid(nwid_), address(address_.toInt())
  334. {}
  335. ZT_INLINE unsigned long hashCode() const noexcept
  336. { return (unsigned long)(nwid + address); }
  337. ZT_INLINE bool operator==(const p_LocalControllerAuth &a) const noexcept
  338. { return ((a.nwid == nwid) && (a.address == address)); }
  339. ZT_INLINE bool operator!=(const p_LocalControllerAuth &a) const noexcept
  340. { return ((a.nwid != nwid) || (a.address != address)); }
  341. ZT_INLINE bool operator<(const p_LocalControllerAuth &a) const noexcept
  342. { return ((a.nwid < nwid) || ((a.nwid == nwid) && (a.address < address))); }
  343. };
  344. Map< p_LocalControllerAuth, int64_t > m_localControllerAuthorizations;
  345. Mutex m_localControllerAuthorizations_l;
  346. // Locally joined networks by network ID.
  347. Map< uint64_t, SharedPtr< Network > > m_networks;
  348. RWMutex m_networks_l;
  349. // These are local interface addresses that have been configured via the API
  350. // and can be pushed to other nodes.
  351. Vector< ZT_InterfaceAddress > m_localInterfaceAddresses;
  352. Mutex m_localInterfaceAddresses_m;
  353. // This is locked while running processBackgroundTasks().
  354. Mutex m_backgroundTasksLock;
  355. // These are locked via _backgroundTasksLock as they're only checked and modified in processBackgroundTasks().
  356. int64_t m_lastPeerPulse;
  357. int64_t m_lastHousekeepingRun;
  358. int64_t m_lastNetworkHousekeepingRun;
  359. // This is the most recent value for time passed in via any of the core API methods.
  360. std::atomic< int64_t > m_now;
  361. // True if at least one root appears reachable.
  362. std::atomic< bool > m_online;
  363. };
  364. } // namespace ZeroTier
  365. #endif