Network.hpp 11 KB

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