Network.hpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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
  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,"%llu",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,10);
  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 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",ts);
  126. (*this)["ts"] = foo;
  127. sprintf(foo,"%llu",maxDelta);
  128. (*this)["~ts"] = foo;
  129. }
  130. /**
  131. * Set or update the sig field to contain a signature
  132. *
  133. * @param with Signing identity -- the identity of this network's controller
  134. */
  135. void sign(const Identity &with);
  136. /**
  137. * Check if another peer is indeed a current member of this network
  138. *
  139. * Fields with companion ~fields are compared with the defined maximum
  140. * delta in this certificate. Fields without ~fields are compared for
  141. * equality.
  142. *
  143. * This does not verify the certificate's signature! The signature
  144. * must be verified first.
  145. *
  146. * @param mc Peer membership certificate
  147. * @return True if mc's membership in this network is current
  148. */
  149. bool qualifyMembership(const Certificate &mc) const;
  150. };
  151. /**
  152. * A network configuration for a given node
  153. */
  154. class Config : private Dictionary
  155. {
  156. public:
  157. Config()
  158. {
  159. }
  160. Config(const char *s) :
  161. Dictionary(s)
  162. {
  163. }
  164. Config(const std::string &s) :
  165. Dictionary(s)
  166. {
  167. }
  168. /**
  169. * @return Certificate of membership for this network, or empty cert if none
  170. */
  171. inline Certificate certificateOfMembership() const
  172. {
  173. return Certificate(get("com",""));
  174. }
  175. /**
  176. * @return True if this is an open non-access-controlled network
  177. */
  178. inline bool isOpen() const
  179. {
  180. return (get("isOpen","0") == "1");
  181. }
  182. /**
  183. * @return All static addresses / netmasks, IPv4 or IPv6
  184. */
  185. inline std::set<InetAddress> staticAddresses() const
  186. {
  187. std::set<InetAddress> sa;
  188. std::vector<std::string> ips(Utils::split(get("ipv4Static","").c_str(),",","",""));
  189. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  190. sa.insert(InetAddress(*i));
  191. ips = Utils::split(get("ipv6Static","").c_str(),",","","");
  192. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  193. sa.insert(InetAddress(*i));
  194. return sa;
  195. }
  196. /**
  197. * Set static IPv4 and IPv6 addresses
  198. *
  199. * This sets the ipv4Static and ipv6Static fields to comma-delimited
  200. * lists of assignments. The port field in InetAddress must be the
  201. * number of bits in the netmask.
  202. *
  203. * @param begin Start of container or array of addresses (InetAddress)
  204. * @param end End of container or array of addresses (InetAddress)
  205. * @tparam I Type of container or array
  206. */
  207. template<typename I>
  208. inline void setStaticInetAddresses(const I &begin,const I &end)
  209. {
  210. std::string v4;
  211. std::string v6;
  212. for(I i(begin);i!=end;++i) {
  213. if (i->isV4()) {
  214. if (v4.length())
  215. v4.push_back(',');
  216. v4.append(i->toString());
  217. } else if (i->isV6()) {
  218. if (v6.length())
  219. v6.push_back(',');
  220. v6.append(i->toString());
  221. }
  222. }
  223. if (v4.length())
  224. (*this)["ipv4Static"] = v4;
  225. else erase("ipv4Static");
  226. if (v6.length())
  227. (*this)["ipv6Static"] = v6;
  228. else erase("ipv6Static");
  229. }
  230. };
  231. private:
  232. // Only NodeConfig can create, only SharedPtr can delete
  233. Network(const RuntimeEnvironment *renv,uint64_t id)
  234. throw(std::runtime_error);
  235. ~Network();
  236. public:
  237. /**
  238. * @return Network ID
  239. */
  240. inline uint64_t id() const throw() { return _id; }
  241. /**
  242. * @return Ethernet tap
  243. */
  244. inline EthernetTap &tap() throw() { return _tap; }
  245. /**
  246. * @return Address of network's controlling node
  247. */
  248. inline Address controller() throw() { return Address(_id >> 24); }
  249. /**
  250. * @return True if network is open (no membership required)
  251. */
  252. inline bool isOpen() const
  253. throw()
  254. {
  255. Mutex::Lock _l(_lock);
  256. return _isOpen;
  257. }
  258. /**
  259. * Update multicast groups for this network's tap
  260. *
  261. * @return True if internal multicast group set has changed
  262. */
  263. inline bool updateMulticastGroups()
  264. {
  265. Mutex::Lock _l(_lock);
  266. return _tap.updateMulticastGroups(_multicastGroups);
  267. }
  268. /**
  269. * @return Latest set of multicast groups for this network's tap
  270. */
  271. inline std::set<MulticastGroup> multicastGroups() const
  272. {
  273. Mutex::Lock _l(_lock);
  274. return _multicastGroups;
  275. }
  276. /**
  277. * Set or update this network's configuration
  278. *
  279. * This is called by PacketDecoder when an update comes over the wire, or
  280. * internally when an old config is reloaded from disk.
  281. *
  282. * @param conf Configuration in key/value dictionary form
  283. */
  284. void setConfiguration(const Config &conf);
  285. /**
  286. * Causes this network to request an updated configuration from its master node now
  287. */
  288. void requestConfiguration();
  289. private:
  290. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  291. const RuntimeEnvironment *_r;
  292. EthernetTap _tap;
  293. std::set<MulticastGroup> _multicastGroups;
  294. uint64_t _id;
  295. bool _isOpen;
  296. Mutex _lock;
  297. AtomicCounter __refCount;
  298. };
  299. } // naemspace ZeroTier
  300. #endif