Network.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. namespace ZeroTier {
  48. class RuntimeEnvironment;
  49. class NodeConfig;
  50. /**
  51. * A virtual LAN
  52. *
  53. * Networks can be open or closed. Each network has an ID whose most
  54. * significant 40 bits are the ZeroTier address of the node that should
  55. * be contacted for network configuration. The least significant 24
  56. * bits are arbitrary, allowing up to 2^24 networks per managing
  57. * node.
  58. *
  59. * Open networks do not track membership. Anyone is allowed to communicate
  60. * over them.
  61. *
  62. * Closed networks track membership by way of timestamped signatures. When
  63. * the network requests its configuration, one of the fields returned is
  64. * a signature for the identity of the peer on the network. This signature
  65. * includes a timestamp. When a peer communicates with other peers on a
  66. * closed network, it periodically (and pre-emptively) propagates this
  67. * signature to the peers with which it is communicating. Peers reject
  68. * packets with an error if no recent signature is on file.
  69. */
  70. class Network : NonCopyable
  71. {
  72. friend class SharedPtr<Network>;
  73. friend class NodeConfig;
  74. public:
  75. /**
  76. * A certificate of network membership for private network participation
  77. */
  78. class Certificate : private Dictionary
  79. {
  80. public:
  81. Certificate()
  82. {
  83. }
  84. Certificate(const char *s) :
  85. Dictionary(s)
  86. {
  87. }
  88. Certificate(const std::string &s) :
  89. Dictionary(s)
  90. {
  91. }
  92. /**
  93. * @return Read-only underlying dictionary
  94. */
  95. inline const Dictionary &dictionary() const { return *this; }
  96. inline void setNetworkId(uint64_t id)
  97. {
  98. char buf[32];
  99. sprintf(buf,"%.16llx",(unsigned long long)id);
  100. (*this)["nwid"] = buf;
  101. }
  102. inline uint64_t networkId() const
  103. throw(std::invalid_argument)
  104. {
  105. return strtoull(get("nwid").c_str(),(char **)0,16);
  106. }
  107. inline void setPeerAddress(Address &a)
  108. {
  109. (*this)["peer"] = a.toString();
  110. }
  111. inline Address peerAddress() const
  112. throw(std::invalid_argument)
  113. {
  114. return Address(get("peer"));
  115. }
  116. /**
  117. * Set the timestamp and timestamp max-delta
  118. *
  119. * @param ts Timestamp in ms since epoch
  120. * @param maxDelta Maximum difference between two peers on the same network
  121. */
  122. inline void setTimestamp(uint64_t ts,uint64_t maxDelta)
  123. {
  124. char foo[32];
  125. sprintf(foo,"%llu",(unsigned long long)ts);
  126. (*this)["ts"] = foo;
  127. sprintf(foo,"%llu",(unsigned long long)maxDelta);
  128. (*this)["~ts"] = foo;
  129. }
  130. /**
  131. * Sign this certificate
  132. *
  133. * @param with Signing identity -- the identity of this network's controller
  134. * @return Signature or empty string on failure
  135. */
  136. inline std::string sign(const Identity &with) const
  137. {
  138. unsigned char dig[32];
  139. _shaForSignature(dig);
  140. return with.sign(dig);
  141. }
  142. /**
  143. * Verify this certificate's signature
  144. *
  145. * @param with Signing identity -- the identity of this network's controller
  146. * @param sig Signature
  147. * @param siglen Length of signature in bytes
  148. */
  149. inline bool verify(const Identity &with,const void *sig,unsigned int siglen) const
  150. {
  151. unsigned char dig[32];
  152. _shaForSignature(dig);
  153. return with.verifySignature(dig,sig,siglen);
  154. }
  155. /**
  156. * Check if another peer is indeed a current member of this network
  157. *
  158. * Fields with companion ~fields are compared with the defined maximum
  159. * delta in this certificate. Fields without ~fields are compared for
  160. * equality.
  161. *
  162. * This does not verify the certificate's signature!
  163. *
  164. * @param mc Peer membership certificate
  165. * @return True if mc's membership in this network is current
  166. */
  167. bool qualifyMembership(const Certificate &mc) const;
  168. private:
  169. void _shaForSignature(unsigned char *dig) const;
  170. };
  171. /**
  172. * A network configuration for a given node
  173. */
  174. class Config : private Dictionary
  175. {
  176. public:
  177. Config()
  178. {
  179. }
  180. Config(const char *s) :
  181. Dictionary(s)
  182. {
  183. }
  184. Config(const std::string &s) :
  185. Dictionary(s)
  186. {
  187. }
  188. inline void setNetworkId(uint64_t id)
  189. {
  190. char buf[32];
  191. sprintf(buf,"%.16llx",(unsigned long long)id);
  192. (*this)["nwid"] = buf;
  193. }
  194. inline uint64_t networkId() const
  195. throw(std::invalid_argument)
  196. {
  197. return strtoull(get("nwid").c_str(),(char **)0,16);
  198. }
  199. inline void setPeerAddress(Address &a)
  200. {
  201. (*this)["peer"] = a.toString();
  202. }
  203. inline Address peerAddress() const
  204. throw(std::invalid_argument)
  205. {
  206. return Address(get("peer"));
  207. }
  208. /**
  209. * @return Certificate of membership for this network, or empty cert if none
  210. */
  211. inline Certificate certificateOfMembership() const
  212. {
  213. const_iterator cm(find("com"));
  214. if (cm == end())
  215. return Certificate();
  216. else return Certificate(cm->second);
  217. }
  218. /**
  219. * @return True if this is an open non-access-controlled network
  220. */
  221. inline bool isOpen() const
  222. {
  223. return (get("isOpen") == "1");
  224. }
  225. /**
  226. * @return All static addresses / netmasks, IPv4 or IPv6
  227. */
  228. inline std::set<InetAddress> staticAddresses() const
  229. {
  230. std::set<InetAddress> sa;
  231. std::vector<std::string> ips(Utils::split(get("ipv4Static","").c_str(),",","",""));
  232. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  233. sa.insert(InetAddress(*i));
  234. ips = Utils::split(get("ipv6Static","").c_str(),",","","");
  235. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  236. sa.insert(InetAddress(*i));
  237. return sa;
  238. }
  239. /**
  240. * Set static IPv4 and IPv6 addresses
  241. *
  242. * This sets the ipv4Static and ipv6Static fields to comma-delimited
  243. * lists of assignments. The port field in InetAddress must be the
  244. * number of bits in the netmask.
  245. *
  246. * @param begin Start of container or array of addresses (InetAddress)
  247. * @param end End of container or array of addresses (InetAddress)
  248. * @tparam I Type of container or array
  249. */
  250. template<typename I>
  251. inline void setStaticInetAddresses(const I &begin,const I &end)
  252. {
  253. std::string v4;
  254. std::string v6;
  255. for(I i(begin);i!=end;++i) {
  256. if (i->isV4()) {
  257. if (v4.length())
  258. v4.push_back(',');
  259. v4.append(i->toString());
  260. } else if (i->isV6()) {
  261. if (v6.length())
  262. v6.push_back(',');
  263. v6.append(i->toString());
  264. }
  265. }
  266. if (v4.length())
  267. (*this)["ipv4Static"] = v4;
  268. else erase("ipv4Static");
  269. if (v6.length())
  270. (*this)["ipv6Static"] = v6;
  271. else erase("ipv6Static");
  272. }
  273. };
  274. private:
  275. // Only NodeConfig can create, only SharedPtr can delete
  276. Network(const RuntimeEnvironment *renv,uint64_t id)
  277. throw(std::runtime_error);
  278. ~Network();
  279. public:
  280. /**
  281. * @return Network ID
  282. */
  283. inline uint64_t id() const throw() { return _id; }
  284. /**
  285. * @return Ethernet tap
  286. */
  287. inline EthernetTap &tap() throw() { return _tap; }
  288. /**
  289. * @return Address of network's controlling node
  290. */
  291. inline Address controller() throw() { return Address(_id >> 24); }
  292. /**
  293. * @return Network ID in hexadecimal form
  294. */
  295. inline std::string toString()
  296. {
  297. char buf[64];
  298. sprintf(buf,"%.16llx",(unsigned long long)_id);
  299. return std::string(buf);
  300. }
  301. /**
  302. * @return True if network is open (no membership required)
  303. */
  304. inline bool isOpen() const
  305. throw()
  306. {
  307. try {
  308. Mutex::Lock _l(_lock);
  309. return _configuration.isOpen();
  310. } catch ( ... ) {
  311. return false;
  312. }
  313. }
  314. /**
  315. * Update multicast groups for this network's tap
  316. *
  317. * @return True if internal multicast group set has changed
  318. */
  319. inline bool updateMulticastGroups()
  320. {
  321. Mutex::Lock _l(_lock);
  322. return _tap.updateMulticastGroups(_multicastGroups);
  323. }
  324. /**
  325. * @return Latest set of multicast groups for this network's tap
  326. */
  327. inline std::set<MulticastGroup> multicastGroups() const
  328. {
  329. Mutex::Lock _l(_lock);
  330. return _multicastGroups;
  331. }
  332. /**
  333. * Set or update this network's configuration
  334. *
  335. * This is called by PacketDecoder when an update comes over the wire, or
  336. * internally when an old config is reloaded from disk.
  337. *
  338. * @param conf Configuration in key/value dictionary form
  339. */
  340. void setConfiguration(const Config &conf);
  341. /**
  342. * Causes this network to request an updated configuration from its master node now
  343. */
  344. void requestConfiguration();
  345. /**
  346. * Add or update a peer's membership certificate
  347. *
  348. * The certificate must already have been validated via signature checking.
  349. *
  350. * @param peer Peer that owns certificate
  351. * @param cert Certificate itself
  352. */
  353. inline void addMembershipCertificate(const Address &peer,const Certificate &cert)
  354. {
  355. Mutex::Lock _l(_lock);
  356. _membershipCertificates[peer] = cert;
  357. }
  358. bool isAllowed(const Address &peer) const;
  359. /**
  360. * Perform periodic database cleaning such as removing expired membership certificates
  361. */
  362. void clean();
  363. /**
  364. * @return Time of last updated configuration or 0 if none
  365. */
  366. inline uint64_t lastConfigUpdate() const
  367. throw()
  368. {
  369. return _lastConfigUpdate;
  370. }
  371. private:
  372. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  373. const RuntimeEnvironment *_r;
  374. EthernetTap _tap;
  375. std::set<MulticastGroup> _multicastGroups;
  376. std::map<Address,Certificate> _membershipCertificates;
  377. Config _configuration;
  378. Certificate _myCertificate;
  379. uint64_t _id;
  380. volatile uint64_t _lastConfigUpdate;
  381. Mutex _lock;
  382. AtomicCounter __refCount;
  383. };
  384. } // naemspace ZeroTier
  385. #endif