Network.hpp 11 KB

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