Network.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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_NETWORK_HPP
  14. #define ZT_NETWORK_HPP
  15. #include "Constants.hpp"
  16. #include "Address.hpp"
  17. #include "Mutex.hpp"
  18. #include "SharedPtr.hpp"
  19. #include "MulticastGroup.hpp"
  20. #include "MAC.hpp"
  21. #include "Buf.hpp"
  22. #include "Dictionary.hpp"
  23. #include "Member.hpp"
  24. #include "NetworkConfig.hpp"
  25. #include "MembershipCredential.hpp"
  26. #include "Containers.hpp"
  27. #define ZT_NETWORK_MAX_INCOMING_UPDATES 3
  28. namespace ZeroTier {
  29. class RuntimeEnvironment;
  30. class Peer;
  31. /**
  32. * A virtual LAN
  33. */
  34. class Network
  35. {
  36. friend class SharedPtr< Network >;
  37. public:
  38. /**
  39. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  40. */
  41. static const MulticastGroup BROADCAST;
  42. /**
  43. * Compute primary controller device ID from network ID
  44. */
  45. static ZT_INLINE Address controllerFor(uint64_t nwid) noexcept
  46. { return Address(nwid >> 24U); }
  47. /**
  48. * Construct a new network
  49. *
  50. * Note that init() should be called immediately after the network is
  51. * constructed to actually configure the port.
  52. *
  53. * @param renv Runtime environment
  54. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  55. * @param nwid Network ID
  56. * @param controllerFingerprint Initial controller fingerprint if non-NULL
  57. * @param uptr Arbitrary pointer used by externally-facing API (for user use)
  58. * @param nconf Network config, if known
  59. */
  60. Network(const RuntimeEnvironment *renv, void *tPtr, uint64_t nwid, const Fingerprint &controllerFingerprint, void *uptr, const NetworkConfig *nconf);
  61. ~Network();
  62. ZT_INLINE uint64_t id() const noexcept
  63. { return m_id; }
  64. ZT_INLINE Address controller() const noexcept
  65. { return Address(m_id >> 24U); }
  66. ZT_INLINE bool multicastEnabled() const noexcept
  67. { return (m_config.multicastLimit > 0); }
  68. ZT_INLINE bool hasConfig() const noexcept
  69. { return (m_config); }
  70. ZT_INLINE uint64_t lastConfigUpdate() const noexcept
  71. { return m_lastConfigUpdate; }
  72. ZT_INLINE ZT_VirtualNetworkStatus status() const noexcept
  73. { return m_status(); }
  74. ZT_INLINE const NetworkConfig &config() const noexcept
  75. { return m_config; }
  76. ZT_INLINE const MAC &mac() const noexcept
  77. { return m_mac; }
  78. /**
  79. * Apply filters to an outgoing packet
  80. *
  81. * This applies filters from our network config and, if that doesn't match,
  82. * our capabilities in ascending order of capability ID. Additional actions
  83. * such as TEE may be taken, and credentials may be pushed, so this is not
  84. * side-effect-free. It's basically step one in sending something over VL2.
  85. *
  86. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  87. * @param noTee If true, do not TEE anything anywhere (for two-pass filtering as done with multicast and bridging)
  88. * @param ztSource Source ZeroTier address
  89. * @param ztDest Destination ZeroTier address
  90. * @param macSource Ethernet layer source address
  91. * @param macDest Ethernet layer destination address
  92. * @param frameData Ethernet frame data
  93. * @param frameLen Ethernet frame payload length
  94. * @param etherType 16-bit ethernet type ID
  95. * @param vlanId 16-bit VLAN ID
  96. * @return True if packet should be sent, false if dropped or redirected
  97. */
  98. bool filterOutgoingPacket(
  99. void *tPtr,
  100. bool noTee,
  101. const Address &ztSource,
  102. const Address &ztDest,
  103. const MAC &macSource,
  104. const MAC &macDest,
  105. const uint8_t *frameData,
  106. unsigned int frameLen,
  107. unsigned int etherType,
  108. unsigned int vlanId,
  109. uint8_t &qosBucket);
  110. /**
  111. * Apply filters to an incoming packet
  112. *
  113. * This applies filters from our network config and, if that doesn't match,
  114. * the peer's capabilities in ascending order of capability ID. If there is
  115. * a match certain actions may be taken such as sending a copy of the packet
  116. * to a TEE or REDIRECT target.
  117. *
  118. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  119. * @param sourcePeer Source Peer
  120. * @param ztDest Destination ZeroTier address
  121. * @param macSource Ethernet layer source address
  122. * @param macDest Ethernet layer destination address
  123. * @param frameData Ethernet frame data
  124. * @param frameLen Ethernet frame payload length
  125. * @param etherType 16-bit ethernet type ID
  126. * @param vlanId 16-bit VLAN ID
  127. * @return 0 == drop, 1 == accept, 2 == accept even if bridged
  128. */
  129. int filterIncomingPacket(
  130. void *tPtr,
  131. const SharedPtr< Peer > &sourcePeer,
  132. const Address &ztDest,
  133. const MAC &macSource,
  134. const MAC &macDest,
  135. const uint8_t *frameData,
  136. unsigned int frameLen,
  137. unsigned int etherType,
  138. unsigned int vlanId);
  139. /**
  140. * Check whether we are subscribed to a multicast group
  141. *
  142. * @param mg Multicast group
  143. * @param includeBridgedGroups If true, also check groups we've learned via bridging
  144. * @return True if this network endpoint / peer is a member
  145. */
  146. ZT_INLINE bool subscribedToMulticastGroup(const MulticastGroup &mg, const bool includeBridgedGroups) const
  147. {
  148. Mutex::Lock l(m_myMulticastGroups_l);
  149. if (std::binary_search(m_myMulticastGroups.begin(), m_myMulticastGroups.end(), mg))
  150. return true;
  151. else if (includeBridgedGroups)
  152. return (m_multicastGroupsBehindMe.find(mg) != m_multicastGroupsBehindMe.end());
  153. return false;
  154. }
  155. /**
  156. * Subscribe to a multicast group
  157. *
  158. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  159. * @param mg New multicast group
  160. */
  161. void multicastSubscribe(void *tPtr, const MulticastGroup &mg);
  162. /**
  163. * Unsubscribe from a multicast group
  164. *
  165. * @param mg Multicast group
  166. */
  167. void multicastUnsubscribe(const MulticastGroup &mg);
  168. /**
  169. * Parse, verify, and handle an inbound network config chunk
  170. *
  171. * This is called from IncomingPacket to handle incoming network config
  172. * chunks via OK(NETWORK_CONFIG_REQUEST) or NETWORK_CONFIG. It's a common
  173. * bit of packet parsing code that also verifies chunks and replicates
  174. * them (via rumor mill flooding) if their fast propagate flag is set.
  175. *
  176. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  177. * @param packetId Packet ID or 0 if none (e.g. via cluster path)
  178. * @param source Peer that actually sent this chunk (probably controller)
  179. * @param chunk Buffer containing chunk
  180. * @param ptr Index of chunk and related fields in packet (starting with network ID)
  181. * @param size Size of data in chunk buffer (total, not relative to ptr)
  182. * @return Update ID if update was fully assembled and accepted or 0 otherwise
  183. */
  184. uint64_t handleConfigChunk(void *tPtr, uint64_t packetId, const SharedPtr< Peer > &source, const Buf &chunk, int ptr, int size);
  185. /**
  186. * Set network configuration
  187. *
  188. * This is normally called internally when a configuration is received
  189. * and fully assembled, but it can also be called on Node startup when
  190. * cached configurations are re-read from the data store.
  191. *
  192. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  193. * @param nconf Network configuration
  194. * @param saveToDisk Save to disk? Used during loading, should usually be true otherwise.
  195. * @return 0 == bad, 1 == accepted but duplicate/unchanged, 2 == accepted and new
  196. */
  197. int setConfiguration(void *tPtr, const NetworkConfig &nconf, bool saveToDisk);
  198. /**
  199. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  200. */
  201. ZT_INLINE void setAccessDenied() noexcept
  202. { _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED; }
  203. /**
  204. * Set netconf failure to 'not found' -- called by IncomingPacket when controller reports this
  205. */
  206. ZT_INLINE void setNotFound() noexcept
  207. { _netconfFailure = NETCONF_FAILURE_NOT_FOUND; }
  208. /**
  209. * Determine whether this peer is permitted to communicate on this network
  210. *
  211. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  212. * @param peer Peer to check
  213. */
  214. bool gate(void *tPtr, const SharedPtr< Peer > &peer) noexcept;
  215. /**
  216. * Do periodic cleanup and housekeeping tasks
  217. */
  218. void doPeriodicTasks(void *tPtr, int64_t now);
  219. /**
  220. * Find the node on this network that has this MAC behind it (if any)
  221. *
  222. * @param mac MAC address
  223. * @return ZeroTier address of bridge to this MAC
  224. */
  225. ZT_INLINE Address findBridgeTo(const MAC &mac) const
  226. {
  227. Mutex::Lock _l(m_remoteBridgeRoutes_l);
  228. Map< MAC, Address >::const_iterator br(m_remoteBridgeRoutes.find(mac));
  229. return ((br == m_remoteBridgeRoutes.end()) ? Address() : br->second);
  230. }
  231. /**
  232. * Set a bridge route
  233. *
  234. * @param mac MAC address of destination
  235. * @param addr Bridge this MAC is reachable behind
  236. */
  237. void learnBridgeRoute(const MAC &mac, const Address &addr);
  238. /**
  239. * Learn a multicast group that is bridged to our tap device
  240. *
  241. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  242. * @param mg Multicast group
  243. * @param now Current time
  244. */
  245. ZT_INLINE void learnBridgedMulticastGroup(void *tPtr, const MulticastGroup &mg, int64_t now)
  246. {
  247. Mutex::Lock l(m_myMulticastGroups_l);
  248. m_multicastGroupsBehindMe[mg] = now;
  249. }
  250. /**
  251. * Validate a credential and learn it if it passes certificate and other checks
  252. */
  253. Member::AddCredentialResult addCredential(void *tPtr, const Identity &sourcePeerIdentity, const MembershipCredential &com);
  254. /**
  255. * Validate a credential and learn it if it passes certificate and other checks
  256. */
  257. Member::AddCredentialResult addCredential(void *tPtr, const Identity &sourcePeerIdentity, const CapabilityCredential &cap);
  258. /**
  259. * Validate a credential and learn it if it passes certificate and other checks
  260. */
  261. Member::AddCredentialResult addCredential(void *tPtr, const Identity &sourcePeerIdentity, const TagCredential &tag);
  262. /**
  263. * Validate a credential and learn it if it passes certificate and other checks
  264. */
  265. Member::AddCredentialResult addCredential(void *tPtr, const Identity &sourcePeerIdentity, const RevocationCredential &rev);
  266. /**
  267. * Validate a credential and learn it if it passes certificate and other checks
  268. */
  269. Member::AddCredentialResult addCredential(void *tPtr, const Identity &sourcePeerIdentity, const OwnershipCredential &coo);
  270. /**
  271. * Push credentials to a peer if timeouts indicate that we should do so
  272. *
  273. * @param tPtr Thread pointer to be handed through to any callbacks called as a result of this call
  274. * @param to Destination peer
  275. * @param now Current time
  276. */
  277. void pushCredentials(void *tPtr, const SharedPtr< Peer > &to, int64_t now);
  278. /**
  279. * Destroy this network
  280. *
  281. * This sets the network to completely remove itself on delete. This also prevents the
  282. * call of the normal port shutdown event on delete.
  283. */
  284. void destroy();
  285. /**
  286. * Get this network's config for export via the ZT core API
  287. *
  288. * @param ec Buffer to fill with externally-visible network configuration
  289. */
  290. void externalConfig(ZT_VirtualNetworkConfig *ec) const;
  291. /**
  292. * Iterate through memberships
  293. *
  294. * @param f Function of (const Address,const Membership)
  295. */
  296. template< typename F >
  297. ZT_INLINE void eachMember(F f)
  298. {
  299. Mutex::Lock ml(m_memberships_l);
  300. for (Map< Address, Member >::iterator i(m_memberships.begin()); i != m_memberships.end(); ++i) { // NOLINT(modernize-loop-convert,hicpp-use-auto,modernize-use-auto)
  301. if (!f(i->first, i->second))
  302. break;
  303. }
  304. }
  305. /**
  306. * @return Externally usable pointer-to-pointer exported via the core API
  307. */
  308. ZT_INLINE void **userPtr() noexcept
  309. { return &m_uPtr; }
  310. private:
  311. void m_requestConfiguration(void *tPtr);
  312. ZT_VirtualNetworkStatus m_status() const;
  313. void m_externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  314. void m_announceMulticastGroups(void *tPtr, bool force);
  315. void m_announceMulticastGroupsTo(void *tPtr, const Address &peer, const Vector< MulticastGroup > &allMulticastGroups);
  316. Vector< MulticastGroup > m_allMulticastGroups() const;
  317. const RuntimeEnvironment *const RR;
  318. void *m_uPtr;
  319. const uint64_t m_id;
  320. Fingerprint m_controllerFingerprint;
  321. MAC m_mac; // local MAC address
  322. bool m_portInitialized;
  323. std::atomic< bool > m_destroyed;
  324. Vector< MulticastGroup > m_myMulticastGroups; // multicast groups that we belong to (according to tap)
  325. Map< MulticastGroup, int64_t > m_multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  326. Map< MAC, Address > m_remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  327. NetworkConfig m_config;
  328. std::atomic< int64_t > m_lastConfigUpdate;
  329. volatile enum
  330. {
  331. NETCONF_FAILURE_NONE,
  332. NETCONF_FAILURE_ACCESS_DENIED,
  333. NETCONF_FAILURE_NOT_FOUND,
  334. NETCONF_FAILURE_INIT_FAILED
  335. } _netconfFailure;
  336. Map< Address, Member > m_memberships;
  337. Mutex m_myMulticastGroups_l;
  338. Mutex m_remoteBridgeRoutes_l;
  339. Mutex m_config_l;
  340. Mutex m_memberships_l;
  341. std::atomic< int > __refCount;
  342. };
  343. } // namespace ZeroTier
  344. #endif