Network.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_NETWORK_HPP
  28. #define ZT_NETWORK_HPP
  29. #include <stdint.h>
  30. #include "../include/ZeroTierOne.h"
  31. #include <string>
  32. #include <map>
  33. #include <vector>
  34. #include <algorithm>
  35. #include <stdexcept>
  36. #include "Constants.hpp"
  37. #include "NonCopyable.hpp"
  38. #include "Address.hpp"
  39. #include "Mutex.hpp"
  40. #include "SharedPtr.hpp"
  41. #include "AtomicCounter.hpp"
  42. #include "MulticastGroup.hpp"
  43. #include "MAC.hpp"
  44. #include "Dictionary.hpp"
  45. #include "Multicaster.hpp"
  46. #include "NetworkConfig.hpp"
  47. #include "CertificateOfMembership.hpp"
  48. namespace ZeroTier {
  49. class RuntimeEnvironment;
  50. class _AnnounceMulticastGroupsToPeersWithActiveDirectPaths;
  51. /**
  52. * A virtual LAN
  53. */
  54. class Network : NonCopyable
  55. {
  56. friend class SharedPtr<Network>;
  57. friend class _AnnounceMulticastGroupsToPeersWithActiveDirectPaths;
  58. public:
  59. /**
  60. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  61. */
  62. static const MulticastGroup BROADCAST;
  63. /**
  64. * Construct a new network
  65. *
  66. * Note that init() should be called immediately after the network is
  67. * constructed to actually configure the port.
  68. *
  69. * @param renv Runtime environment
  70. * @param nwid Network ID
  71. */
  72. Network(const RuntimeEnvironment *renv,uint64_t nwid);
  73. ~Network();
  74. /**
  75. * @return Network ID
  76. */
  77. inline uint64_t id() const throw() { return _id; }
  78. /**
  79. * @return Address of network's controller (most significant 40 bits of ID)
  80. */
  81. inline Address controller() throw() { return Address(_id >> 24); }
  82. /**
  83. * @return Multicast group memberships for this network's port (local, not learned via bridging)
  84. */
  85. inline std::vector<MulticastGroup> multicastGroups() const
  86. {
  87. Mutex::Lock _l(_lock);
  88. return _myMulticastGroups;
  89. }
  90. /**
  91. * @return All multicast groups including learned groups that are behind any bridges we're attached to
  92. */
  93. inline std::vector<MulticastGroup> allMulticastGroups() const
  94. {
  95. Mutex::Lock _l(_lock);
  96. return _allMulticastGroups();
  97. }
  98. /**
  99. * @param mg Multicast group
  100. * @param includeBridgedGroups If true, also include any groups we've learned via bridging
  101. * @return True if this network endpoint / peer is a member
  102. */
  103. bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
  104. /**
  105. * Subscribe to a multicast group
  106. *
  107. * @param mg New multicast group
  108. */
  109. void multicastSubscribe(const MulticastGroup &mg);
  110. /**
  111. * Unsubscribe from a multicast group
  112. *
  113. * @param mg Multicast group
  114. */
  115. void multicastUnsubscribe(const MulticastGroup &mg);
  116. /**
  117. * Apply a NetworkConfig to this network
  118. *
  119. * @param conf Configuration in NetworkConfig form
  120. * @return True if configuration was accepted
  121. */
  122. bool applyConfiguration(const SharedPtr<NetworkConfig> &conf);
  123. /**
  124. * Set or update this network's configuration
  125. *
  126. * This decodes a network configuration in key=value dictionary form,
  127. * applies it if valid, and persists it to disk if saveToDisk is true.
  128. *
  129. * @param conf Configuration in key/value dictionary form
  130. * @param saveToDisk IF true (default), write config to disk
  131. * @return 0 -- rejected, 1 -- accepted but not new, 2 -- accepted new config
  132. */
  133. int setConfiguration(const Dictionary &conf,bool saveToDisk = true);
  134. /**
  135. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  136. */
  137. inline void setAccessDenied()
  138. {
  139. Mutex::Lock _l(_lock);
  140. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  141. }
  142. /**
  143. * Set netconf failure to 'not found' -- called by PacketDecider when controller reports this
  144. */
  145. inline void setNotFound()
  146. {
  147. Mutex::Lock _l(_lock);
  148. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  149. }
  150. /**
  151. * Causes this network to request an updated configuration from its master node now
  152. */
  153. void requestConfiguration();
  154. /**
  155. * Add or update a membership certificate
  156. *
  157. * @param cert Certificate of membership
  158. * @return True if certificate was accepted as valid
  159. */
  160. bool validateAndAddMembershipCertificate(const CertificateOfMembership &cert);
  161. /**
  162. * Check if we should push membership certificate to a peer, AND update last pushed
  163. *
  164. * If we haven't pushed a cert to this peer in a long enough time, this returns
  165. * true and updates the last pushed time. Otherwise it returns false.
  166. *
  167. * This doesn't actually send anything, since COMs can hitch a ride with several
  168. * different kinds of packets.
  169. *
  170. * @param to Destination peer
  171. * @param now Current time
  172. * @return True if we should include a COM with whatever we're currently sending
  173. */
  174. bool peerNeedsOurMembershipCertificate(const Address &to,uint64_t now);
  175. /**
  176. * @param peer Peer address to check
  177. * @return True if peer is allowed to communicate on this network
  178. */
  179. inline bool isAllowed(const Address &peer) const
  180. {
  181. Mutex::Lock _l(_lock);
  182. return _isAllowed(peer);
  183. }
  184. /**
  185. * Perform cleanup and possibly save state
  186. */
  187. void clean();
  188. /**
  189. * @return Time of last updated configuration or 0 if none
  190. */
  191. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  192. /**
  193. * @return Status of this network
  194. */
  195. inline ZT1_VirtualNetworkStatus status() const
  196. {
  197. Mutex::Lock _l(_lock);
  198. return _status();
  199. }
  200. /**
  201. * @param ec Buffer to fill with externally-visible network configuration
  202. */
  203. inline void externalConfig(ZT1_VirtualNetworkConfig *ec) const
  204. {
  205. Mutex::Lock _l(_lock);
  206. _externalConfig(ec);
  207. }
  208. /**
  209. * Get current network config or throw exception
  210. *
  211. * This version never returns null. Instead it throws a runtime error if
  212. * there is no current configuration. Callers should check isUp() first or
  213. * use config2() to get with the potential for null.
  214. *
  215. * Since it never returns null, it's safe to config()->whatever() inside
  216. * a try/catch block.
  217. *
  218. * @return Network configuration (never null)
  219. * @throws std::runtime_error Network configuration unavailable
  220. */
  221. inline SharedPtr<NetworkConfig> config() const
  222. {
  223. Mutex::Lock _l(_lock);
  224. if (_config)
  225. return _config;
  226. throw std::runtime_error("no configuration");
  227. }
  228. /**
  229. * Get current network config or return NULL
  230. *
  231. * @return Network configuration -- may be NULL
  232. */
  233. inline SharedPtr<NetworkConfig> config2() const
  234. throw()
  235. {
  236. Mutex::Lock _l(_lock);
  237. return _config;
  238. }
  239. /**
  240. * @return Ethernet MAC address for this network's local interface
  241. */
  242. inline const MAC &mac() const throw() { return _mac; }
  243. /**
  244. * Shortcut for config()->permitsBridging(), returns false if no config
  245. *
  246. * @param peer Peer address to check
  247. * @return True if peer can bridge other Ethernet nodes into this network or network is in permissive bridging mode
  248. */
  249. inline bool permitsBridging(const Address &peer) const
  250. {
  251. Mutex::Lock _l(_lock);
  252. if (_config)
  253. return _config->permitsBridging(peer);
  254. return false;
  255. }
  256. /**
  257. * Find the node on this network that has this MAC behind it (if any)
  258. *
  259. * @param mac MAC address
  260. * @return ZeroTier address of bridge to this MAC
  261. */
  262. inline Address findBridgeTo(const MAC &mac) const
  263. {
  264. Mutex::Lock _l(_lock);
  265. std::map<MAC,Address>::const_iterator br(_remoteBridgeRoutes.find(mac));
  266. if (br == _remoteBridgeRoutes.end())
  267. return Address();
  268. return br->second;
  269. }
  270. /**
  271. * Set a bridge route
  272. *
  273. * @param mac MAC address of destination
  274. * @param addr Bridge this MAC is reachable behind
  275. */
  276. void learnBridgeRoute(const MAC &mac,const Address &addr);
  277. /**
  278. * Learn a multicast group that is bridged to our tap device
  279. *
  280. * @param mg Multicast group
  281. * @param now Current time
  282. */
  283. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  284. /**
  285. * @return True if traffic on this network's tap is enabled
  286. */
  287. inline bool enabled() const throw() { return _enabled; }
  288. /**
  289. * @param enabled Should traffic be allowed on this network?
  290. */
  291. void setEnabled(bool enabled);
  292. /**
  293. * Destroy this network
  294. *
  295. * This causes the network to disable itself, destroy its tap device, and on
  296. * delete to delete all trace of itself on disk and remove any persistent tap
  297. * device instances. Call this when a network is being removed from the system.
  298. */
  299. void destroy();
  300. inline bool operator==(const Network &n) const throw() { return (_id == n._id); }
  301. inline bool operator!=(const Network &n) const throw() { return (_id != n._id); }
  302. inline bool operator<(const Network &n) const throw() { return (_id < n._id); }
  303. inline bool operator>(const Network &n) const throw() { return (_id > n._id); }
  304. inline bool operator<=(const Network &n) const throw() { return (_id <= n._id); }
  305. inline bool operator>=(const Network &n) const throw() { return (_id >= n._id); }
  306. private:
  307. ZT1_VirtualNetworkStatus _status() const;
  308. void _externalConfig(ZT1_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  309. bool _isAllowed(const Address &peer) const;
  310. void _announceMulticastGroups();
  311. std::vector<MulticastGroup> _allMulticastGroups() const;
  312. const RuntimeEnvironment *RR;
  313. uint64_t _id;
  314. MAC _mac; // local MAC address
  315. volatile bool _enabled;
  316. volatile bool _portInitialized;
  317. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to including those behind us (updated periodically)
  318. std::map< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups bridged to us and when we last saw activity on each
  319. std::map<MAC,Address> _remoteBridgeRoutes; // remote addresses where given MACs are reachable
  320. std::map<Address,CertificateOfMembership> _membershipCertificates; // Other members' certificates of membership
  321. std::map<Address,uint64_t> _lastPushedMembershipCertificate; // When did we last push our certificate to each remote member?
  322. SharedPtr<NetworkConfig> _config; // Most recent network configuration, which is an immutable value-object
  323. volatile uint64_t _lastConfigUpdate;
  324. volatile bool _destroyed;
  325. enum {
  326. NETCONF_FAILURE_NONE,
  327. NETCONF_FAILURE_ACCESS_DENIED,
  328. NETCONF_FAILURE_NOT_FOUND,
  329. NETCONF_FAILURE_INIT_FAILED
  330. } _netconfFailure;
  331. volatile int _portError; // return value from port config callback
  332. Mutex _lock;
  333. AtomicCounter __refCount;
  334. };
  335. } // naemspace ZeroTier
  336. #endif