Network.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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 "Multicaster.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. * Certificate of network membership
  81. *
  82. * The COM consists of a series of three-element 64-bit tuples. These values
  83. * are an id, a value, and a maximum delta. The ID is arbitrary and should be
  84. * assigned using a scheme that makes every ID globally unique for a given
  85. * type of parameter. ID 0 is reserved for the always-present timestamp
  86. * parameter. The value is parameter-specific. The maximum delta is the
  87. * maximum difference that is permitted between two values for determining
  88. * whether a certificate permits two peers to speak to one another. A value
  89. * of zero indicates that the values must equal.
  90. *
  91. * Certificates of membership must be signed by the netconf master for the
  92. * network in question. This permits members to verify these certs against
  93. * the netconf master's public key before testing them.
  94. */
  95. class CertificateOfMembership
  96. {
  97. public:
  98. CertificateOfMembership() throw() {}
  99. CertificateOfMembership(const char *s) { fromString(s); }
  100. CertificateOfMembership(const std::string &s) { fromString(s.c_str()); }
  101. /**
  102. * Add a paramter to this certificate
  103. *
  104. * @param id Parameter ID
  105. * @param value Parameter value
  106. * @param maxDelta Parameter maximum difference with others
  107. */
  108. void addParameter(uint64_t id,uint64_t value,uint64_t maxDelta);
  109. /**
  110. * @return Hex-serialized representation of this certificate (minus signature)
  111. */
  112. std::string toString() const;
  113. /**
  114. * Set this certificate equal to the hex-serialized string
  115. *
  116. * Invalid strings will result in invalid or undefined certificate
  117. * contents. These will subsequently fail validation and comparison.
  118. *
  119. * @param s String to deserialize
  120. */
  121. void fromString(const char *s);
  122. inline void fromString(const std::string &s) { fromString(s.c_str()); }
  123. /**
  124. * Compare two certificates for parameter agreement
  125. *
  126. * This compares this certificate with the other and returns true if all
  127. * paramters in this cert are present in the other and if they agree to
  128. * within this cert's max delta value for each given parameter.
  129. *
  130. * @param other Cert to compare with
  131. * @return True if certs agree and 'other' may be communicated with
  132. */
  133. bool compare(const CertificateOfMembership &other) const
  134. throw();
  135. private:
  136. struct _Parameter
  137. {
  138. _Parameter() throw() {}
  139. _Parameter(uint64_t i,uint64_t v,uint64_t m) throw() :
  140. id(i),
  141. value(v),
  142. maxDelta(m) {}
  143. uint64_t id;
  144. uint64_t value;
  145. uint64_t maxDelta;
  146. };
  147. // Used with std::sort to ensure that _params are sorted
  148. struct _SortByIdComparison
  149. {
  150. inline bool operator()(const _Parameter &a,const _Parameter &b) const
  151. throw()
  152. {
  153. return (a.id < b.id);
  154. }
  155. };
  156. std::vector<_Parameter> _params;
  157. };
  158. /**
  159. * Preload and rates of accrual for multicast group bandwidth limits
  160. *
  161. * Key is multicast group in lower case hex format: MAC (without :s) /
  162. * ADI (hex). Value is preload, maximum balance, and rate of accrual in
  163. * hex.
  164. */
  165. class MulticastRates : private Dictionary
  166. {
  167. public:
  168. /**
  169. * Preload and accrual parameter tuple
  170. */
  171. struct Rate
  172. {
  173. Rate() {}
  174. Rate(uint32_t pl,uint32_t maxb,uint32_t acc)
  175. {
  176. preload = pl;
  177. maxBalance = maxb;
  178. accrual = acc;
  179. }
  180. uint32_t preload;
  181. uint32_t maxBalance;
  182. uint32_t accrual;
  183. };
  184. MulticastRates() {}
  185. MulticastRates(const char *s) : Dictionary(s) {}
  186. MulticastRates(const std::string &s) : Dictionary(s) {}
  187. inline std::string toString() const { return Dictionary::toString(); }
  188. /**
  189. * A very minimal default rate, fast enough for ARP
  190. */
  191. static const Rate GLOBAL_DEFAULT_RATE;
  192. /**
  193. * @return Default rate, or GLOBAL_DEFAULT_RATE if not specified
  194. */
  195. inline Rate defaultRate() const
  196. {
  197. Rate r;
  198. const_iterator dfl(find("*"));
  199. if (dfl == end())
  200. return GLOBAL_DEFAULT_RATE;
  201. return _toRate(dfl->second);
  202. }
  203. /**
  204. * Get the rate for a given multicast group
  205. *
  206. * @param mg Multicast group
  207. * @return Rate or default() rate if not specified
  208. */
  209. inline Rate get(const MulticastGroup &mg) const
  210. {
  211. const_iterator r(find(mg.toString()));
  212. if (r == end())
  213. return defaultRate();
  214. return _toRate(r->second);
  215. }
  216. private:
  217. static inline Rate _toRate(const std::string &s)
  218. {
  219. char tmp[16384];
  220. Utils::scopy(tmp,sizeof(tmp),s.c_str());
  221. Rate r(0,0,0);
  222. char *saveptr = (char *)0;
  223. unsigned int fn = 0;
  224. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  225. switch(fn++) {
  226. case 0:
  227. r.preload = (uint32_t)Utils::hexStrToULong(f);
  228. break;
  229. case 1:
  230. r.maxBalance = (uint32_t)Utils::hexStrToULong(f);
  231. break;
  232. case 2:
  233. r.accrual = (uint32_t)Utils::hexStrToULong(f);
  234. break;
  235. }
  236. }
  237. return r;
  238. }
  239. };
  240. /**
  241. * A network configuration for a given node
  242. *
  243. * Configuration fields:
  244. *
  245. * nwid=<hex network ID> (required)
  246. * name=short name
  247. * desc=long(er) description
  248. * com=Certificate (serialized dictionary)
  249. * mr=MulticastRates (serialized dictionary)
  250. * o=open network? (1 or 0, default false if missing)
  251. * et=ethertype whitelist (comma-delimited list of ethertypes in decimal)
  252. * v4s=IPv4 static assignments / netmasks (comma-delimited)
  253. * v6s=IPv6 static assignments / netmasks (comma-delimited)
  254. */
  255. class Config : private Dictionary
  256. {
  257. public:
  258. Config() {}
  259. Config(const char *s) : Dictionary(s) {}
  260. Config(const std::string &s) : Dictionary(s) {}
  261. inline std::string toString() const { return Dictionary::toString(); }
  262. /**
  263. * @return True if configuration is valid and contains required fields
  264. */
  265. inline operator bool() const throw() { return (find("nwid") != end()); }
  266. /**
  267. * @return Network ID
  268. * @throws std::invalid_argument Network ID field missing
  269. */
  270. inline uint64_t networkId() const
  271. throw(std::invalid_argument)
  272. {
  273. return Utils::hexStrToU64(get("nwid").c_str());
  274. }
  275. /**
  276. * Get this network's short name, or its ID in hex if unspecified
  277. *
  278. * @return Short name of this network (e.g. "earth")
  279. */
  280. inline std::string name() const
  281. {
  282. const_iterator n(find("name"));
  283. if (n == end())
  284. return get("nwid");
  285. return n->second;
  286. }
  287. /**
  288. * @return Long description of network or empty string if not present
  289. */
  290. inline std::string desc() const
  291. {
  292. return get("desc",std::string());
  293. }
  294. /**
  295. * @return Breadth for multicast propagation
  296. */
  297. inline unsigned int multicastPropagationBreadth() const
  298. {
  299. const_iterator mcb(find("mcb"));
  300. if (mcb == end())
  301. return ZT_MULTICAST_DEFAULT_PROPAGATION_BREADTH;
  302. unsigned int mcb2 = Utils::hexStrToUInt(mcb->second.c_str());
  303. if (mcb2)
  304. return mcb2;
  305. return ZT_MULTICAST_DEFAULT_PROPAGATION_BREADTH;
  306. }
  307. /**
  308. * @return Depth for multicast propagation
  309. */
  310. inline unsigned int multicastPropagationDepth() const
  311. {
  312. const_iterator mcd(find("mcd"));
  313. if (mcd == end())
  314. return ZT_MULTICAST_DEFAULT_PROPAGATION_DEPTH;
  315. unsigned int mcd2 = Utils::hexStrToUInt(mcd->second.c_str());
  316. if (mcd2)
  317. return mcd2;
  318. return ZT_MULTICAST_DEFAULT_PROPAGATION_DEPTH;
  319. }
  320. /**
  321. * @return Certificate of membership for this network, or empty cert if none
  322. */
  323. inline CertificateOfMembership certificateOfMembership() const
  324. {
  325. const_iterator cm(find("com"));
  326. if (cm == end())
  327. return CertificateOfMembership();
  328. else return CertificateOfMembership(cm->second);
  329. }
  330. /**
  331. * @return Multicast rates for this network
  332. */
  333. inline MulticastRates multicastRates() const
  334. {
  335. const_iterator mr(find("mr"));
  336. if (mr == end())
  337. return MulticastRates();
  338. else return MulticastRates(mr->second);
  339. }
  340. /**
  341. * @return True if this is an open non-access-controlled network
  342. */
  343. inline bool isOpen() const
  344. {
  345. const_iterator o(find("o"));
  346. if (o == end())
  347. return false;
  348. else if (!o->second.length())
  349. return false;
  350. else return (o->second[0] == '1');
  351. }
  352. /**
  353. * @return Network ethertype whitelist
  354. */
  355. inline std::set<unsigned int> etherTypes() const
  356. {
  357. char tmp[16384];
  358. char *saveptr = (char *)0;
  359. std::set<unsigned int> et;
  360. if (!Utils::scopy(tmp,sizeof(tmp),get("et","").c_str()))
  361. return et; // sanity check, packet can't really be that big
  362. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  363. unsigned int t = Utils::hexStrToUInt(f);
  364. if (t)
  365. et.insert(t);
  366. }
  367. return et;
  368. }
  369. /**
  370. * @return All static addresses / netmasks, IPv4 or IPv6
  371. */
  372. inline std::set<InetAddress> staticAddresses() const
  373. {
  374. std::set<InetAddress> sa;
  375. std::vector<std::string> ips(Utils::split(get("v4s","").c_str(),",","",""));
  376. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  377. sa.insert(InetAddress(*i));
  378. ips = Utils::split(get("v6s","").c_str(),",","","");
  379. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  380. sa.insert(InetAddress(*i));
  381. return sa;
  382. }
  383. };
  384. /**
  385. * Status for networks
  386. */
  387. enum Status
  388. {
  389. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  390. NETWORK_OK,
  391. NETWORK_ACCESS_DENIED
  392. };
  393. /**
  394. * @param s Status
  395. * @return String description
  396. */
  397. static const char *statusString(const Status s)
  398. throw();
  399. private:
  400. // Only NodeConfig can create, only SharedPtr can delete
  401. // Actual construction happens in newInstance()
  402. Network()
  403. throw() :
  404. _tap((EthernetTap *)0)
  405. {
  406. }
  407. ~Network();
  408. /**
  409. * Create a new Network instance and restore any saved state
  410. *
  411. * If there is no saved state, a dummy .conf is created on disk to remember
  412. * this network across restarts.
  413. *
  414. * @param renv Runtime environment
  415. * @param id Network ID
  416. * @return Reference counted pointer to new network
  417. * @throws std::runtime_error Unable to create tap device or other fatal error
  418. */
  419. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id)
  420. throw(std::runtime_error);
  421. /**
  422. * Causes all persistent disk presence to be erased on delete
  423. */
  424. inline void destroyOnDelete()
  425. {
  426. _destroyOnDelete = true;
  427. }
  428. public:
  429. /**
  430. * @return Network ID
  431. */
  432. inline uint64_t id() const throw() { return _id; }
  433. /**
  434. * @return Ethernet tap
  435. */
  436. inline EthernetTap &tap() throw() { return *_tap; }
  437. /**
  438. * @return Address of network's controlling node
  439. */
  440. inline Address controller() throw() { return Address(_id >> 24); }
  441. /**
  442. * @return Network ID in hexadecimal form
  443. */
  444. inline std::string idString()
  445. {
  446. char buf[64];
  447. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  448. return std::string(buf);
  449. }
  450. /**
  451. * @return True if network is open (no membership required)
  452. */
  453. inline bool isOpen() const
  454. throw()
  455. {
  456. try {
  457. Mutex::Lock _l(_lock);
  458. return _configuration.isOpen();
  459. } catch ( ... ) {
  460. return false;
  461. }
  462. }
  463. /**
  464. * Update multicast groups for this network's tap
  465. *
  466. * @return True if internal multicast group set has changed
  467. */
  468. inline bool updateMulticastGroups()
  469. {
  470. Mutex::Lock _l(_lock);
  471. return _tap->updateMulticastGroups(_multicastGroups);
  472. }
  473. /**
  474. * @return Latest set of multicast groups for this network's tap
  475. */
  476. inline std::set<MulticastGroup> multicastGroups() const
  477. {
  478. Mutex::Lock _l(_lock);
  479. return _multicastGroups;
  480. }
  481. /**
  482. * Set or update this network's configuration
  483. *
  484. * This is called by PacketDecoder when an update comes over the wire, or
  485. * internally when an old config is reloaded from disk.
  486. *
  487. * @param conf Configuration in key/value dictionary form
  488. */
  489. void setConfiguration(const Config &conf);
  490. /**
  491. * Causes this network to request an updated configuration from its master node now
  492. */
  493. void requestConfiguration();
  494. /**
  495. * Add or update a peer's membership certificate
  496. *
  497. * The certificate must already have been validated via signature checking.
  498. *
  499. * @param peer Peer that owns certificate
  500. * @param cert Certificate itself
  501. */
  502. void addMembershipCertificate(const Address &peer,const CertificateOfMembership &cert);
  503. /**
  504. * @param peer Peer address to check
  505. * @return True if peer is allowed to communicate on this network
  506. */
  507. bool isAllowed(const Address &peer) const;
  508. /**
  509. * Perform cleanup and possibly save state
  510. */
  511. void clean();
  512. /**
  513. * @return Time of last updated configuration or 0 if none
  514. */
  515. inline uint64_t lastConfigUpdate() const
  516. throw()
  517. {
  518. return _lastConfigUpdate;
  519. }
  520. /**
  521. * @return Status of this network
  522. */
  523. Status status() const;
  524. /**
  525. * Determine whether frames of a given ethernet type are allowed on this network
  526. *
  527. * @param etherType Ethernet frame type
  528. * @return True if network permits this type
  529. */
  530. inline bool permitsEtherType(unsigned int etherType) const
  531. throw()
  532. {
  533. if (!etherType)
  534. return false;
  535. else if (etherType > 65535)
  536. return false;
  537. else return ((_etWhitelist[etherType / 8] & (unsigned char)(1 << (etherType % 8))) != 0);
  538. }
  539. /**
  540. * Update multicast balance for an address and multicast group, return whether packet is allowed
  541. *
  542. * @param a Address that wants to send/relay packet
  543. * @param mg Multicast group
  544. * @param bytes Size of packet
  545. * @return True if packet is within budget
  546. */
  547. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  548. {
  549. Mutex::Lock _l(_lock);
  550. std::pair<Address,MulticastGroup> k(a,mg);
  551. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(k));
  552. if (bal == _multicastRateAccounts.end()) {
  553. MulticastRates::Rate r(_mcRates.get(mg));
  554. bal = _multicastRateAccounts.insert(std::pair< std::pair<Address,MulticastGroup>,BandwidthAccount >(k,BandwidthAccount(r.preload,r.maxBalance,r.accrual))).first;
  555. }
  556. return bal->second.deduct(bytes);
  557. //bool tmp = bal->second.deduct(bytes);
  558. //printf("%s: BAL: %u\n",mg.toString().c_str(),(unsigned int)bal->second.balance());
  559. //return tmp;
  560. }
  561. /**
  562. * @return Breadth for multicast rumor mill propagation
  563. */
  564. inline unsigned int multicastPropagationBreadth() const
  565. throw()
  566. {
  567. return _multicastPropagationBreadth;
  568. }
  569. /**
  570. * @return Depth for multicast rumor mill propagation
  571. */
  572. inline unsigned int multicastPropagationDepth() const
  573. throw()
  574. {
  575. return _multicastPropagationDepth;
  576. }
  577. private:
  578. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  579. void _restoreState();
  580. const RuntimeEnvironment *_r;
  581. // Multicast bandwidth accounting for peers on this network
  582. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount > _multicastRateAccounts;
  583. // Tap and tap multicast memberships for this node on this network
  584. EthernetTap *_tap;
  585. std::set<MulticastGroup> _multicastGroups;
  586. // Membership certificates supplied by other peers on this network
  587. std::map<Address,CertificateOfMembership> _membershipCertificates;
  588. // Configuration from network master node
  589. Config _configuration;
  590. CertificateOfMembership _myCertificate; // memoized from _configuration
  591. MulticastRates _mcRates; // memoized from _configuration
  592. unsigned int _multicastPropagationBreadth; // memoized from _configuration
  593. unsigned int _multicastPropagationDepth; // memoized from _configuration
  594. // Ethertype whitelist bit field, set from config, for really fast lookup
  595. unsigned char _etWhitelist[65536 / 8];
  596. uint64_t _id;
  597. volatile uint64_t _lastConfigUpdate;
  598. volatile bool _destroyOnDelete;
  599. volatile bool _ready;
  600. Mutex _lock;
  601. AtomicCounter __refCount;
  602. };
  603. } // naemspace ZeroTier
  604. #endif