Network.hpp 16 KB

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