Network.hpp 14 KB

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