Network.hpp 17 KB

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