Network.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 <string>
  30. #include <set>
  31. #include <map>
  32. #include <vector>
  33. #include <stdexcept>
  34. #include "Constants.hpp"
  35. #include "Utils.hpp"
  36. #include "EthernetTap.hpp"
  37. #include "Address.hpp"
  38. #include "Mutex.hpp"
  39. #include "SharedPtr.hpp"
  40. #include "AtomicCounter.hpp"
  41. #include "MulticastGroup.hpp"
  42. #include "NonCopyable.hpp"
  43. #include "MAC.hpp"
  44. #include "Dictionary.hpp"
  45. #include "Identity.hpp"
  46. #include "InetAddress.hpp"
  47. #include "BandwidthAccount.hpp"
  48. namespace ZeroTier {
  49. class RuntimeEnvironment;
  50. class NodeConfig;
  51. /**
  52. * A virtual LAN
  53. *
  54. * Networks can be open or closed. Each network has an ID whose most
  55. * significant 40 bits are the ZeroTier address of the node that should
  56. * be contacted for network configuration. The least significant 24
  57. * bits are arbitrary, allowing up to 2^24 networks per managing
  58. * node.
  59. *
  60. * Open networks do not track membership. Anyone is allowed to communicate
  61. * over them.
  62. *
  63. * Closed networks track membership by way of timestamped signatures. When
  64. * the network requests its configuration, one of the fields returned is
  65. * a signature for the identity of the peer on the network. This signature
  66. * includes a timestamp. When a peer communicates with other peers on a
  67. * closed network, it periodically (and pre-emptively) propagates this
  68. * signature to the peers with which it is communicating. Peers reject
  69. * packets with an error if no recent signature is on file.
  70. */
  71. class Network : NonCopyable
  72. {
  73. friend class SharedPtr<Network>;
  74. friend class NodeConfig;
  75. public:
  76. /**
  77. * A certificate of network membership for private network participation
  78. */
  79. class Certificate : private Dictionary
  80. {
  81. public:
  82. Certificate() {}
  83. Certificate(const char *s) : Dictionary(s) {}
  84. Certificate(const std::string &s) : Dictionary(s) {}
  85. inline std::string toString() const { return Dictionary::toString(); }
  86. /**
  87. * Sign this certificate
  88. *
  89. * @param with Signing identity -- the identity of this network's controller
  90. * @return Signature or empty string on failure
  91. */
  92. inline std::string sign(const Identity &with) const
  93. {
  94. unsigned char dig[32];
  95. _shaForSignature(dig);
  96. return with.sign(dig);
  97. }
  98. /**
  99. * Verify this certificate's signature
  100. *
  101. * @param with Signing identity -- the identity of this network's controller
  102. * @param sig Signature
  103. * @param siglen Length of signature in bytes
  104. */
  105. inline bool verify(const Identity &with,const void *sig,unsigned int siglen) const
  106. {
  107. unsigned char dig[32];
  108. _shaForSignature(dig);
  109. return with.verifySignature(dig,sig,siglen);
  110. }
  111. /**
  112. * Check if another peer is indeed a current member of this network
  113. *
  114. * Fields with companion ~fields are compared with the defined maximum
  115. * delta in this certificate. Fields without ~fields are compared for
  116. * equality.
  117. *
  118. * This does not verify the certificate's signature!
  119. *
  120. * @param mc Peer membership certificate
  121. * @return True if mc's membership in this network is current
  122. */
  123. bool qualifyMembership(const Certificate &mc) const;
  124. private:
  125. void _shaForSignature(unsigned char *dig) const;
  126. };
  127. /**
  128. * Preload and rates of accrual for multicast group bandwidth limits
  129. *
  130. * Key is multicast group in lower case hex format: MAC (without :s) /
  131. * ADI (hex). Value is a comma-delimited list of: preload, min, max,
  132. * rate of accrual for bandwidth accounts. A key called '*' indicates
  133. * the default for unlisted groups.
  134. */
  135. class MulticastRates : private Dictionary
  136. {
  137. public:
  138. /**
  139. * Preload and accrual parameter tuple
  140. */
  141. struct Rate
  142. {
  143. Rate() {}
  144. Rate(double pl,double minr,double maxr,double bps)
  145. {
  146. preload = pl;
  147. accrual.bytesPerSecond = bps;
  148. accrual.maxBalance = maxr;
  149. accrual.minBalance = minr;
  150. }
  151. double preload;
  152. BandwidthAccount::Accrual accrual;
  153. };
  154. MulticastRates() {}
  155. MulticastRates(const char *s) : Dictionary(s) {}
  156. MulticastRates(const std::string &s) : Dictionary(s) {}
  157. inline std::string toString() const { return Dictionary::toString(); }
  158. /**
  159. * A very minimal default rate, fast enough for ARP
  160. */
  161. static const Rate GLOBAL_DEFAULT_RATE;
  162. /**
  163. * @return Default rate, or GLOBAL_DEFAULT_RATE if not specified
  164. */
  165. Rate defaultRate() const
  166. {
  167. Rate r;
  168. const_iterator dfl(find("*"));
  169. if (dfl == end())
  170. return GLOBAL_DEFAULT_RATE;
  171. return _toRate(dfl->second);
  172. }
  173. /**
  174. * Get the rate for a given multicast group
  175. *
  176. * @param mg Multicast group
  177. * @return Rate or default() rate if not specified
  178. */
  179. Rate get(const MulticastGroup &mg) const
  180. {
  181. const_iterator r(find(mg.toString()));
  182. if (r == end())
  183. return defaultRate();
  184. return _toRate(r->second);
  185. }
  186. private:
  187. static inline Rate _toRate(const std::string &s)
  188. {
  189. char tmp[16384];
  190. Utils::scopy(tmp,sizeof(tmp),s.c_str());
  191. Rate r;
  192. r.preload = 0.0;
  193. r.accrual.bytesPerSecond = 0.0;
  194. r.accrual.maxBalance = 0.0;
  195. r.accrual.minBalance = 0.0;
  196. char *saveptr = (char *)0;
  197. unsigned int fn = 0;
  198. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  199. switch(fn++) {
  200. case 0:
  201. r.preload = Utils::strToDouble(f);
  202. break;
  203. case 1:
  204. r.accrual.minBalance = Utils::strToDouble(f);
  205. break;
  206. case 2:
  207. r.accrual.maxBalance = Utils::strToDouble(f);
  208. break;
  209. case 3:
  210. r.accrual.bytesPerSecond = Utils::strToDouble(f);
  211. break;
  212. }
  213. }
  214. return r;
  215. }
  216. };
  217. /**
  218. * A network configuration for a given node
  219. *
  220. * Configuration fields:
  221. *
  222. * nwid=<hex network ID> (required)
  223. * name=short name
  224. * desc=long(er) description
  225. * com=Certificate (serialized dictionary)
  226. * mr=MulticastRates (serialized dictionary)
  227. * o=open network? (1 or 0, default false if missing)
  228. * et=ethertype whitelist (comma-delimited list of ethertypes in decimal)
  229. * v4s=IPv4 static assignments / netmasks (comma-delimited)
  230. * v6s=IPv6 static assignments / netmasks (comma-delimited)
  231. */
  232. class Config : private Dictionary
  233. {
  234. public:
  235. Config() {}
  236. Config(const char *s) : Dictionary(s) {}
  237. Config(const std::string &s) : Dictionary(s) {}
  238. inline std::string toString() const { return Dictionary::toString(); }
  239. /**
  240. * @return True if configuration is valid and contains required fields
  241. */
  242. inline operator bool() const throw() { return (find("nwid") != end()); }
  243. /**
  244. * @return Network ID
  245. * @throws std::invalid_argument Network ID field missing
  246. */
  247. inline uint64_t networkId() const
  248. throw(std::invalid_argument)
  249. {
  250. return Utils::hexStrToU64(get("nwid").c_str());
  251. }
  252. /**
  253. * Get this network's short name, or its ID in hex if unspecified
  254. *
  255. * @return Short name of this network (e.g. "earth")
  256. */
  257. inline std::string name() const
  258. {
  259. const_iterator n(find("name"));
  260. if (n == end())
  261. return get("nwid");
  262. return n->second;
  263. }
  264. /**
  265. * @return Long description of network or empty string if not present
  266. */
  267. inline std::string desc() const
  268. {
  269. return get("desc",std::string());
  270. }
  271. /**
  272. * @return Certificate of membership for this network, or empty cert if none
  273. */
  274. inline Certificate certificateOfMembership() const
  275. {
  276. const_iterator cm(find("com"));
  277. if (cm == end())
  278. return Certificate();
  279. else return Certificate(cm->second);
  280. }
  281. /**
  282. * @return Multicast rates for this network
  283. */
  284. inline MulticastRates multicastRates() const
  285. {
  286. const_iterator mr(find("mr"));
  287. if (mr == end())
  288. return MulticastRates();
  289. else return MulticastRates(mr->second);
  290. }
  291. /**
  292. * @return True if this is an open non-access-controlled network
  293. */
  294. inline bool isOpen() const
  295. {
  296. const_iterator o(find("o"));
  297. if (o == end())
  298. return false;
  299. else if (!o->second.length())
  300. return false;
  301. else return (o->second[0] == '1');
  302. }
  303. /**
  304. * @return Network ethertype whitelist
  305. */
  306. inline std::set<unsigned int> etherTypes() const
  307. {
  308. char tmp[16384];
  309. char *saveptr = (char *)0;
  310. std::set<unsigned int> et;
  311. if (!Utils::scopy(tmp,sizeof(tmp),get("et","").c_str()))
  312. return et; // sanity check, packet can't really be that big
  313. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  314. unsigned int t = Utils::hexStrToUInt(f);
  315. if (t)
  316. et.insert(t);
  317. }
  318. return et;
  319. }
  320. /**
  321. * @return All static addresses / netmasks, IPv4 or IPv6
  322. */
  323. inline std::set<InetAddress> staticAddresses() const
  324. {
  325. std::set<InetAddress> sa;
  326. std::vector<std::string> ips(Utils::split(get("v4s","").c_str(),",","",""));
  327. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  328. sa.insert(InetAddress(*i));
  329. ips = Utils::split(get("v6s","").c_str(),",","","");
  330. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  331. sa.insert(InetAddress(*i));
  332. return sa;
  333. }
  334. };
  335. /**
  336. * Status for networks
  337. */
  338. enum Status
  339. {
  340. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  341. NETWORK_OK,
  342. NETWORK_ACCESS_DENIED
  343. };
  344. /**
  345. * @param s Status
  346. * @return String description
  347. */
  348. static const char *statusString(const Status s)
  349. throw();
  350. private:
  351. // Only NodeConfig can create, only SharedPtr can delete
  352. // Actual construction happens in newInstance()
  353. Network()
  354. throw() :
  355. _tap((EthernetTap *)0)
  356. {
  357. }
  358. ~Network();
  359. /**
  360. * Create a new Network instance and restore any saved state
  361. *
  362. * If there is no saved state, a dummy .conf is created on disk to remember
  363. * this network across restarts.
  364. *
  365. * @param renv Runtime environment
  366. * @param id Network ID
  367. * @return Reference counted pointer to new network
  368. * @throws std::runtime_error Unable to create tap device or other fatal error
  369. */
  370. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id)
  371. throw(std::runtime_error);
  372. /**
  373. * Causes all persistent disk presence to be erased on delete
  374. */
  375. inline void destroyOnDelete()
  376. {
  377. _destroyOnDelete = true;
  378. }
  379. public:
  380. /**
  381. * @return Network ID
  382. */
  383. inline uint64_t id() const throw() { return _id; }
  384. /**
  385. * @return Ethernet tap
  386. */
  387. inline EthernetTap &tap() throw() { return *_tap; }
  388. /**
  389. * @return Address of network's controlling node
  390. */
  391. inline Address controller() throw() { return Address(_id >> 24); }
  392. /**
  393. * @return Network ID in hexadecimal form
  394. */
  395. inline std::string toString()
  396. {
  397. char buf[64];
  398. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  399. return std::string(buf);
  400. }
  401. /**
  402. * @return True if network is open (no membership required)
  403. */
  404. inline bool isOpen() const
  405. throw()
  406. {
  407. try {
  408. Mutex::Lock _l(_lock);
  409. return _configuration.isOpen();
  410. } catch ( ... ) {
  411. return false;
  412. }
  413. }
  414. /**
  415. * Update multicast groups for this network's tap
  416. *
  417. * @return True if internal multicast group set has changed
  418. */
  419. inline bool updateMulticastGroups()
  420. {
  421. Mutex::Lock _l(_lock);
  422. return _tap->updateMulticastGroups(_multicastGroups);
  423. }
  424. /**
  425. * @return Latest set of multicast groups for this network's tap
  426. */
  427. inline std::set<MulticastGroup> multicastGroups() const
  428. {
  429. Mutex::Lock _l(_lock);
  430. return _multicastGroups;
  431. }
  432. /**
  433. * Set or update this network's configuration
  434. *
  435. * This is called by PacketDecoder when an update comes over the wire, or
  436. * internally when an old config is reloaded from disk.
  437. *
  438. * @param conf Configuration in key/value dictionary form
  439. */
  440. void setConfiguration(const Config &conf);
  441. /**
  442. * Causes this network to request an updated configuration from its master node now
  443. */
  444. void requestConfiguration();
  445. /**
  446. * Add or update a peer's membership certificate
  447. *
  448. * The certificate must already have been validated via signature checking.
  449. *
  450. * @param peer Peer that owns certificate
  451. * @param cert Certificate itself
  452. */
  453. void addMembershipCertificate(const Address &peer,const Certificate &cert);
  454. /**
  455. * @param peer Peer address to check
  456. * @return True if peer is allowed to communicate on this network
  457. */
  458. bool isAllowed(const Address &peer) const;
  459. /**
  460. * Perform cleanup and possibly save state
  461. */
  462. void clean();
  463. /**
  464. * @return Time of last updated configuration or 0 if none
  465. */
  466. inline uint64_t lastConfigUpdate() const
  467. throw()
  468. {
  469. return _lastConfigUpdate;
  470. }
  471. /**
  472. * @return Status of this network
  473. */
  474. Status status() const;
  475. /**
  476. * Determine whether frames of a given ethernet type are allowed on this network
  477. *
  478. * @param etherType Ethernet frame type
  479. * @return True if network permits this type
  480. */
  481. inline bool permitsEtherType(unsigned int etherType) const
  482. throw()
  483. {
  484. if (!etherType)
  485. return false;
  486. else if (etherType > 65535)
  487. return false;
  488. else return ((_etWhitelist[etherType / 8] & (unsigned char)(1 << (etherType % 8))) != 0);
  489. }
  490. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  491. {
  492. Mutex::Lock _l(_lock);
  493. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(std::pair<Address,MulticastGroup>(a,mg)));
  494. }
  495. private:
  496. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  497. void _restoreState();
  498. const RuntimeEnvironment *_r;
  499. // Multicast bandwidth accounting for peers on this network
  500. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount > _multicastRateAccounts;
  501. // Tap and tap multicast memberships for this node on this network
  502. EthernetTap *_tap;
  503. std::set<MulticastGroup> _multicastGroups;
  504. // Membership certificates supplied by other peers on this network
  505. std::map<Address,Certificate> _membershipCertificates;
  506. // Configuration from network master node
  507. Config _configuration;
  508. Certificate _myCertificate;
  509. // Ethertype whitelist bit field, set from config, for really fast lookup
  510. unsigned char _etWhitelist[65536 / 8];
  511. uint64_t _id;
  512. volatile uint64_t _lastConfigUpdate;
  513. volatile bool _destroyOnDelete;
  514. volatile bool _ready;
  515. Mutex _lock;
  516. AtomicCounter __refCount;
  517. };
  518. } // naemspace ZeroTier
  519. #endif