Network.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2015 ZeroTier Networks
  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 "Multicaster.hpp"
  51. #include "NetworkConfig.hpp"
  52. #include "CertificateOfMembership.hpp"
  53. #include "Thread.hpp"
  54. namespace ZeroTier {
  55. class RuntimeEnvironment;
  56. class NodeConfig;
  57. /**
  58. * A virtual LAN
  59. *
  60. * Networks can be open or closed. Each network has an ID whose most
  61. * significant 40 bits are the ZeroTier address of the node that should
  62. * be contacted for network configuration. The least significant 24
  63. * bits are arbitrary, allowing up to 2^24 networks per managing
  64. * node.
  65. *
  66. * Open networks do not track membership. Anyone is allowed to communicate
  67. * over them. For closed networks, each peer must distribute a certificate
  68. * regularly that proves that they are allowed to communicate.
  69. */
  70. class Network : NonCopyable
  71. {
  72. friend class SharedPtr<Network>;
  73. friend class NodeConfig;
  74. private:
  75. // Only NodeConfig can create, only SharedPtr can delete
  76. // Actual construction happens in newInstance()
  77. Network() throw() {}
  78. ~Network();
  79. /**
  80. * Create a new Network instance and restore any saved state
  81. *
  82. * If there is no saved state, a dummy .conf is created on disk to remember
  83. * this network across restarts.
  84. *
  85. * @param renv Runtime environment
  86. * @param nc Parent NodeConfig
  87. * @param id Network ID
  88. * @return Reference counted pointer to new network
  89. * @throws std::runtime_error Unable to create tap device or other fatal error
  90. */
  91. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,NodeConfig *nc,uint64_t id);
  92. public:
  93. /**
  94. * Broadcast multicast group: ff:ff:ff:ff:ff:ff / 0
  95. */
  96. static const MulticastGroup BROADCAST;
  97. /**
  98. * Possible network states
  99. */
  100. enum Status
  101. {
  102. NETWORK_INITIALIZING = 0, // Creating tap device and setting up state
  103. NETWORK_WAITING_FOR_FIRST_AUTOCONF = 1, // Waiting for initial setup with netconf master
  104. NETWORK_OK = 2, // Network is up, seems to be working
  105. NETWORK_ACCESS_DENIED = 3, // Netconf node reported permission denied
  106. NETWORK_NOT_FOUND = 4, // Netconf node reported network not found
  107. NETWORK_INITIALIZATION_FAILED = 5, // Cannot initialize device (OS/installation problem?)
  108. NETWORK_NO_MORE_DEVICES = 6 // OS cannot create any more tap devices (some OSes have a limit)
  109. };
  110. /**
  111. * @param s Status
  112. * @return String description
  113. */
  114. static const char *statusString(const Status s)
  115. throw();
  116. /**
  117. * @return Network ID
  118. */
  119. inline uint64_t id() const throw() { return _id; }
  120. /**
  121. * @return Address of network's netconf master (most significant 40 bits of ID)
  122. */
  123. inline Address controller() throw() { return Address(_id >> 24); }
  124. /**
  125. * @return Network ID in hexadecimal form
  126. */
  127. inline std::string idString()
  128. {
  129. char buf[64];
  130. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  131. return std::string(buf);
  132. }
  133. /**
  134. * Rescan multicast groups for this network's tap and update peers on change
  135. *
  136. * @return True if internal multicast group set has changed since last update
  137. */
  138. bool rescanMulticastGroups();
  139. /**
  140. * @return Latest set of multicast groups for this network's tap
  141. */
  142. inline std::set<MulticastGroup> multicastGroups() const
  143. {
  144. Mutex::Lock _l(_lock);
  145. return _myMulticastGroups;
  146. }
  147. /**
  148. * @param mg Multicast group
  149. * @return True if this network endpoint / peer is a member
  150. */
  151. bool subscribedToMulticastGroup(const MulticastGroup &mg) const
  152. {
  153. Mutex::Lock _l(_lock);
  154. return (_myMulticastGroups.find(mg) != _myMulticastGroups.end());
  155. }
  156. /**
  157. * Apply a NetworkConfig to this network
  158. *
  159. * @param conf Configuration in NetworkConfig form
  160. * @return True if configuration was accepted
  161. */
  162. bool applyConfiguration(const SharedPtr<NetworkConfig> &conf);
  163. /**
  164. * Set or update this network's configuration
  165. *
  166. * This decodes a network configuration in key=value dictionary form,
  167. * applies it if valid, and persists it to disk if saveToDisk is true.
  168. *
  169. * @param conf Configuration in key/value dictionary form
  170. * @param saveToDisk IF true (default), write config to disk
  171. * @return 0 -- rejected, 1 -- accepted but not new, 2 -- accepted new config
  172. */
  173. int setConfiguration(const Dictionary &conf,bool saveToDisk = true);
  174. /**
  175. * Set netconf failure to 'access denied' -- called in IncomingPacket when netconf master reports this
  176. */
  177. inline void setAccessDenied()
  178. {
  179. Mutex::Lock _l(_lock);
  180. _netconfFailure = NETCONF_FAILURE_ACCESS_DENIED;
  181. }
  182. /**
  183. * Set netconf failure to 'not found' -- called by PacketDecider when netconf master reports this
  184. */
  185. inline void setNotFound()
  186. {
  187. Mutex::Lock _l(_lock);
  188. _netconfFailure = NETCONF_FAILURE_NOT_FOUND;
  189. }
  190. /**
  191. * Causes this network to request an updated configuration from its master node now
  192. */
  193. void requestConfiguration();
  194. /**
  195. * Add or update a membership certificate
  196. *
  197. * @param cert Certificate of membership
  198. * @param forceAccept If true, accept without validating signature
  199. */
  200. void addMembershipCertificate(const CertificateOfMembership &cert,bool forceAccept);
  201. /**
  202. * Check if we should push membership certificate to a peer, and update last pushed
  203. *
  204. * If we haven't pushed a cert to this peer in a long enough time, this returns
  205. * true and updates the last pushed time. Otherwise it returns false.
  206. *
  207. * This doesn't actually send anything, since COMs can hitch a ride with several
  208. * different kinds of packets.
  209. *
  210. * @param to Destination peer
  211. * @param now Current time
  212. * @return True if we should include a COM with whatever we're currently sending
  213. */
  214. bool peerNeedsOurMembershipCertificate(const Address &to,uint64_t now);
  215. /**
  216. * @param peer Peer address to check
  217. * @return True if peer is allowed to communicate on this network
  218. */
  219. bool isAllowed(const Address &peer) const;
  220. /**
  221. * Perform cleanup and possibly save state
  222. */
  223. void clean();
  224. /**
  225. * @return Time of last updated configuration or 0 if none
  226. */
  227. inline uint64_t lastConfigUpdate() const throw() { return _lastConfigUpdate; }
  228. /**
  229. * @return Status of this network
  230. */
  231. Status status() const;
  232. /**
  233. * Update and check multicast rate balance for a multicast group
  234. *
  235. * @param mg Multicast group
  236. * @param bytes Size of packet
  237. * @return True if packet is within budget
  238. */
  239. inline bool updateAndCheckMulticastBalance(const MulticastGroup &mg,unsigned int bytes)
  240. {
  241. Mutex::Lock _l(_lock);
  242. if (!_config)
  243. return false;
  244. std::map< MulticastGroup,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(mg));
  245. if (bal == _multicastRateAccounts.end()) {
  246. NetworkConfig::MulticastRate r(_config->multicastRate(mg));
  247. bal = _multicastRateAccounts.insert(std::pair< MulticastGroup,BandwidthAccount >(mg,BandwidthAccount(r.preload,r.maxBalance,r.accrual))).first;
  248. }
  249. return bal->second.deduct(bytes);
  250. }
  251. /**
  252. * Get current network config or throw exception
  253. *
  254. * This version never returns null. Instead it throws a runtime error if
  255. * there is no current configuration. Callers should check isUp() first or
  256. * use config2() to get with the potential for null.
  257. *
  258. * Since it never returns null, it's safe to config()->whatever() inside
  259. * a try/catch block.
  260. *
  261. * @return Network configuration (never null)
  262. * @throws std::runtime_error Network configuration unavailable
  263. */
  264. inline SharedPtr<NetworkConfig> config() const
  265. {
  266. Mutex::Lock _l(_lock);
  267. if (_config)
  268. return _config;
  269. throw std::runtime_error("no configuration");
  270. }
  271. /**
  272. * Get current network config or return NULL
  273. *
  274. * @return Network configuration -- may be NULL
  275. */
  276. inline SharedPtr<NetworkConfig> config2() const
  277. throw()
  278. {
  279. Mutex::Lock _l(_lock);
  280. return _config;
  281. }
  282. /**
  283. * Inject a frame into tap (if it's created and network is enabled)
  284. *
  285. * @param from Origin MAC
  286. * @param to Destination MC
  287. * @param etherType Ethernet frame type
  288. * @param data Frame data
  289. * @param len Frame length
  290. */
  291. inline void tapPut(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  292. {
  293. Mutex::Lock _l(_lock);
  294. if (!_enabled)
  295. return;
  296. EthernetTap *t = _tap;
  297. if (t)
  298. t->put(from,to,etherType,data,len);
  299. }
  300. /**
  301. * Call injectPacketFromHost() on tap if it exists
  302. *
  303. * @param from Source MAC
  304. * @param to Destination MAC
  305. * @param etherType Ethernet frame type
  306. * @param data Packet data
  307. * @param len Packet length
  308. */
  309. inline bool tapInjectPacketFromHost(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  310. {
  311. Mutex::Lock _l(_lock);
  312. EthernetTap *t = _tap;
  313. if (t)
  314. return t->injectPacketFromHost(from,to,etherType,data,len);
  315. return false;
  316. }
  317. /**
  318. * @return Tap device name or empty string if still initializing
  319. */
  320. inline std::string tapDeviceName() const
  321. {
  322. Mutex::Lock _l(_lock);
  323. EthernetTap *t = _tap;
  324. if (t)
  325. return t->deviceName();
  326. else return std::string();
  327. }
  328. /**
  329. * @return Ethernet MAC address for this network's local interface
  330. */
  331. inline const MAC &mac() const throw() { return _mac; }
  332. /**
  333. * @return Set of IPs currently assigned to interface
  334. */
  335. inline std::set<InetAddress> ips() const
  336. {
  337. Mutex::Lock _l(_lock);
  338. EthernetTap *t = _tap;
  339. if (t)
  340. return t->ips();
  341. return std::set<InetAddress>();
  342. }
  343. /**
  344. * Shortcut for config()->permitsBridging(), returns false if no config
  345. *
  346. * @param peer Peer address to check
  347. * @return True if peer can bridge other Ethernet nodes into this network or network is in permissive bridging mode
  348. */
  349. inline bool permitsBridging(const Address &peer) const
  350. {
  351. Mutex::Lock _l(_lock);
  352. if (_config)
  353. return _config->permitsBridging(peer);
  354. return false;
  355. }
  356. /**
  357. * Find the node on this network that has this MAC behind it (if any)
  358. *
  359. * @param mac MAC address
  360. * @return ZeroTier address of bridge to this MAC
  361. */
  362. inline Address findBridgeTo(const MAC &mac) const
  363. {
  364. Mutex::Lock _l(_lock);
  365. std::map<MAC,Address>::const_iterator br(_remoteBridgeRoutes.find(mac));
  366. if (br == _remoteBridgeRoutes.end())
  367. return Address();
  368. return br->second;
  369. }
  370. /**
  371. * Set a bridge route
  372. *
  373. * @param mac MAC address of destination
  374. * @param addr Bridge this MAC is reachable behind
  375. */
  376. void learnBridgeRoute(const MAC &mac,const Address &addr);
  377. /**
  378. * Learn a multicast group that is bridged to our tap device
  379. *
  380. * @param mg Multicast group
  381. * @param now Current time
  382. */
  383. inline void learnBridgedMulticastGroup(const MulticastGroup &mg,uint64_t now)
  384. {
  385. Mutex::Lock _l(_lock);
  386. _multicastGroupsBehindMe[mg] = now;
  387. }
  388. /**
  389. * @return True if traffic on this network's tap is enabled
  390. */
  391. inline bool enabled() const throw() { return _enabled; }
  392. /**
  393. * @param enabled Should traffic be allowed on this network?
  394. */
  395. void setEnabled(bool enabled);
  396. /**
  397. * Destroy this network
  398. *
  399. * This causes the network to disable itself, destroy its tap device, and on
  400. * delete to delete all trace of itself on disk and remove any persistent tap
  401. * device instances. Call this when a network is being removed from the system.
  402. */
  403. void destroy();
  404. /**
  405. * Thread main method; do not call elsewhere
  406. */
  407. void threadMain()
  408. throw();
  409. private:
  410. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  411. void _restoreState();
  412. void _dumpMembershipCerts();
  413. inline void _mkNetworkFriendlyName(char *buf,unsigned int len)
  414. {
  415. // assumes _lock is locked
  416. if (_config)
  417. Utils::snprintf(buf,len,"ZeroTier One [%s]",_config->name().c_str());
  418. else Utils::snprintf(buf,len,"ZeroTier One [%.16llx]",(unsigned long long)_id);
  419. }
  420. uint64_t _id;
  421. NodeConfig *_nc; // parent NodeConfig object
  422. MAC _mac; // local MAC address
  423. const RuntimeEnvironment *RR;
  424. EthernetTap *volatile _tap; // tap device or NULL if not initialized yet
  425. volatile bool _enabled;
  426. std::set< MulticastGroup > _myMulticastGroups; // multicast groups that we belong to including those behind us (updated periodically)
  427. std::map< MulticastGroup,uint64_t > _multicastGroupsBehindMe; // multicast groups bridged to us and when we last saw activity on each
  428. std::map< MulticastGroup,BandwidthAccount > _multicastRateAccounts;
  429. std::map<MAC,Address> _remoteBridgeRoutes; // remote addresses where given MACs are reachable
  430. std::map<Address,CertificateOfMembership> _membershipCertificates; // Other members' certificates of membership
  431. std::map<Address,uint64_t> _lastPushedMembershipCertificate; // When did we last push our certificate to each remote member?
  432. SharedPtr<NetworkConfig> _config; // Most recent network configuration, which is an immutable value-object
  433. volatile uint64_t _lastConfigUpdate;
  434. volatile bool _destroyed;
  435. volatile enum {
  436. NETCONF_FAILURE_NONE,
  437. NETCONF_FAILURE_ACCESS_DENIED,
  438. NETCONF_FAILURE_NOT_FOUND,
  439. NETCONF_FAILURE_INIT_FAILED
  440. } _netconfFailure;
  441. Thread _setupThread;
  442. Mutex _lock;
  443. AtomicCounter __refCount;
  444. };
  445. } // naemspace ZeroTier
  446. #endif