Network.hpp 11 KB

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