Network.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 Address peerAddress() const
  211. throw(std::invalid_argument)
  212. {
  213. return Address(get("peer"));
  214. }
  215. /**
  216. * @return Certificate of membership for this network, or empty cert if none
  217. */
  218. inline Certificate certificateOfMembership() const
  219. {
  220. const_iterator cm(find("com"));
  221. if (cm == end())
  222. return Certificate();
  223. else return Certificate(cm->second);
  224. }
  225. /**
  226. * @return True if this is an open non-access-controlled network
  227. */
  228. inline bool isOpen() const
  229. {
  230. return (get("isOpen","0") == "1");
  231. }
  232. /**
  233. * @return All static addresses / netmasks, IPv4 or IPv6
  234. */
  235. inline std::set<InetAddress> staticAddresses() const
  236. {
  237. std::set<InetAddress> sa;
  238. std::vector<std::string> ips(Utils::split(get("ipv4Static","").c_str(),",","",""));
  239. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  240. sa.insert(InetAddress(*i));
  241. ips = Utils::split(get("ipv6Static","").c_str(),",","","");
  242. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  243. sa.insert(InetAddress(*i));
  244. return sa;
  245. }
  246. };
  247. /**
  248. * Status for networks
  249. */
  250. enum Status
  251. {
  252. NETWORK_WAITING_FOR_FIRST_AUTOCONF,
  253. NETWORK_OK,
  254. NETWORK_ACCESS_DENIED
  255. };
  256. /**
  257. * @param s Status
  258. * @return String description
  259. */
  260. static const char *statusString(const Status s)
  261. throw();
  262. private:
  263. // Only NodeConfig can create, only SharedPtr can delete
  264. // Actual construction happens in newInstance()
  265. Network()
  266. throw() :
  267. _tap((EthernetTap *)0)
  268. {
  269. }
  270. ~Network();
  271. /**
  272. * Create a new Network instance and restore any saved state
  273. *
  274. * If there is no saved state, a dummy .conf is created on disk to remember
  275. * this network across restarts.
  276. *
  277. * @param renv Runtime environment
  278. * @param id Network ID
  279. * @return Reference counted pointer to new network
  280. * @throws std::runtime_error Unable to create tap device or other fatal error
  281. */
  282. static SharedPtr<Network> newInstance(const RuntimeEnvironment *renv,uint64_t id)
  283. throw(std::runtime_error);
  284. /**
  285. * Causes all persistent disk presence to be erased on delete
  286. */
  287. inline void destroyOnDelete()
  288. {
  289. _destroyOnDelete = true;
  290. }
  291. public:
  292. /**
  293. * @return Network ID
  294. */
  295. inline uint64_t id() const throw() { return _id; }
  296. /**
  297. * @return Ethernet tap
  298. */
  299. inline EthernetTap &tap() throw() { return *_tap; }
  300. /**
  301. * @return Address of network's controlling node
  302. */
  303. inline Address controller() throw() { return Address(_id >> 24); }
  304. /**
  305. * @return Network ID in hexadecimal form
  306. */
  307. inline std::string toString()
  308. {
  309. char buf[64];
  310. sprintf(buf,"%.16llx",(unsigned long long)_id);
  311. return std::string(buf);
  312. }
  313. /**
  314. * @return True if network is open (no membership required)
  315. */
  316. inline bool isOpen() const
  317. throw()
  318. {
  319. try {
  320. Mutex::Lock _l(_lock);
  321. return _configuration.isOpen();
  322. } catch ( ... ) {
  323. return false;
  324. }
  325. }
  326. /**
  327. * Update multicast groups for this network's tap
  328. *
  329. * @return True if internal multicast group set has changed
  330. */
  331. inline bool updateMulticastGroups()
  332. {
  333. Mutex::Lock _l(_lock);
  334. return _tap->updateMulticastGroups(_multicastGroups);
  335. }
  336. /**
  337. * @return Latest set of multicast groups for this network's tap
  338. */
  339. inline std::set<MulticastGroup> multicastGroups() const
  340. {
  341. Mutex::Lock _l(_lock);
  342. return _multicastGroups;
  343. }
  344. /**
  345. * Set or update this network's configuration
  346. *
  347. * This is called by PacketDecoder when an update comes over the wire, or
  348. * internally when an old config is reloaded from disk.
  349. *
  350. * @param conf Configuration in key/value dictionary form
  351. */
  352. void setConfiguration(const Config &conf);
  353. /**
  354. * Causes this network to request an updated configuration from its master node now
  355. */
  356. void requestConfiguration();
  357. /**
  358. * Add or update a peer's membership certificate
  359. *
  360. * The certificate must already have been validated via signature checking.
  361. *
  362. * @param peer Peer that owns certificate
  363. * @param cert Certificate itself
  364. */
  365. void addMembershipCertificate(const Address &peer,const Certificate &cert);
  366. /**
  367. * @param peer Peer address to check
  368. * @return True if peer is allowed to communicate on this network
  369. */
  370. bool isAllowed(const Address &peer) const;
  371. /**
  372. * Perform cleanup and possibly save state
  373. */
  374. void clean();
  375. /**
  376. * @return Time of last updated configuration or 0 if none
  377. */
  378. inline uint64_t lastConfigUpdate() const
  379. throw()
  380. {
  381. return _lastConfigUpdate;
  382. }
  383. /**
  384. * @return Status of this network
  385. */
  386. Status status() const;
  387. /**
  388. * Invoke multicast rate limiter gate for a given address
  389. *
  390. * @param addr Address to check
  391. * @param bytes Bytes address wishes to send us / propagate
  392. * @return True if allowed, false if overshot rate limit
  393. */
  394. inline bool multicastRateGate(const Address &addr,unsigned int bytes)
  395. {
  396. Mutex::Lock _l(_lock);
  397. std::map<Address,RateLimiter>::iterator rl(_multicastRateLimiters.find(addr));
  398. if (rl == _multicastRateLimiters.end()) {
  399. RateLimiter &newrl = _multicastRateLimiters[addr];
  400. newrl.init(ZT_MULTICAST_DEFAULT_RATE_PRELOAD);
  401. return newrl.gate(_rlLimit,(double)bytes);
  402. }
  403. return rl->second.gate(_rlLimit,(double)bytes);
  404. }
  405. private:
  406. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  407. void _restoreState();
  408. const RuntimeEnvironment *_r;
  409. // Rate limits for this network
  410. RateLimiter::Limit _rlLimit;
  411. // Tap and tap multicast memberships
  412. EthernetTap *_tap;
  413. std::set<MulticastGroup> _multicastGroups;
  414. // Membership certificates supplied by peers
  415. std::map<Address,Certificate> _membershipCertificates;
  416. // Rate limiters for each multicasting peer
  417. std::map<Address,RateLimiter> _multicastRateLimiters;
  418. // Configuration from network master node
  419. Config _configuration;
  420. Certificate _myCertificate;
  421. uint64_t _id;
  422. volatile uint64_t _lastConfigUpdate;
  423. volatile bool _destroyOnDelete;
  424. volatile bool _ready;
  425. Mutex _lock;
  426. AtomicCounter __refCount;
  427. };
  428. } // naemspace ZeroTier
  429. #endif