Network.hpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  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 <set>
  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 "EthernetTap.hpp"
  40. #include "Address.hpp"
  41. #include "Mutex.hpp"
  42. #include "SharedPtr.hpp"
  43. #include "AtomicCounter.hpp"
  44. #include "MulticastGroup.hpp"
  45. #include "MAC.hpp"
  46. #include "Dictionary.hpp"
  47. #include "Identity.hpp"
  48. #include "InetAddress.hpp"
  49. #include "BandwidthAccount.hpp"
  50. #include "NetworkConfig.hpp"
  51. #include "CertificateOfMembership.hpp"
  52. namespace ZeroTier {
  53. class RuntimeEnvironment;
  54. class NodeConfig;
  55. /**
  56. * A virtual LAN
  57. *
  58. * Networks can be open or closed. Each network has an ID whose most
  59. * significant 40 bits are the ZeroTier address of the node that should
  60. * be contacted for network configuration. The least significant 24
  61. * bits are arbitrary, allowing up to 2^24 networks per managing
  62. * node.
  63. *
  64. * Open networks do not track membership. Anyone is allowed to communicate
  65. * over them. For closed networks, each peer must distribute a certificate
  66. * regularly that proves that they are allowed to communicate.
  67. */
  68. class Network : NonCopyable
  69. {
  70. friend class SharedPtr<Network>;
  71. friend class NodeConfig;
  72. private:
  73. // Only NodeConfig can create, only SharedPtr can delete
  74. // Actual construction happens in newInstance()
  75. Network() throw() : _tap((EthernetTap *)0) {}
  76. ~Network();
  77. /**
  78. * Create a new Network instance and restore any saved state
  79. *
  80. * If there is no saved state, a dummy .conf is created on disk to remember
  81. * this network across restarts.
  82. *
  83. * @param renv Runtime environment
  84. * @param id Network ID
  85. * @return Reference counted pointer to new network
  86. * @throws std::runtime_error Unable to create tap device or other fatal error
  87. */
  88. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id);
  89. /**
  90. * Causes all persistent disk presence to be erased on delete
  91. */
  92. inline void destroyOnDelete() throw() { _destroyOnDelete = true; }
  93. public:
  94. /**
  95. * Possible network states
  96. */
  97. enum Status
  98. {
  99. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  100. NETWORK_OK,
  101. NETWORK_ACCESS_DENIED,
  102. NETWORK_NOT_FOUND
  103. };
  104. /**
  105. * @param s Status
  106. * @return String description
  107. */
  108. static const char *statusString(const Status s)
  109. throw();
  110. /**
  111. * @return Network ID
  112. */
  113. inline uint64_t id() const throw() { return _id; }
  114. /**
  115. * @return Ethernet tap
  116. */
  117. inline EthernetTap &tap() throw() { return *_tap; }
  118. /**
  119. * @return Address of network's controlling node
  120. */
  121. inline Address controller() throw() { return Address(_id >> 24); }
  122. /**
  123. * @return Network ID in hexadecimal form
  124. */
  125. inline std::string idString()
  126. {
  127. char buf[64];
  128. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  129. return std::string(buf);
  130. }
  131. /**
  132. * Update multicast groups for this network's tap
  133. *
  134. * @return True if internal multicast group set has changed
  135. */
  136. inline bool updateMulticastGroups()
  137. {
  138. Mutex::Lock _l(_lock);
  139. return _tap->updateMulticastGroups(_multicastGroups);
  140. }
  141. /**
  142. * @return Latest set of multicast groups for this network's tap
  143. */
  144. inline std::set<MulticastGroup> multicastGroups() const
  145. {
  146. Mutex::Lock _l(_lock);
  147. return _multicastGroups;
  148. }
  149. /**
  150. * Set or update this network's configuration
  151. *
  152. * This is called by PacketDecoder when an update comes over the wire, or
  153. * internally when an old config is reloaded from disk.
  154. *
  155. * @param conf Configuration in key/value dictionary form
  156. * @param saveToDisk IF true (default), write config to disk
  157. */
  158. void setConfiguration(const Dictionary &conf,bool saveToDisk = true);
  159. /**
  160. * Causes this network to request an updated configuration from its master node now
  161. */
  162. void requestConfiguration();
  163. /**
  164. * Add or update a membership certificate
  165. *
  166. * This cert must have been signature checked first. Certs older than the
  167. * cert on file are ignored and the newer cert remains in the database.
  168. *
  169. * @param cert Certificate of membership
  170. */
  171. void addMembershipCertificate(const CertificateOfMembership &cert);
  172. /**
  173. * Push our membership certificate to a peer
  174. *
  175. * @param peer Destination peer address
  176. * @param force If true, push even if we've already done so within required time frame
  177. * @param now Current time
  178. */
  179. inline void pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  180. {
  181. Mutex::Lock _l(_lock);
  182. if ((_config)&&(!_config->isOpen())&&(_config->com()))
  183. _pushMembershipCertificate(peer,force,now);
  184. }
  185. /**
  186. * @param peer Peer address to check
  187. * @return True if peer is allowed to communicate on this network
  188. */
  189. bool isAllowed(const Address &peer) const;
  190. /**
  191. * Perform cleanup and possibly save state
  192. */
  193. void clean();
  194. /**
  195. * @return Time of last updated configuration or 0 if none
  196. */
  197. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  198. /**
  199. * Force this network's status to a particular state based on config reply
  200. */
  201. inline void forceStatusTo(const Status s)
  202. throw()
  203. {
  204. Mutex::Lock _l(_lock);
  205. _status = s;
  206. }
  207. /**
  208. * @return Status of this network
  209. */
  210. inline Status status() const
  211. throw()
  212. {
  213. Mutex::Lock _l(_lock);
  214. return _status;
  215. }
  216. /**
  217. * @return True if this network is in "OK" status and can accept traffic from us
  218. */
  219. inline bool isUp() const
  220. throw()
  221. {
  222. Mutex::Lock _l(_lock);
  223. return ((_config)&&(_status == NETWORK_OK)&&(_ready));
  224. }
  225. /**
  226. * Update multicast balance for an address and multicast group, return whether packet is allowed
  227. *
  228. * @param a Address that wants to send/relay packet
  229. * @param mg Multicast group
  230. * @param bytes Size of packet
  231. * @return True if packet is within budget
  232. */
  233. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  234. {
  235. Mutex::Lock _l(_lock);
  236. if (!_config)
  237. return false;
  238. std::pair<Address,MulticastGroup> k(a,mg);
  239. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(k));
  240. if (bal == _multicastRateAccounts.end()) {
  241. NetworkConfig::MulticastRate r(_config->multicastRate(mg));
  242. bal = _multicastRateAccounts.insert(std::pair< std::pair<Address,MulticastGroup>,BandwidthAccount >(k,BandwidthAccount(r.preload,r.maxBalance,r.accrual))).first;
  243. }
  244. return bal->second.deduct(bytes);
  245. }
  246. /**
  247. * Get current network config or throw exception
  248. *
  249. * This version never returns null. Instead it throws a runtime error if
  250. * there is no current configuration. Callers should check isUp() first or
  251. * use config2() to get with the potential for null.
  252. *
  253. * Since it never returns null, it's safe to config()->whatever().
  254. *
  255. * @return Network configuration (never null)
  256. * @throws std::runtime_error Network configuration unavailable
  257. */
  258. inline SharedPtr<NetworkConfig> config() const
  259. {
  260. Mutex::Lock _l(_lock);
  261. if (_config)
  262. return _config;
  263. throw std::runtime_error("no configuration");
  264. }
  265. /**
  266. * Get current network config or return NULL
  267. *
  268. * @return Network configuration -- may be NULL
  269. */
  270. inline SharedPtr<NetworkConfig> config2() const
  271. throw()
  272. {
  273. Mutex::Lock _l(_lock);
  274. return _config;
  275. }
  276. private:
  277. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  278. void _pushMembershipCertificate(const Address &peer,bool force,uint64_t now);
  279. void _restoreState();
  280. void _dumpMulticastCerts();
  281. uint64_t _id;
  282. const RuntimeEnvironment *_r;
  283. EthernetTap *_tap;
  284. std::set<MulticastGroup> _multicastGroups;
  285. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount > _multicastRateAccounts;
  286. std::map<Address,CertificateOfMembership> _membershipCertificates;
  287. std::map<Address,uint64_t> _lastPushedMembershipCertificate;
  288. SharedPtr<NetworkConfig> _config;
  289. volatile uint64_t _lastConfigUpdate;
  290. volatile Status _status;
  291. volatile bool _destroyOnDelete;
  292. volatile bool _ready;
  293. Mutex _lock;
  294. AtomicCounter __refCount;
  295. };
  296. } // naemspace ZeroTier
  297. #endif