Network.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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. #include "Thread.hpp"
  53. namespace ZeroTier {
  54. class RuntimeEnvironment;
  55. class NodeConfig;
  56. /**
  57. * A virtual LAN
  58. *
  59. * Networks can be open or closed. Each network has an ID whose most
  60. * significant 40 bits are the ZeroTier address of the node that should
  61. * be contacted for network configuration. The least significant 24
  62. * bits are arbitrary, allowing up to 2^24 networks per managing
  63. * node.
  64. *
  65. * Open networks do not track membership. Anyone is allowed to communicate
  66. * over them. For closed networks, each peer must distribute a certificate
  67. * regularly that proves that they are allowed to communicate.
  68. */
  69. class Network : NonCopyable
  70. {
  71. friend class SharedPtr<Network>;
  72. friend class NodeConfig;
  73. private:
  74. // Only NodeConfig can create, only SharedPtr can delete
  75. // Actual construction happens in newInstance()
  76. Network() throw() {}
  77. ~Network();
  78. /**
  79. * Create a new Network instance and restore any saved state
  80. *
  81. * If there is no saved state, a dummy .conf is created on disk to remember
  82. * this network across restarts.
  83. *
  84. * This can be a time consuming operation on some platforms (cough Windows
  85. * cough).
  86. *
  87. * @param renv Runtime environment
  88. * @param nc Parent NodeConfig
  89. * @param id Network ID
  90. * @return Reference counted pointer to new network
  91. * @throws std::runtime_error Unable to create tap device or other fatal error
  92. */
  93. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,NodeConfig *nc,uint64_t id);
  94. /**
  95. * Causes all persistent disk presence to be erased on delete
  96. */
  97. inline void destroyOnDelete() throw() { _destroyOnDelete = true; }
  98. public:
  99. /**
  100. * Possible network states
  101. */
  102. enum Status
  103. {
  104. NETWORK_INITIALIZING,
  105. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  106. NETWORK_OK,
  107. NETWORK_ACCESS_DENIED,
  108. NETWORK_NOT_FOUND,
  109. NETWORK_INITIALIZATION_FAILED
  110. };
  111. /**
  112. * @param s Status
  113. * @return String description
  114. */
  115. static const char *statusString(const Status s)
  116. throw();
  117. /**
  118. * @return Network ID
  119. */
  120. inline uint64_t id() const throw() { return _id; }
  121. /**
  122. * @return Address of network's controlling node
  123. */
  124. inline Address controller() throw() { return Address(_id >> 24); }
  125. /**
  126. * @return Network ID in hexadecimal form
  127. */
  128. inline std::string idString()
  129. {
  130. char buf[64];
  131. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  132. return std::string(buf);
  133. }
  134. /**
  135. * Update multicast groups for this network's tap
  136. *
  137. * @return True if internal multicast group set has changed
  138. */
  139. inline bool updateMulticastGroups()
  140. {
  141. Mutex::Lock _l(_lock);
  142. EthernetTap *t = _tap;
  143. if (t)
  144. return _tap->updateMulticastGroups(_multicastGroups);
  145. return false;
  146. }
  147. /**
  148. * @return Latest set of multicast groups for this network's tap
  149. */
  150. inline std::set<MulticastGroup> multicastGroups() const
  151. {
  152. Mutex::Lock _l(_lock);
  153. return _multicastGroups;
  154. }
  155. /**
  156. * Set or update this network's configuration
  157. *
  158. * This is called by PacketDecoder when an update comes over the wire, or
  159. * internally when an old config is reloaded from disk.
  160. *
  161. * This also cancels any netconf failure flags.
  162. *
  163. * The network can't accept configuration when in INITIALIZATION state,
  164. * and so in that state this will just return false.
  165. *
  166. * @param conf Configuration in key/value dictionary form
  167. * @param saveToDisk IF true (default), write config to disk
  168. * @return True if configuration was accepted
  169. */
  170. bool setConfiguration(const Dictionary &conf,bool saveToDisk = true);
  171. /**
  172. * Set netconf failure to 'access denied'.
  173. */
  174. inline void setAccessDenied()
  175. {
  176. Mutex::Lock _l(_lock);
  177. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  178. }
  179. /**
  180. * Set netconf failure to 'not found'.
  181. */
  182. inline void setNotFound()
  183. {
  184. Mutex::Lock _l(_lock);
  185. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  186. }
  187. /**
  188. * Causes this network to request an updated configuration from its master node now
  189. */
  190. void requestConfiguration();
  191. /**
  192. * Add or update a membership certificate
  193. *
  194. * This cert must have been signature checked first. Certs older than the
  195. * cert on file are ignored and the newer cert remains in the database.
  196. *
  197. * @param cert Certificate of membership
  198. */
  199. void addMembershipCertificate(const CertificateOfMembership &cert);
  200. /**
  201. * Push our membership certificate to a peer
  202. *
  203. * @param peer Destination peer address
  204. * @param force If true, push even if we've already done so within required time frame
  205. * @param now Current time
  206. */
  207. inline void pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  208. {
  209. Mutex::Lock _l(_lock);
  210. if ((_config)&&(!_config->isOpen())&&(_config->com()))
  211. _pushMembershipCertificate(peer,force,now);
  212. }
  213. /**
  214. * @param peer Peer address to check
  215. * @return True if peer is allowed to communicate on this network
  216. */
  217. bool isAllowed(const Address &peer) const;
  218. /**
  219. * Perform cleanup and possibly save state
  220. */
  221. void clean();
  222. /**
  223. * @return Time of last updated configuration or 0 if none
  224. */
  225. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  226. /**
  227. * @return Status of this network
  228. */
  229. inline Status status() const
  230. throw()
  231. {
  232. Mutex::Lock _l(_lock);
  233. if (_tap) {
  234. switch(_netconfFailure) {
  235. case NETCONF_FAILURE_ACCESS_DENIED:
  236. return NETWORK_ACCESS_DENIED;
  237. case NETCONF_FAILURE_NOT_FOUND:
  238. return NETWORK_NOT_FOUND;
  239. case NETCONF_FAILURE_NONE:
  240. if (_lastConfigUpdate > 0)
  241. return NETWORK_OK;
  242. else return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  243. case NETCONF_FAILURE_INIT_FAILED:
  244. default:
  245. return NETWORK_INITIALIZATION_FAILED;
  246. }
  247. } else if (_netconfFailure == NETCONF_FAILURE_INIT_FAILED) {
  248. return NETWORK_INITIALIZATION_FAILED;
  249. } else return NETWORK_INITIALIZING;
  250. }
  251. /**
  252. * Update multicast balance for an address and multicast group, return whether packet is allowed
  253. *
  254. * @param a Address that wants to send/relay packet
  255. * @param mg Multicast group
  256. * @param bytes Size of packet
  257. * @return True if packet is within budget
  258. */
  259. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  260. {
  261. Mutex::Lock _l(_lock);
  262. if (!_config)
  263. return false;
  264. std::pair<Address,MulticastGroup> k(a,mg);
  265. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(k));
  266. if (bal == _multicastRateAccounts.end()) {
  267. NetworkConfig::MulticastRate r(_config->multicastRate(mg));
  268. bal = _multicastRateAccounts.insert(std::pair< std::pair<Address,MulticastGroup>,BandwidthAccount >(k,BandwidthAccount(r.preload,r.maxBalance,r.accrual))).first;
  269. }
  270. return bal->second.deduct(bytes);
  271. }
  272. /**
  273. * Get current network config or throw exception
  274. *
  275. * This version never returns null. Instead it throws a runtime error if
  276. * there is no current configuration. Callers should check isUp() first or
  277. * use config2() to get with the potential for null.
  278. *
  279. * Since it never returns null, it's safe to config()->whatever().
  280. *
  281. * @return Network configuration (never null)
  282. * @throws std::runtime_error Network configuration unavailable
  283. */
  284. inline SharedPtr<NetworkConfig> config() const
  285. {
  286. Mutex::Lock _l(_lock);
  287. if (_config)
  288. return _config;
  289. throw std::runtime_error("no configuration");
  290. }
  291. /**
  292. * Get current network config or return NULL
  293. *
  294. * @return Network configuration -- may be NULL
  295. */
  296. inline SharedPtr<NetworkConfig> config2() const
  297. throw()
  298. {
  299. Mutex::Lock _l(_lock);
  300. return _config;
  301. }
  302. /**
  303. * Thread main method; do not call elsewhere
  304. */
  305. void threadMain()
  306. throw();
  307. /**
  308. * Inject a frame into tap (if it's created)
  309. *
  310. * @param from Origin MAC
  311. * @param to Destination MC
  312. * @param etherType Ethernet frame type
  313. * @param data Frame data
  314. * @param len Frame length
  315. */
  316. inline void tapPut(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  317. {
  318. EthernetTap *t = _tap;
  319. if (t)
  320. t->put(from,to,etherType,data,len);
  321. }
  322. /**
  323. * Inject a frame into tap with local MAC as destination MAC (if it's created)
  324. *
  325. * @param from Origin MAC
  326. * @param etherType Ethernet frame type
  327. * @param data Frame data
  328. * @param len Frame length
  329. */
  330. inline void tapPut(const MAC &from,unsigned int etherType,const void *data,unsigned int len)
  331. {
  332. EthernetTap *t = _tap;
  333. if (t)
  334. t->put(from,t->mac(),etherType,data,len);
  335. }
  336. /**
  337. * @return Tap device name or empty string if still initializing
  338. */
  339. inline std::string tapDeviceName() const
  340. {
  341. EthernetTap *t = _tap;
  342. if (t)
  343. return t->deviceName();
  344. else return std::string();
  345. }
  346. /**
  347. * @return Ethernet MAC address for this network's local interface
  348. */
  349. inline const MAC &mac() const
  350. {
  351. return _mac;
  352. }
  353. /**
  354. * @return Set of currently assigned IP addresses
  355. */
  356. inline std::set<InetAddress> ips() const
  357. {
  358. EthernetTap *t = _tap;
  359. if (t)
  360. return t->ips();
  361. return std::set<InetAddress>();
  362. }
  363. private:
  364. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  365. void _pushMembershipCertificate(const Address &peer,bool force,uint64_t now);
  366. void _restoreState();
  367. void _dumpMulticastCerts();
  368. uint64_t _id;
  369. NodeConfig *_nc;
  370. MAC _mac;
  371. const RuntimeEnvironment *_r;
  372. EthernetTap *volatile _tap;
  373. std::set<MulticastGroup> _multicastGroups;
  374. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount > _multicastRateAccounts;
  375. std::map<Address,CertificateOfMembership> _membershipCertificates;
  376. std::map<Address,uint64_t> _lastPushedMembershipCertificate;
  377. SharedPtr<NetworkConfig> _config;
  378. volatile uint64_t _lastConfigUpdate;
  379. volatile bool _destroyOnDelete;
  380. volatile enum {
  381. NETCONF_FAILURE_NONE,
  382. NETCONF_FAILURE_ACCESS_DENIED,
  383. NETCONF_FAILURE_NOT_FOUND,
  384. NETCONF_FAILURE_INIT_FAILED
  385. } _netconfFailure;
  386. Thread _setupThread;
  387. Mutex _lock;
  388. AtomicCounter __refCount;
  389. };
  390. } // naemspace ZeroTier
  391. #endif