Network.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. * @param renv Runtime environment
  85. * @param nc Parent NodeConfig
  86. * @param id Network ID
  87. * @return Reference counted pointer to new network
  88. * @throws std::runtime_error Unable to create tap device or other fatal error
  89. */
  90. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,NodeConfig *nc,uint64_t id);
  91. public:
  92. /**
  93. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  94. */
  95. static const MulticastGroup BROADCAST;
  96. /**
  97. * Possible network states
  98. */
  99. enum Status
  100. {
  101. NETWORK_INITIALIZING, // Creating tap device and setting up state
  102. NETWORK_WAITING_FOR_FIRST_AUTOCONF, // Waiting for initial setup with netconf master
  103. NETWORK_OK, // Network is up, seems to be working
  104. NETWORK_ACCESS_DENIED, // Netconf node reported permission denied
  105. NETWORK_NOT_FOUND, // Netconf node reported network not found
  106. NETWORK_INITIALIZATION_FAILED, // Cannot initialize device (OS/installation problem?)
  107. NETWORK_NO_MORE_DEVICES // OS cannot create any more tap devices (some OSes have a limit)
  108. };
  109. /**
  110. * @param s Status
  111. * @return String description
  112. */
  113. static const char *statusString(const Status s)
  114. throw();
  115. /**
  116. * @return Network ID
  117. */
  118. inline uint64_t id() const throw() { return _id; }
  119. /**
  120. * @return Address of network's netconf master (most significant 40 bits of ID)
  121. */
  122. inline Address controller() throw() { return Address(_id >> 24); }
  123. /**
  124. * @return Network ID in hexadecimal form
  125. */
  126. inline std::string idString()
  127. {
  128. char buf[64];
  129. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  130. return std::string(buf);
  131. }
  132. /**
  133. * Update multicast groups for this network's tap
  134. *
  135. * @return True if internal multicast group set has changed since last update
  136. */
  137. bool updateMulticastGroups();
  138. /**
  139. * @return Latest set of multicast groups for this network's tap
  140. */
  141. inline std::set<MulticastGroup> multicastGroups() const
  142. {
  143. Mutex::Lock _l(_lock);
  144. return _multicastGroups;
  145. }
  146. /**
  147. * Set or update this network's configuration
  148. *
  149. * This is called by PacketDecoder when an update comes over the wire, or
  150. * internally when an old config is reloaded from disk.
  151. *
  152. * This also cancels any netconf failure flags.
  153. *
  154. * The network can't accept configuration when in INITIALIZATION state,
  155. * and so in that state this will just return false.
  156. *
  157. * @param conf Configuration in key/value dictionary form
  158. * @param saveToDisk IF true (default), write config to disk
  159. * @return True if configuration was accepted, false if still initializing or config was not valid
  160. */
  161. bool setConfiguration(const Dictionary &conf,bool saveToDisk = true);
  162. /**
  163. * Set netconf failure to 'access denied' -- called by PacketDecoder when netconf master reports this
  164. */
  165. inline void setAccessDenied()
  166. {
  167. Mutex::Lock _l(_lock);
  168. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  169. }
  170. /**
  171. * Set netconf failure to 'not found' -- called by PacketDecider when netconf master reports this
  172. */
  173. inline void setNotFound()
  174. {
  175. Mutex::Lock _l(_lock);
  176. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  177. }
  178. /**
  179. * Causes this network to request an updated configuration from its master node now
  180. */
  181. void requestConfiguration();
  182. /**
  183. * Add or update a membership certificate
  184. *
  185. * This cert must have been signature checked first. Certs older than the
  186. * cert on file are ignored and the newer cert remains in the database.
  187. *
  188. * @param cert Certificate of membership
  189. */
  190. void addMembershipCertificate(const CertificateOfMembership &cert);
  191. /**
  192. * Push our membership certificate to a peer
  193. *
  194. * @param peer Destination peer address
  195. * @param force If true, push even if we've already done so within required time frame
  196. * @param now Current time
  197. */
  198. inline void pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  199. {
  200. Mutex::Lock _l(_lock);
  201. if ((_config)&&(!_config->isPublic())&&(_config->com()))
  202. _pushMembershipCertificate(peer,force,now);
  203. }
  204. /**
  205. * @param peer Peer address to check
  206. * @return True if peer is allowed to communicate on this network
  207. */
  208. bool isAllowed(const Address &peer) const;
  209. /**
  210. * Perform cleanup and possibly save state
  211. */
  212. void clean();
  213. /**
  214. * @return Time of last updated configuration or 0 if none
  215. */
  216. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  217. /**
  218. * @return Status of this network
  219. */
  220. Status status() const;
  221. /**
  222. * Update multicast balance for an address and multicast group, return whether packet is allowed
  223. *
  224. * @param a Originating address of multicast packet
  225. * @param mg Multicast group
  226. * @param bytes Size of packet
  227. * @return True if packet is within budget
  228. */
  229. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  230. {
  231. Mutex::Lock _l(_lock);
  232. if (!_config)
  233. return false;
  234. std::pair<Address,MulticastGroup> k(a,mg);
  235. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(k));
  236. if (bal == _multicastRateAccounts.end()) {
  237. NetworkConfig::MulticastRate r(_config->multicastRate(mg));
  238. bal = _multicastRateAccounts.insert(std::pair< std::pair<Address,MulticastGroup>,BandwidthAccount >(k,BandwidthAccount(r.preload,r.maxBalance,r.accrual))).first;
  239. }
  240. return bal->second.deduct(bytes);
  241. }
  242. /**
  243. * Get current network config or throw exception
  244. *
  245. * This version never returns null. Instead it throws a runtime error if
  246. * there is no current configuration. Callers should check isUp() first or
  247. * use config2() to get with the potential for null.
  248. *
  249. * Since it never returns null, it's safe to config()->whatever() inside
  250. * a try/catch block.
  251. *
  252. * @return Network configuration (never null)
  253. * @throws std::runtime_error Network configuration unavailable
  254. */
  255. inline SharedPtr<NetworkConfig> config() const
  256. {
  257. Mutex::Lock _l(_lock);
  258. if (_config)
  259. return _config;
  260. throw std::runtime_error("no configuration");
  261. }
  262. /**
  263. * Get current network config or return NULL
  264. *
  265. * @return Network configuration -- may be NULL
  266. */
  267. inline SharedPtr<NetworkConfig> config2() const
  268. throw()
  269. {
  270. Mutex::Lock _l(_lock);
  271. return _config;
  272. }
  273. /**
  274. * Thread main method; do not call elsewhere
  275. */
  276. void threadMain()
  277. throw();
  278. /**
  279. * Inject a frame into tap (if it's created and network is enabled)
  280. *
  281. * @param from Origin MAC
  282. * @param to Destination MC
  283. * @param etherType Ethernet frame type
  284. * @param data Frame data
  285. * @param len Frame length
  286. */
  287. inline void tapPut(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  288. {
  289. if (!_enabled)
  290. return;
  291. EthernetTap *t = _tap;
  292. if (t)
  293. t->put(from,to,etherType,data,len);
  294. }
  295. /**
  296. * @return Tap device name or empty string if still initializing
  297. */
  298. inline std::string tapDeviceName() const
  299. {
  300. EthernetTap *t = _tap;
  301. if (t)
  302. return t->deviceName();
  303. else return std::string();
  304. }
  305. /**
  306. * @return Ethernet MAC address for this network's local interface
  307. */
  308. inline const MAC &mac() const
  309. throw()
  310. {
  311. return _mac;
  312. }
  313. /**
  314. * @return Set of currently assigned IP addresses
  315. */
  316. inline std::set<InetAddress> ips() const
  317. {
  318. EthernetTap *t = _tap;
  319. if (t)
  320. return t->ips();
  321. return std::set<InetAddress>();
  322. }
  323. /**
  324. * @return True if multicasts must be authenticated on this network
  325. */
  326. inline bool authenticateMulticasts() const
  327. {
  328. return false;
  329. }
  330. /**
  331. * Shortcut for config()->permitsBridging(), returns false if no config
  332. *
  333. * @param peer Peer address to check
  334. * @return True if peer can bridge other Ethernet nodes into this network or network is in permissive bridging mode
  335. */
  336. inline bool permitsBridging(const Address &peer) const
  337. {
  338. Mutex::Lock _l(_lock);
  339. if (_config)
  340. return _config->permitsBridging(peer);
  341. return false;
  342. }
  343. /**
  344. * @param mac MAC address
  345. * @return ZeroTier address of bridge to this MAC or null address if not found (also check result for self, since this can happen)
  346. */
  347. inline Address findBridgeTo(const MAC &mac) const
  348. {
  349. Mutex::Lock _l(_lock);
  350. std::map<MAC,Address>::const_iterator br(_bridgeRoutes.find(mac));
  351. if (br == _bridgeRoutes.end())
  352. return Address();
  353. return br->second;
  354. }
  355. /**
  356. * Set a bridge route
  357. *
  358. * @param mac MAC address of destination
  359. * @param addr Bridge this MAC is reachable behind
  360. */
  361. void learnBridgeRoute(const MAC &mac,const Address &addr);
  362. /**
  363. * Learn a multicast group that is bridged to our tap device
  364. *
  365. * @param mg Multicast group
  366. * @param now Current time
  367. */
  368. inline void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  369. {
  370. Mutex::Lock _l(_lock);
  371. _bridgedMulticastGroups[mg] = now;
  372. }
  373. /**
  374. * @return True if traffic on this network's tap is enabled
  375. */
  376. inline bool enabled() const throw() { return _enabled; }
  377. /**
  378. * @param enabled Should traffic be allowed on this network?
  379. */
  380. void setEnabled(bool enabled);
  381. /**
  382. * Destroy this network
  383. *
  384. * This causes the network to disable itself, destroy its tap device, and on
  385. * delete to delete all trace of itself on disk and remove any persistent tap
  386. * device instances. Call this when a network is being removed from the system.
  387. */
  388. void destroy();
  389. private:
  390. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  391. void _pushMembershipCertificate(const Address &peer,bool force,uint64_t now);
  392. void _restoreState();
  393. void _dumpMulticastCerts();
  394. inline void _mkNetworkFriendlyName(char *buf,unsigned int len)
  395. {
  396. // assumes _lock is locked
  397. if (_config)
  398. Utils::snprintf(buf,len,"ZeroTier One [%s]",_config->name().c_str());
  399. else Utils::snprintf(buf,len,"ZeroTier One [%.16llx]",(unsigned long long)_id);
  400. }
  401. uint64_t _id;
  402. NodeConfig *_nc; // parent NodeConfig object
  403. MAC _mac; // local MAC address
  404. const RuntimeEnvironment *_r;
  405. EthernetTap *volatile _tap; // tap device or NULL if not initialized yet
  406. volatile bool _enabled;
  407. std::set<MulticastGroup> _multicastGroups;
  408. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount > _multicastRateAccounts;
  409. std::map<Address,CertificateOfMembership> _membershipCertificates;
  410. std::map<Address,uint64_t> _lastPushedMembershipCertificate;
  411. std::map<MAC,Address> _bridgeRoutes; // remote addresses where given MACs are reachable
  412. std::map<MulticastGroup,uint64_t> _bridgedMulticastGroups; // multicast groups of interest on our side of the bridge
  413. SharedPtr<NetworkConfig> _config;
  414. volatile uint64_t _lastConfigUpdate;
  415. volatile bool _destroyed;
  416. volatile enum {
  417. NETCONF_FAILURE_NONE,
  418. NETCONF_FAILURE_ACCESS_DENIED,
  419. NETCONF_FAILURE_NOT_FOUND,
  420. NETCONF_FAILURE_INIT_FAILED
  421. } _netconfFailure;
  422. Thread _setupThread;
  423. Mutex _lock;
  424. AtomicCounter __refCount;
  425. };
  426. } // naemspace ZeroTier
  427. #endif