Network.hpp 17 KB

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