Network.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. * Certificates consist of a dictionary containing one or more values with
  80. * optional max delta paramters. A max delta paramter defines the maximum
  81. * absolute value of the difference between each set of two values in order
  82. * for two certificates to match. If there is no max delta parameter, each
  83. * value is compared for straightforward string equality. Values must be
  84. * in hexadecimal (and may be negative) for max delta comparison purposes.
  85. * Decimals are not allowed, so decimal values must be multiplied by some
  86. * factor to convert them to integers with the required relative precision.
  87. * Math is done in 64-bit, allowing plenty of room for this.
  88. *
  89. * This allows membership in a network to be defined not only in terms of
  90. * absolute parameters but also relative comparisons. For example, a network
  91. * could be created that defined membership in terms of a geographic radius.
  92. * Its certificates would contain latitude, longitude, and a max delta for
  93. * each defining the radius.
  94. *
  95. * Max deltas are prefixed by "~". For example, a max delta for "longitude"
  96. * would be "~longitude".
  97. *
  98. * One value and its associated max delta is just about always present: a
  99. * timestamp. This represents the time the certificate was issued by the
  100. * netconf controller. Each peer requests netconf updates periodically with
  101. * new certificates, so this causes peers that are no longer members of the
  102. * network to lose the ability to communicate with their certificate's "ts"
  103. * field differs from everyone else's "ts" by more than "~ts".
  104. */
  105. class Certificate : private Dictionary
  106. {
  107. public:
  108. Certificate() {}
  109. Certificate(const char *s) : Dictionary(s) {}
  110. Certificate(const std::string &s) : Dictionary(s) {}
  111. inline std::string toString() const { return Dictionary::toString(); }
  112. /**
  113. * Sign this certificate
  114. *
  115. * @param with Signing identity -- the identity of this network's controller
  116. * @return Signature or empty string on failure
  117. */
  118. inline std::string sign(const Identity &with) const
  119. {
  120. unsigned char dig[32];
  121. _shaForSignature(dig);
  122. return with.sign(dig);
  123. }
  124. /**
  125. * Verify this certificate's signature
  126. *
  127. * @param with Signing identity -- the identity of this network's controller
  128. * @param sig Signature
  129. * @param siglen Length of signature in bytes
  130. */
  131. inline bool verify(const Identity &with,const void *sig,unsigned int siglen) const
  132. {
  133. unsigned char dig[32];
  134. _shaForSignature(dig);
  135. return with.verifySignature(dig,sig,siglen);
  136. }
  137. /**
  138. * Check if another peer is indeed a current member of this network
  139. *
  140. * Fields with companion ~fields are compared with the defined maximum
  141. * delta in this certificate. Fields without ~fields are compared for
  142. * equality.
  143. *
  144. * This does not verify the certificate's signature!
  145. *
  146. * @param mc Peer membership certificate
  147. * @return True if mc's membership in this network is current
  148. */
  149. bool qualifyMembership(const Certificate &mc) const;
  150. private:
  151. void _shaForSignature(unsigned char *dig) const;
  152. };
  153. /**
  154. * Preload and rates of accrual for multicast group bandwidth limits
  155. *
  156. * Key is multicast group in lower case hex format: MAC (without :s) /
  157. * ADI (hex). Value is a comma-delimited list of: preload, min, max,
  158. * rate of accrual for bandwidth accounts. A key called '*' indicates
  159. * the default for unlisted groups. Values are in hexadecimal and may
  160. * be prefixed with '-' to indicate a negative value.
  161. */
  162. class MulticastRates : private Dictionary
  163. {
  164. public:
  165. /**
  166. * Preload and accrual parameter tuple
  167. */
  168. struct Rate
  169. {
  170. Rate() {}
  171. Rate(int32_t pl,int32_t minb,int32_t maxb,int32_t acc)
  172. {
  173. preload = pl;
  174. minBalance = minb;
  175. maxBalance = maxb;
  176. accrual = acc;
  177. }
  178. int32_t preload;
  179. int32_t minBalance;
  180. int32_t maxBalance;
  181. int32_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,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 = (int32_t)Utils::hexStrToLong(f);
  227. break;
  228. case 1:
  229. r.minBalance = (int32_t)Utils::hexStrToLong(f);
  230. break;
  231. case 2:
  232. r.maxBalance = (int32_t)Utils::hexStrToLong(f);
  233. break;
  234. case 3:
  235. r.accrual = (int32_t)Utils::hexStrToLong(f);
  236. break;
  237. }
  238. }
  239. return r;
  240. }
  241. };
  242. /**
  243. * A network configuration for a given node
  244. *
  245. * Configuration fields:
  246. *
  247. * nwid=<hex network ID> (required)
  248. * name=short name
  249. * desc=long(er) description
  250. * com=Certificate (serialized dictionary)
  251. * mr=MulticastRates (serialized dictionary)
  252. * o=open network? (1 or 0, default false if missing)
  253. * et=ethertype whitelist (comma-delimited list of ethertypes in decimal)
  254. * v4s=IPv4 static assignments / netmasks (comma-delimited)
  255. * v6s=IPv6 static assignments / netmasks (comma-delimited)
  256. */
  257. class Config : private Dictionary
  258. {
  259. public:
  260. Config() {}
  261. Config(const char *s) : Dictionary(s) {}
  262. Config(const std::string &s) : Dictionary(s) {}
  263. inline std::string toString() const { return Dictionary::toString(); }
  264. /**
  265. * @return True if configuration is valid and contains required fields
  266. */
  267. inline operator bool() const throw() { return (find("nwid") != end()); }
  268. /**
  269. * @return Network ID
  270. * @throws std::invalid_argument Network ID field missing
  271. */
  272. inline uint64_t networkId() const
  273. throw(std::invalid_argument)
  274. {
  275. return Utils::hexStrToU64(get("nwid").c_str());
  276. }
  277. /**
  278. * Get this network's short name, or its ID in hex if unspecified
  279. *
  280. * @return Short name of this network (e.g. "earth")
  281. */
  282. inline std::string name() const
  283. {
  284. const_iterator n(find("name"));
  285. if (n == end())
  286. return get("nwid");
  287. return n->second;
  288. }
  289. /**
  290. * @return Long description of network or empty string if not present
  291. */
  292. inline std::string desc() const
  293. {
  294. return get("desc",std::string());
  295. }
  296. /**
  297. * @return Certificate of membership for this network, or empty cert if none
  298. */
  299. inline Certificate certificateOfMembership() const
  300. {
  301. const_iterator cm(find("com"));
  302. if (cm == end())
  303. return Certificate();
  304. else return Certificate(cm->second);
  305. }
  306. /**
  307. * @return Multicast rates for this network
  308. */
  309. inline MulticastRates multicastRates() const
  310. {
  311. const_iterator mr(find("mr"));
  312. if (mr == end())
  313. return MulticastRates();
  314. else return MulticastRates(mr->second);
  315. }
  316. /**
  317. * @return True if this is an open non-access-controlled network
  318. */
  319. inline bool isOpen() const
  320. {
  321. const_iterator o(find("o"));
  322. if (o == end())
  323. return false;
  324. else if (!o->second.length())
  325. return false;
  326. else return (o->second[0] == '1');
  327. }
  328. /**
  329. * @return Network ethertype whitelist
  330. */
  331. inline std::set<unsigned int> etherTypes() const
  332. {
  333. char tmp[16384];
  334. char *saveptr = (char *)0;
  335. std::set<unsigned int> et;
  336. if (!Utils::scopy(tmp,sizeof(tmp),get("et","").c_str()))
  337. return et; // sanity check, packet can't really be that big
  338. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  339. unsigned int t = Utils::hexStrToUInt(f);
  340. if (t)
  341. et.insert(t);
  342. }
  343. return et;
  344. }
  345. /**
  346. * @return All static addresses / netmasks, IPv4 or IPv6
  347. */
  348. inline std::set<InetAddress> staticAddresses() const
  349. {
  350. std::set<InetAddress> sa;
  351. std::vector<std::string> ips(Utils::split(get("v4s","").c_str(),",","",""));
  352. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  353. sa.insert(InetAddress(*i));
  354. ips = Utils::split(get("v6s","").c_str(),",","","");
  355. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  356. sa.insert(InetAddress(*i));
  357. return sa;
  358. }
  359. };
  360. /**
  361. * Status for networks
  362. */
  363. enum Status
  364. {
  365. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  366. NETWORK_OK,
  367. NETWORK_ACCESS_DENIED
  368. };
  369. /**
  370. * @param s Status
  371. * @return String description
  372. */
  373. static const char *statusString(const Status s)
  374. throw();
  375. private:
  376. // Only NodeConfig can create, only SharedPtr can delete
  377. // Actual construction happens in newInstance()
  378. Network()
  379. throw() :
  380. _tap((EthernetTap *)0)
  381. {
  382. }
  383. ~Network();
  384. /**
  385. * Create a new Network instance and restore any saved state
  386. *
  387. * If there is no saved state, a dummy .conf is created on disk to remember
  388. * this network across restarts.
  389. *
  390. * @param renv Runtime environment
  391. * @param id Network ID
  392. * @return Reference counted pointer to new network
  393. * @throws std::runtime_error Unable to create tap device or other fatal error
  394. */
  395. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id)
  396. throw(std::runtime_error);
  397. /**
  398. * Causes all persistent disk presence to be erased on delete
  399. */
  400. inline void destroyOnDelete()
  401. {
  402. _destroyOnDelete = true;
  403. }
  404. public:
  405. /**
  406. * @return Network ID
  407. */
  408. inline uint64_t id() const throw() { return _id; }
  409. /**
  410. * @return Ethernet tap
  411. */
  412. inline EthernetTap &tap() throw() { return *_tap; }
  413. /**
  414. * @return Address of network's controlling node
  415. */
  416. inline Address controller() throw() { return Address(_id >> 24); }
  417. /**
  418. * @return Network ID in hexadecimal form
  419. */
  420. inline std::string toString()
  421. {
  422. char buf[64];
  423. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  424. return std::string(buf);
  425. }
  426. /**
  427. * @return True if network is open (no membership required)
  428. */
  429. inline bool isOpen() const
  430. throw()
  431. {
  432. try {
  433. Mutex::Lock _l(_lock);
  434. return _configuration.isOpen();
  435. } catch ( ... ) {
  436. return false;
  437. }
  438. }
  439. /**
  440. * Update multicast groups for this network's tap
  441. *
  442. * @return True if internal multicast group set has changed
  443. */
  444. inline bool updateMulticastGroups()
  445. {
  446. Mutex::Lock _l(_lock);
  447. return _tap->updateMulticastGroups(_multicastGroups);
  448. }
  449. /**
  450. * @return Latest set of multicast groups for this network's tap
  451. */
  452. inline std::set<MulticastGroup> multicastGroups() const
  453. {
  454. Mutex::Lock _l(_lock);
  455. return _multicastGroups;
  456. }
  457. /**
  458. * Set or update this network's configuration
  459. *
  460. * This is called by PacketDecoder when an update comes over the wire, or
  461. * internally when an old config is reloaded from disk.
  462. *
  463. * @param conf Configuration in key/value dictionary form
  464. */
  465. void setConfiguration(const Config &conf);
  466. /**
  467. * Causes this network to request an updated configuration from its master node now
  468. */
  469. void requestConfiguration();
  470. /**
  471. * Add or update a peer's membership certificate
  472. *
  473. * The certificate must already have been validated via signature checking.
  474. *
  475. * @param peer Peer that owns certificate
  476. * @param cert Certificate itself
  477. */
  478. void addMembershipCertificate(const Address &peer,const Certificate &cert);
  479. /**
  480. * @param peer Peer address to check
  481. * @return True if peer is allowed to communicate on this network
  482. */
  483. bool isAllowed(const Address &peer) const;
  484. /**
  485. * Perform cleanup and possibly save state
  486. */
  487. void clean();
  488. /**
  489. * @return Time of last updated configuration or 0 if none
  490. */
  491. inline uint64_t lastConfigUpdate() const
  492. throw()
  493. {
  494. return _lastConfigUpdate;
  495. }
  496. /**
  497. * @return Status of this network
  498. */
  499. Status status() const;
  500. /**
  501. * Determine whether frames of a given ethernet type are allowed on this network
  502. *
  503. * @param etherType Ethernet frame type
  504. * @return True if network permits this type
  505. */
  506. inline bool permitsEtherType(unsigned int etherType) const
  507. throw()
  508. {
  509. if (!etherType)
  510. return false;
  511. else if (etherType > 65535)
  512. return false;
  513. else return ((_etWhitelist[etherType / 8] & (unsigned char)(1 << (etherType % 8))) != 0);
  514. }
  515. /**
  516. * Update multicast balance for an address and multicast group, return whether packet is allowed
  517. *
  518. * @param a Address that wants to send/relay packet
  519. * @param mg Multicast group
  520. * @param bytes Size of packet
  521. * @return True if packet is within budget
  522. */
  523. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  524. {
  525. Mutex::Lock _l(_lock);
  526. std::pair<Address,MulticastGroup> k(a,mg);
  527. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(k));
  528. if (bal == _multicastRateAccounts.end()) {
  529. MulticastRates::Rate r(_mcRates.get(mg));
  530. bal = _multicastRateAccounts.insert(std::make_pair(k,BandwidthAccount(r.preload,r.minBalance,r.maxBalance,r.accrual))).first;
  531. }
  532. return bal->second.update((int32_t)bytes).second;
  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,Certificate> _membershipCertificates;
  545. // Configuration from network master node
  546. Config _configuration;
  547. Certificate _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