Network.hpp 14 KB

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