Network.hpp 15 KB

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