Network.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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 preload, maximum balance, and rate of accrual in
  158. * hex. These are signed hex numbers, so a negative value can be prefixed
  159. * with '-'.
  160. */
  161. class MulticastRates : private Dictionary
  162. {
  163. public:
  164. /**
  165. * Preload and accrual parameter tuple
  166. */
  167. struct Rate
  168. {
  169. Rate() {}
  170. Rate(int32_t pl,int32_t maxb,int32_t acc)
  171. {
  172. preload = pl;
  173. maxBalance = maxb;
  174. accrual = acc;
  175. }
  176. int32_t preload;
  177. int32_t maxBalance;
  178. int32_t accrual;
  179. };
  180. MulticastRates() {}
  181. MulticastRates(const char *s) : Dictionary(s) {}
  182. MulticastRates(const std::string &s) : Dictionary(s) {}
  183. inline std::string toString() const { return Dictionary::toString(); }
  184. /**
  185. * A very minimal default rate, fast enough for ARP
  186. */
  187. static const Rate GLOBAL_DEFAULT_RATE;
  188. /**
  189. * @return Default rate, or GLOBAL_DEFAULT_RATE if not specified
  190. */
  191. inline Rate defaultRate() const
  192. {
  193. Rate r;
  194. const_iterator dfl(find("*"));
  195. if (dfl == end())
  196. return GLOBAL_DEFAULT_RATE;
  197. return _toRate(dfl->second);
  198. }
  199. /**
  200. * Get the rate for a given multicast group
  201. *
  202. * @param mg Multicast group
  203. * @return Rate or default() rate if not specified
  204. */
  205. inline Rate get(const MulticastGroup &mg) const
  206. {
  207. const_iterator r(find(mg.toString()));
  208. if (r == end())
  209. return defaultRate();
  210. return _toRate(r->second);
  211. }
  212. private:
  213. static inline Rate _toRate(const std::string &s)
  214. {
  215. char tmp[16384];
  216. Utils::scopy(tmp,sizeof(tmp),s.c_str());
  217. Rate r(0,0,0);
  218. char *saveptr = (char *)0;
  219. unsigned int fn = 0;
  220. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  221. switch(fn++) {
  222. case 0:
  223. r.preload = (int32_t)Utils::hexStrToLong(f);
  224. break;
  225. case 1:
  226. r.maxBalance = (int32_t)Utils::hexStrToLong(f);
  227. break;
  228. case 2:
  229. r.accrual = (int32_t)Utils::hexStrToLong(f);
  230. break;
  231. }
  232. }
  233. return r;
  234. }
  235. };
  236. /**
  237. * A network configuration for a given node
  238. *
  239. * Configuration fields:
  240. *
  241. * nwid=<hex network ID> (required)
  242. * name=short name
  243. * desc=long(er) description
  244. * com=Certificate (serialized dictionary)
  245. * mr=MulticastRates (serialized dictionary)
  246. * o=open network? (1 or 0, default false if missing)
  247. * et=ethertype whitelist (comma-delimited list of ethertypes in decimal)
  248. * v4s=IPv4 static assignments / netmasks (comma-delimited)
  249. * v6s=IPv6 static assignments / netmasks (comma-delimited)
  250. */
  251. class Config : private Dictionary
  252. {
  253. public:
  254. Config() {}
  255. Config(const char *s) : Dictionary(s) {}
  256. Config(const std::string &s) : Dictionary(s) {}
  257. inline std::string toString() const { return Dictionary::toString(); }
  258. /**
  259. * @return True if configuration is valid and contains required fields
  260. */
  261. inline operator bool() const throw() { return (find("nwid") != end()); }
  262. /**
  263. * @return Network ID
  264. * @throws std::invalid_argument Network ID field missing
  265. */
  266. inline uint64_t networkId() const
  267. throw(std::invalid_argument)
  268. {
  269. return Utils::hexStrToU64(get("nwid").c_str());
  270. }
  271. /**
  272. * Get this network's short name, or its ID in hex if unspecified
  273. *
  274. * @return Short name of this network (e.g. "earth")
  275. */
  276. inline std::string name() const
  277. {
  278. const_iterator n(find("name"));
  279. if (n == end())
  280. return get("nwid");
  281. return n->second;
  282. }
  283. /**
  284. * @return Long description of network or empty string if not present
  285. */
  286. inline std::string desc() const
  287. {
  288. return get("desc",std::string());
  289. }
  290. /**
  291. * @return Certificate of membership for this network, or empty cert if none
  292. */
  293. inline Certificate certificateOfMembership() const
  294. {
  295. const_iterator cm(find("com"));
  296. if (cm == end())
  297. return Certificate();
  298. else return Certificate(cm->second);
  299. }
  300. /**
  301. * @return Multicast rates for this network
  302. */
  303. inline MulticastRates multicastRates() const
  304. {
  305. const_iterator mr(find("mr"));
  306. if (mr == end())
  307. return MulticastRates();
  308. else return MulticastRates(mr->second);
  309. }
  310. /**
  311. * @return True if this is an open non-access-controlled network
  312. */
  313. inline bool isOpen() const
  314. {
  315. const_iterator o(find("o"));
  316. if (o == end())
  317. return false;
  318. else if (!o->second.length())
  319. return false;
  320. else return (o->second[0] == '1');
  321. }
  322. /**
  323. * @return Network ethertype whitelist
  324. */
  325. inline std::set<unsigned int> etherTypes() const
  326. {
  327. char tmp[16384];
  328. char *saveptr = (char *)0;
  329. std::set<unsigned int> et;
  330. if (!Utils::scopy(tmp,sizeof(tmp),get("et","").c_str()))
  331. return et; // sanity check, packet can't really be that big
  332. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  333. unsigned int t = Utils::hexStrToUInt(f);
  334. if (t)
  335. et.insert(t);
  336. }
  337. return et;
  338. }
  339. /**
  340. * @return All static addresses / netmasks, IPv4 or IPv6
  341. */
  342. inline std::set<InetAddress> staticAddresses() const
  343. {
  344. std::set<InetAddress> sa;
  345. std::vector<std::string> ips(Utils::split(get("v4s","").c_str(),",","",""));
  346. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  347. sa.insert(InetAddress(*i));
  348. ips = Utils::split(get("v6s","").c_str(),",","","");
  349. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  350. sa.insert(InetAddress(*i));
  351. return sa;
  352. }
  353. };
  354. /**
  355. * Status for networks
  356. */
  357. enum Status
  358. {
  359. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  360. NETWORK_OK,
  361. NETWORK_ACCESS_DENIED
  362. };
  363. /**
  364. * @param s Status
  365. * @return String description
  366. */
  367. static const char *statusString(const Status s)
  368. throw();
  369. private:
  370. // Only NodeConfig can create, only SharedPtr can delete
  371. // Actual construction happens in newInstance()
  372. Network()
  373. throw() :
  374. _tap((EthernetTap *)0)
  375. {
  376. }
  377. ~Network();
  378. /**
  379. * Create a new Network instance and restore any saved state
  380. *
  381. * If there is no saved state, a dummy .conf is created on disk to remember
  382. * this network across restarts.
  383. *
  384. * @param renv Runtime environment
  385. * @param id Network ID
  386. * @return Reference counted pointer to new network
  387. * @throws std::runtime_error Unable to create tap device or other fatal error
  388. */
  389. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id)
  390. throw(std::runtime_error);
  391. /**
  392. * Causes all persistent disk presence to be erased on delete
  393. */
  394. inline void destroyOnDelete()
  395. {
  396. _destroyOnDelete = true;
  397. }
  398. public:
  399. /**
  400. * @return Network ID
  401. */
  402. inline uint64_t id() const throw() { return _id; }
  403. /**
  404. * @return Ethernet tap
  405. */
  406. inline EthernetTap &tap() throw() { return *_tap; }
  407. /**
  408. * @return Address of network's controlling node
  409. */
  410. inline Address controller() throw() { return Address(_id >> 24); }
  411. /**
  412. * @return Network ID in hexadecimal form
  413. */
  414. inline std::string toString()
  415. {
  416. char buf[64];
  417. Utils::snprintf(buf,sizeof(buf),"%.16llx",(unsigned long long)_id);
  418. return std::string(buf);
  419. }
  420. /**
  421. * @return True if network is open (no membership required)
  422. */
  423. inline bool isOpen() const
  424. throw()
  425. {
  426. try {
  427. Mutex::Lock _l(_lock);
  428. return _configuration.isOpen();
  429. } catch ( ... ) {
  430. return false;
  431. }
  432. }
  433. /**
  434. * Update multicast groups for this network's tap
  435. *
  436. * @return True if internal multicast group set has changed
  437. */
  438. inline bool updateMulticastGroups()
  439. {
  440. Mutex::Lock _l(_lock);
  441. return _tap->updateMulticastGroups(_multicastGroups);
  442. }
  443. /**
  444. * @return Latest set of multicast groups for this network's tap
  445. */
  446. inline std::set<MulticastGroup> multicastGroups() const
  447. {
  448. Mutex::Lock _l(_lock);
  449. return _multicastGroups;
  450. }
  451. /**
  452. * Set or update this network's configuration
  453. *
  454. * This is called by PacketDecoder when an update comes over the wire, or
  455. * internally when an old config is reloaded from disk.
  456. *
  457. * @param conf Configuration in key/value dictionary form
  458. */
  459. void setConfiguration(const Config &conf);
  460. /**
  461. * Causes this network to request an updated configuration from its master node now
  462. */
  463. void requestConfiguration();
  464. /**
  465. * Add or update a peer's membership certificate
  466. *
  467. * The certificate must already have been validated via signature checking.
  468. *
  469. * @param peer Peer that owns certificate
  470. * @param cert Certificate itself
  471. */
  472. void addMembershipCertificate(const Address &peer,const Certificate &cert);
  473. /**
  474. * @param peer Peer address to check
  475. * @return True if peer is allowed to communicate on this network
  476. */
  477. bool isAllowed(const Address &peer) const;
  478. /**
  479. * Perform cleanup and possibly save state
  480. */
  481. void clean();
  482. /**
  483. * @return Time of last updated configuration or 0 if none
  484. */
  485. inline uint64_t lastConfigUpdate() const
  486. throw()
  487. {
  488. return _lastConfigUpdate;
  489. }
  490. /**
  491. * @return Status of this network
  492. */
  493. Status status() const;
  494. /**
  495. * Determine whether frames of a given ethernet type are allowed on this network
  496. *
  497. * @param etherType Ethernet frame type
  498. * @return True if network permits this type
  499. */
  500. inline bool permitsEtherType(unsigned int etherType) const
  501. throw()
  502. {
  503. if (!etherType)
  504. return false;
  505. else if (etherType > 65535)
  506. return false;
  507. else return ((_etWhitelist[etherType / 8] & (unsigned char)(1 << (etherType % 8))) != 0);
  508. }
  509. /**
  510. * Update multicast balance for an address and multicast group, return whether packet is allowed
  511. *
  512. * @param a Address that wants to send/relay packet
  513. * @param mg Multicast group
  514. * @param bytes Size of packet
  515. * @return True if packet is within budget
  516. */
  517. inline bool updateAndCheckMulticastBalance(const Address &a,const MulticastGroup &mg,unsigned int bytes)
  518. {
  519. Mutex::Lock _l(_lock);
  520. std::pair<Address,MulticastGroup> k(a,mg);
  521. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount >::iterator bal(_multicastRateAccounts.find(k));
  522. if (bal == _multicastRateAccounts.end()) {
  523. MulticastRates::Rate r(_mcRates.get(mg));
  524. bal = _multicastRateAccounts.insert(std::pair< std::pair<Address,MulticastGroup>,BandwidthAccount >(k,BandwidthAccount(r.preload,r.maxBalance,r.accrual))).first;
  525. }
  526. return (bal->second.update((int32_t)bytes) >= 0);
  527. }
  528. private:
  529. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  530. void _restoreState();
  531. const RuntimeEnvironment *_r;
  532. // Multicast bandwidth accounting for peers on this network
  533. std::map< std::pair<Address,MulticastGroup>,BandwidthAccount > _multicastRateAccounts;
  534. // Tap and tap multicast memberships for this node on this network
  535. EthernetTap *_tap;
  536. std::set<MulticastGroup> _multicastGroups;
  537. // Membership certificates supplied by other peers on this network
  538. std::map<Address,Certificate> _membershipCertificates;
  539. // Configuration from network master node
  540. Config _configuration;
  541. Certificate _myCertificate; // memoized from _configuration
  542. MulticastRates _mcRates; // memoized from _configuration
  543. // Ethertype whitelist bit field, set from config, for really fast lookup
  544. unsigned char _etWhitelist[65536 / 8];
  545. uint64_t _id;
  546. volatile uint64_t _lastConfigUpdate;
  547. volatile bool _destroyOnDelete;
  548. volatile bool _ready;
  549. Mutex _lock;
  550. AtomicCounter __refCount;
  551. };
  552. } // naemspace ZeroTier
  553. #endif