Network.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 "RateLimiter.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. {
  84. }
  85. Certificate(const char *s) :
  86. Dictionary(s)
  87. {
  88. }
  89. Certificate(const std::string &s) :
  90. Dictionary(s)
  91. {
  92. }
  93. inline std::string toString() const
  94. {
  95. return Dictionary::toString();
  96. }
  97. inline void setNetworkId(uint64_t id)
  98. {
  99. char buf[32];
  100. sprintf(buf,"%.16llx",(unsigned long long)id);
  101. (*this)["nwid"] = buf;
  102. }
  103. inline uint64_t networkId() const
  104. throw(std::invalid_argument)
  105. {
  106. #ifdef __WINDOWS__
  107. return _strtoui64(get("nwid").c_str(),(char **)0,16);
  108. #else
  109. return strtoull(get("nwid").c_str(),(char **)0,16);
  110. #endif
  111. }
  112. inline void setPeerAddress(Address &a)
  113. {
  114. (*this)["peer"] = a.toString();
  115. }
  116. inline Address peerAddress() const
  117. throw(std::invalid_argument)
  118. {
  119. return Address(get("peer"));
  120. }
  121. /**
  122. * Set the timestamp and timestamp max-delta
  123. *
  124. * @param ts Timestamp in ms since epoch
  125. * @param maxDelta Maximum difference between two peers on the same network
  126. */
  127. inline void setTimestamp(uint64_t ts,uint64_t maxDelta)
  128. {
  129. char foo[32];
  130. sprintf(foo,"%llu",(unsigned long long)ts);
  131. (*this)["ts"] = foo;
  132. sprintf(foo,"%llu",(unsigned long long)maxDelta);
  133. (*this)["~ts"] = foo;
  134. }
  135. /**
  136. * Sign this certificate
  137. *
  138. * @param with Signing identity -- the identity of this network's controller
  139. * @return Signature or empty string on failure
  140. */
  141. inline std::string sign(const Identity &with) const
  142. {
  143. unsigned char dig[32];
  144. _shaForSignature(dig);
  145. return with.sign(dig);
  146. }
  147. /**
  148. * Verify this certificate's signature
  149. *
  150. * @param with Signing identity -- the identity of this network's controller
  151. * @param sig Signature
  152. * @param siglen Length of signature in bytes
  153. */
  154. inline bool verify(const Identity &with,const void *sig,unsigned int siglen) const
  155. {
  156. unsigned char dig[32];
  157. _shaForSignature(dig);
  158. return with.verifySignature(dig,sig,siglen);
  159. }
  160. /**
  161. * Check if another peer is indeed a current member of this network
  162. *
  163. * Fields with companion ~fields are compared with the defined maximum
  164. * delta in this certificate. Fields without ~fields are compared for
  165. * equality.
  166. *
  167. * This does not verify the certificate's signature!
  168. *
  169. * @param mc Peer membership certificate
  170. * @return True if mc's membership in this network is current
  171. */
  172. bool qualifyMembership(const Certificate &mc) const;
  173. private:
  174. void _shaForSignature(unsigned char *dig) const;
  175. };
  176. /**
  177. * A network configuration for a given node
  178. */
  179. class Config : private Dictionary
  180. {
  181. public:
  182. Config()
  183. {
  184. }
  185. Config(const char *s) :
  186. Dictionary(s)
  187. {
  188. }
  189. Config(const std::string &s) :
  190. Dictionary(s)
  191. {
  192. }
  193. inline bool containsAllFields() const
  194. {
  195. return (contains("nwid")&&contains("peer"));
  196. }
  197. inline std::string toString() const
  198. {
  199. return Dictionary::toString();
  200. }
  201. inline uint64_t networkId() const
  202. throw(std::invalid_argument)
  203. {
  204. #ifdef __WINDOWS__
  205. return _strtoui64(get("nwid").c_str(),(char **)0,16);
  206. #else
  207. return strtoull(get("nwid").c_str(),(char **)0,16);
  208. #endif
  209. }
  210. inline std::string name() const
  211. {
  212. if (contains("name"))
  213. return get("name");
  214. char buf[32];
  215. sprintf(buf,"%.16llx",(unsigned long long)networkId());
  216. return std::string(buf);
  217. }
  218. inline Address peerAddress() const
  219. throw(std::invalid_argument)
  220. {
  221. return Address(get("peer"));
  222. }
  223. /**
  224. * @return Certificate of membership for this network, or empty cert if none
  225. */
  226. inline Certificate certificateOfMembership() const
  227. {
  228. const_iterator cm(find("com"));
  229. if (cm == end())
  230. return Certificate();
  231. else return Certificate(cm->second);
  232. }
  233. /**
  234. * @return True if this is an open non-access-controlled network
  235. */
  236. inline bool isOpen() const
  237. {
  238. return (get("isOpen","0") == "1");
  239. }
  240. /**
  241. * @return Network ethertype whitelist
  242. */
  243. inline std::set<unsigned int> etherTypes() const
  244. {
  245. char tmp[16384];
  246. char *saveptr = (char *)0;
  247. std::set<unsigned int> et;
  248. if (!Utils::scopy(tmp,sizeof(tmp),get("etherTypes","").c_str()))
  249. return et; // sanity check
  250. for(char *f=Utils::stok(tmp,",",&saveptr);(f);f=Utils::stok((char *)0,",",&saveptr)) {
  251. unsigned int t = Utils::stoui(f);
  252. if (t)
  253. et.insert(t);
  254. }
  255. return et;
  256. }
  257. /**
  258. * @return All static addresses / netmasks, IPv4 or IPv6
  259. */
  260. inline std::set<InetAddress> staticAddresses() const
  261. {
  262. std::set<InetAddress> sa;
  263. std::vector<std::string> ips(Utils::split(get("ipv4Static","").c_str(),",","",""));
  264. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  265. sa.insert(InetAddress(*i));
  266. ips = Utils::split(get("ipv6Static","").c_str(),",","","");
  267. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  268. sa.insert(InetAddress(*i));
  269. return sa;
  270. }
  271. };
  272. /**
  273. * Status for networks
  274. */
  275. enum Status
  276. {
  277. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  278. NETWORK_OK,
  279. NETWORK_ACCESS_DENIED
  280. };
  281. /**
  282. * @param s Status
  283. * @return String description
  284. */
  285. static const char *statusString(const Status s)
  286. throw();
  287. private:
  288. // Only NodeConfig can create, only SharedPtr can delete
  289. // Actual construction happens in newInstance()
  290. Network()
  291. throw() :
  292. _tap((EthernetTap *)0)
  293. {
  294. }
  295. ~Network();
  296. /**
  297. * Create a new Network instance and restore any saved state
  298. *
  299. * If there is no saved state, a dummy .conf is created on disk to remember
  300. * this network across restarts.
  301. *
  302. * @param renv Runtime environment
  303. * @param id Network ID
  304. * @return Reference counted pointer to new network
  305. * @throws std::runtime_error Unable to create tap device or other fatal error
  306. */
  307. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id)
  308. throw(std::runtime_error);
  309. /**
  310. * Causes all persistent disk presence to be erased on delete
  311. */
  312. inline void destroyOnDelete()
  313. {
  314. _destroyOnDelete = true;
  315. }
  316. public:
  317. /**
  318. * @return Network ID
  319. */
  320. inline uint64_t id() const throw() { return _id; }
  321. /**
  322. * @return Ethernet tap
  323. */
  324. inline EthernetTap &tap() throw() { return *_tap; }
  325. /**
  326. * @return Address of network's controlling node
  327. */
  328. inline Address controller() throw() { return Address(_id >> 24); }
  329. /**
  330. * @return Network ID in hexadecimal form
  331. */
  332. inline std::string toString()
  333. {
  334. char buf[64];
  335. sprintf(buf,"%.16llx",(unsigned long long)_id);
  336. return std::string(buf);
  337. }
  338. /**
  339. * @return True if network is open (no membership required)
  340. */
  341. inline bool isOpen() const
  342. throw()
  343. {
  344. try {
  345. Mutex::Lock _l(_lock);
  346. return _configuration.isOpen();
  347. } catch ( ... ) {
  348. return false;
  349. }
  350. }
  351. /**
  352. * Update multicast groups for this network's tap
  353. *
  354. * @return True if internal multicast group set has changed
  355. */
  356. inline bool updateMulticastGroups()
  357. {
  358. Mutex::Lock _l(_lock);
  359. return _tap->updateMulticastGroups(_multicastGroups);
  360. }
  361. /**
  362. * @return Latest set of multicast groups for this network's tap
  363. */
  364. inline std::set<MulticastGroup> multicastGroups() const
  365. {
  366. Mutex::Lock _l(_lock);
  367. return _multicastGroups;
  368. }
  369. /**
  370. * Set or update this network's configuration
  371. *
  372. * This is called by PacketDecoder when an update comes over the wire, or
  373. * internally when an old config is reloaded from disk.
  374. *
  375. * @param conf Configuration in key/value dictionary form
  376. */
  377. void setConfiguration(const Config &conf);
  378. /**
  379. * Causes this network to request an updated configuration from its master node now
  380. */
  381. void requestConfiguration();
  382. /**
  383. * Add or update a peer's membership certificate
  384. *
  385. * The certificate must already have been validated via signature checking.
  386. *
  387. * @param peer Peer that owns certificate
  388. * @param cert Certificate itself
  389. */
  390. void addMembershipCertificate(const Address &peer,const Certificate &cert);
  391. /**
  392. * @param peer Peer address to check
  393. * @return True if peer is allowed to communicate on this network
  394. */
  395. bool isAllowed(const Address &peer) const;
  396. /**
  397. * Perform cleanup and possibly save state
  398. */
  399. void clean();
  400. /**
  401. * @return Time of last updated configuration or 0 if none
  402. */
  403. inline uint64_t lastConfigUpdate() const
  404. throw()
  405. {
  406. return _lastConfigUpdate;
  407. }
  408. /**
  409. * @return Status of this network
  410. */
  411. Status status() const;
  412. /**
  413. * @param etherType Ethernet frame type
  414. * @return True if network permits this type
  415. */
  416. inline bool permitsEtherType(unsigned int etherType) const
  417. throw()
  418. {
  419. if (!etherType)
  420. return false;
  421. else if (etherType > 65535)
  422. return false;
  423. else return ((_etWhitelist[etherType / 8] & (unsigned char)(1 << (etherType % 8))) != 0);
  424. }
  425. private:
  426. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  427. void _restoreState();
  428. const RuntimeEnvironment *_r;
  429. // Tap and tap multicast memberships
  430. EthernetTap *_tap;
  431. std::set<MulticastGroup> _multicastGroups;
  432. // Membership certificates supplied by peers
  433. std::map<Address,Certificate> _membershipCertificates;
  434. // Rate limiters for each multicasting peer
  435. std::map<Address,RateLimiter> _multicastRateLimiters;
  436. // Configuration from network master node
  437. Config _configuration;
  438. Certificate _myCertificate;
  439. // Ethertype whitelist bit field, set from config, for really fast lookup
  440. unsigned char _etWhitelist[65536 / 8];
  441. uint64_t _id;
  442. volatile uint64_t _lastConfigUpdate;
  443. volatile bool _destroyOnDelete;
  444. volatile bool _ready;
  445. Mutex _lock;
  446. AtomicCounter __refCount;
  447. };
  448. } // naemspace ZeroTier
  449. #endif