Network.hpp 15 KB

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