Network.hpp 13 KB

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