Network.hpp 15 KB

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