Network.hpp 10 KB

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