Node.hpp 12 KB

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