Network.hpp 13 KB

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