Network.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 "Hashtable.hpp"
  39. #include "Address.hpp"
  40. #include "Mutex.hpp"
  41. #include "SharedPtr.hpp"
  42. #include "AtomicCounter.hpp"
  43. #include "MulticastGroup.hpp"
  44. #include "MAC.hpp"
  45. #include "Dictionary.hpp"
  46. #include "Multicaster.hpp"
  47. #include "NetworkConfig.hpp"
  48. #include "CertificateOfMembership.hpp"
  49. namespace ZeroTier {
  50. class RuntimeEnvironment;
  51. class Peer;
  52. class _GetPeersThatNeedMulticastAnnouncement;
  53. /**
  54. * A virtual LAN
  55. */
  56. class Network : NonCopyable
  57. {
  58. friend class SharedPtr<Network>;
  59. friend class _GetPeersThatNeedMulticastAnnouncement; // internal function object
  60. public:
  61. /**
  62. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  63. */
  64. static const MulticastGroup BROADCAST;
  65. /**
  66. * Construct a new network
  67. *
  68. * Note that init() should be called immediately after the network is
  69. * constructed to actually configure the port.
  70. *
  71. * @param renv Runtime environment
  72. * @param nwid Network ID
  73. * @param uptr Arbitrary pointer used by externally-facing API (for user use)
  74. */
  75. Network(const RuntimeEnvironment *renv,uint64_t nwid,void *uptr);
  76. ~Network();
  77. /**
  78. * @return Network ID
  79. */
  80. inline uint64_t id() const throw() { return _id; }
  81. /**
  82. * @return Address of network's controller (most significant 40 bits of ID)
  83. */
  84. inline Address controller() const throw() { return Address(_id >> 24); }
  85. /**
  86. * @param nwid Network ID
  87. * @return Address of network's controller
  88. */
  89. static inline Address controllerFor(uint64_t nwid) throw() { return Address(nwid >> 24); }
  90. /**
  91. * @return Multicast group memberships for this network's port (local, not learned via bridging)
  92. */
  93. inline std::vector<MulticastGroup> multicastGroups() const
  94. {
  95. Mutex::Lock _l(_lock);
  96. return _myMulticastGroups;
  97. }
  98. /**
  99. * @return All multicast groups including learned groups that are behind any bridges we're attached to
  100. */
  101. inline std::vector<MulticastGroup> allMulticastGroups() const
  102. {
  103. Mutex::Lock _l(_lock);
  104. return _allMulticastGroups();
  105. }
  106. /**
  107. * @param mg Multicast group
  108. * @param includeBridgedGroups If true, also include any groups we've learned via bridging
  109. * @return True if this network endpoint / peer is a member
  110. */
  111. bool subscribedToMulticastGroup(const MulticastGroup &mg,bool includeBridgedGroups) const;
  112. /**
  113. * Subscribe to a multicast group
  114. *
  115. * @param mg New multicast group
  116. */
  117. void multicastSubscribe(const MulticastGroup &mg);
  118. /**
  119. * Unsubscribe from a multicast group
  120. *
  121. * @param mg Multicast group
  122. */
  123. void multicastUnsubscribe(const MulticastGroup &mg);
  124. /**
  125. * Announce multicast groups to a peer if that peer is authorized on this network
  126. *
  127. * @param peer Peer to try to announce multicast groups to
  128. * @return True if peer was authorized and groups were announced
  129. */
  130. bool tryAnnounceMulticastGroupsTo(const SharedPtr<Peer> &peer);
  131. /**
  132. * Apply a NetworkConfig to this network
  133. *
  134. * @param conf Configuration in NetworkConfig form
  135. * @return True if configuration was accepted
  136. */
  137. bool applyConfiguration(const SharedPtr<NetworkConfig> &conf);
  138. /**
  139. * Set or update this network's configuration
  140. *
  141. * This decodes a network configuration in key=value dictionary form,
  142. * applies it if valid, and persists it to disk if saveToDisk is true.
  143. *
  144. * @param conf Configuration in key/value dictionary form
  145. * @param saveToDisk IF true (default), write config to disk
  146. * @return 0 -- rejected, 1 -- accepted but not new, 2 -- accepted new config
  147. */
  148. int setConfiguration(const Dictionary &conf,bool saveToDisk = true);
  149. /**
  150. * Set netconf failure to 'access denied' -- called in IncomingPacket when controller reports this
  151. */
  152. inline void setAccessDenied()
  153. {
  154. Mutex::Lock _l(_lock);
  155. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  156. }
  157. /**
  158. * Set netconf failure to 'not found' -- called by PacketDecider when controller reports this
  159. */
  160. inline void setNotFound()
  161. {
  162. Mutex::Lock _l(_lock);
  163. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  164. }
  165. /**
  166. * Causes this network to request an updated configuration from its master node now
  167. */
  168. void requestConfiguration();
  169. /**
  170. * @param peer Peer to check
  171. * @return True if peer is allowed to communicate on this network
  172. */
  173. inline bool isAllowed(const SharedPtr<Peer> &peer) const
  174. {
  175. Mutex::Lock _l(_lock);
  176. return _isAllowed(peer);
  177. }
  178. /**
  179. * Perform cleanup and possibly save state
  180. */
  181. void clean();
  182. /**
  183. * @return Time of last updated configuration or 0 if none
  184. */
  185. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  186. /**
  187. * @return Status of this network
  188. */
  189. inline ZT_VirtualNetworkStatus status() const
  190. {
  191. Mutex::Lock _l(_lock);
  192. return _status();
  193. }
  194. /**
  195. * @param ec Buffer to fill with externally-visible network configuration
  196. */
  197. inline void externalConfig(ZT_VirtualNetworkConfig *ec) const
  198. {
  199. Mutex::Lock _l(_lock);
  200. _externalConfig(ec);
  201. }
  202. /**
  203. * Get current network config or throw exception
  204. *
  205. * This version never returns null. Instead it throws a runtime error if
  206. * there is no current configuration. Callers should check isUp() first or
  207. * use config2() to get with the potential for null.
  208. *
  209. * Since it never returns null, it's safe to config()->whatever() inside
  210. * a try/catch block.
  211. *
  212. * @return Network configuration (never null)
  213. * @throws std::runtime_error Network configuration unavailable
  214. */
  215. inline SharedPtr<NetworkConfig> config() const
  216. {
  217. Mutex::Lock _l(_lock);
  218. if (_config)
  219. return _config;
  220. throw std::runtime_error("no configuration");
  221. }
  222. /**
  223. * Get current network config or return NULL
  224. *
  225. * @return Network configuration -- may be NULL
  226. */
  227. inline SharedPtr<NetworkConfig> config2() const
  228. throw()
  229. {
  230. Mutex::Lock _l(_lock);
  231. return _config;
  232. }
  233. /**
  234. * @return Ethernet MAC address for this network's local interface
  235. */
  236. inline const MAC &mac() const throw() { return _mac; }
  237. /**
  238. * Shortcut for config()->permitsBridging(), returns false if no config
  239. *
  240. * @param peer Peer address to check
  241. * @return True if peer can bridge other Ethernet nodes into this network or network is in permissive bridging mode
  242. */
  243. inline bool permitsBridging(const Address &peer) const
  244. {
  245. Mutex::Lock _l(_lock);
  246. if (_config)
  247. return _config->permitsBridging(peer);
  248. return false;
  249. }
  250. /**
  251. * Find the node on this network that has this MAC behind it (if any)
  252. *
  253. * @param mac MAC address
  254. * @return ZeroTier address of bridge to this MAC
  255. */
  256. inline Address findBridgeTo(const MAC &mac) const
  257. {
  258. Mutex::Lock _l(_lock);
  259. const Address *const br = _remoteBridgeRoutes.get(mac);
  260. if (br)
  261. return *br;
  262. return Address();
  263. }
  264. /**
  265. * Set a bridge route
  266. *
  267. * @param mac MAC address of destination
  268. * @param addr Bridge this MAC is reachable behind
  269. */
  270. void learnBridgeRoute(const MAC &mac,const Address &addr);
  271. /**
  272. * Learn a multicast group that is bridged to our tap device
  273. *
  274. * @param mg Multicast group
  275. * @param now Current time
  276. */
  277. void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now);
  278. /**
  279. * @return True if traffic on this network's tap is enabled
  280. */
  281. inline bool enabled() const throw() { return _enabled; }
  282. /**
  283. * @param enabled Should traffic be allowed on this network?
  284. */
  285. void setEnabled(bool enabled);
  286. /**
  287. * Destroy this network
  288. *
  289. * This causes the network to disable itself, destroy its tap device, and on
  290. * delete to delete all trace of itself on disk and remove any persistent tap
  291. * device instances. Call this when a network is being removed from the system.
  292. */
  293. void destroy();
  294. /**
  295. * @return Pointer to user PTR (modifiable user ptr used in API)
  296. */
  297. inline void **userPtr() throw() { return &_uptr; }
  298. inline bool operator==(const Network &n) const throw() { return (_id == n._id); }
  299. inline bool operator!=(const Network &n) const throw() { return (_id != n._id); }
  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. private:
  305. ZT_VirtualNetworkStatus _status() const;
  306. void _externalConfig(ZT_VirtualNetworkConfig *ec) const; // assumes _lock is locked
  307. bool _isAllowed(const SharedPtr<Peer> &peer) const;
  308. bool _tryAnnounceMulticastGroupsTo(const std::vector<Address> &rootAddresses,const std::vector<MulticastGroup> &allMulticastGroups,const SharedPtr<Peer> &peer,uint64_t now) const;
  309. void _announceMulticastGroups();
  310. void _announceMulticastGroupsTo(const Address &peerAddress,const std::vector<MulticastGroup> &allMulticastGroups) const;
  311. std::vector<MulticastGroup> _allMulticastGroups() const;
  312. const RuntimeEnvironment *RR;
  313. void *_uptr;
  314. uint64_t _id;
  315. MAC _mac; // local MAC address
  316. volatile bool _enabled;
  317. volatile bool _portInitialized;
  318. std::vector< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to (according to tap)
  319. Hashtable< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups that seem to be behind us and when we last saw them (if we are a bridge)
  320. Hashtable< MAC,Address > _remoteBridgeRoutes; // remote addresses where given MACs are reachable (for tracking devices behind remote bridges)
  321. SharedPtr<NetworkConfig> _config; // Most recent network configuration, which is an immutable value-object
  322. volatile uint64_t _lastConfigUpdate;
  323. volatile bool _destroyed;
  324. enum {
  325. NETCONF_FAILURE_NONE,
  326. NETCONF_FAILURE_ACCESS_DENIED,
  327. NETCONF_FAILURE_NOT_FOUND,
  328. NETCONF_FAILURE_INIT_FAILED
  329. } _netconfFailure;
  330. volatile int _portError; // return value from port config callback
  331. Mutex _lock;
  332. AtomicCounter __refCount;
  333. };
  334. } // naemspace ZeroTier
  335. #endif