Network.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. inline std::string toString() const
  93. {
  94. return Dictionary::toString();
  95. }
  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 bool containsAllFields() const
  189. {
  190. return (contains("nwid")&&contains("peer"));
  191. }
  192. inline std::string toString() const
  193. {
  194. return Dictionary::toString();
  195. }
  196. inline uint64_t networkId() const
  197. throw(std::invalid_argument)
  198. {
  199. return strtoull(get("nwid").c_str(),(char **)0,16);
  200. }
  201. inline Address peerAddress() const
  202. throw(std::invalid_argument)
  203. {
  204. return Address(get("peer"));
  205. }
  206. /**
  207. * @return Certificate of membership for this network, or empty cert if none
  208. */
  209. inline Certificate certificateOfMembership() const
  210. {
  211. const_iterator cm(find("com"));
  212. if (cm == end())
  213. return Certificate();
  214. else return Certificate(cm->second);
  215. }
  216. /**
  217. * @return True if this is an open non-access-controlled network
  218. */
  219. inline bool isOpen() const
  220. {
  221. return (get("isOpen","0") == "1");
  222. }
  223. /**
  224. * @return All static addresses / netmasks, IPv4 or IPv6
  225. */
  226. inline std::set<InetAddress> staticAddresses() const
  227. {
  228. std::set<InetAddress> sa;
  229. std::vector<std::string> ips(Utils::split(get("ipv4Static","").c_str(),",","",""));
  230. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  231. sa.insert(InetAddress(*i));
  232. ips = Utils::split(get("ipv6Static","").c_str(),",","","");
  233. for(std::vector<std::string>::const_iterator i(ips.begin());i!=ips.end();++i)
  234. sa.insert(InetAddress(*i));
  235. return sa;
  236. }
  237. };
  238. private:
  239. // Only NodeConfig can create, only SharedPtr can delete
  240. Network(const RuntimeEnvironment *renv,uint64_t id)
  241. throw(std::runtime_error);
  242. ~Network();
  243. /**
  244. * Called by NodeConfig after create
  245. *
  246. * This is called separately to avoid a rather evil race condition.
  247. * If config is restored in the constructor, then it's possible that
  248. * the tap will be assigned an IP and will start getting packets
  249. * before SharedPtr<Network> has gotten the pointer from the initial
  250. * object construct. That causes SharedPtr<Network> in the static
  251. * method that handles tap traffic to delete the object, resulting
  252. * in all sorts of utter madness. C++ is crazy like that.
  253. *
  254. * Actually the way we're using SharedPtr<Network> is hacky and
  255. * ugly, so it's our fault sorta.
  256. */
  257. void restoreState();
  258. /**
  259. * Causes all persistent disk presence to be erased on delete
  260. */
  261. inline void destroyOnDelete()
  262. {
  263. _destroyOnDelete = true;
  264. }
  265. public:
  266. /**
  267. * @return Network ID
  268. */
  269. inline uint64_t id() const throw() { return _id; }
  270. /**
  271. * @return Ethernet tap
  272. */
  273. inline EthernetTap &tap() throw() { return _tap; }
  274. /**
  275. * @return Address of network's controlling node
  276. */
  277. inline Address controller() throw() { return Address(_id >> 24); }
  278. /**
  279. * @return Network ID in hexadecimal form
  280. */
  281. inline std::string toString()
  282. {
  283. char buf[64];
  284. sprintf(buf,"%.16llx",(unsigned long long)_id);
  285. return std::string(buf);
  286. }
  287. /**
  288. * @return True if network is open (no membership required)
  289. */
  290. inline bool isOpen() const
  291. throw()
  292. {
  293. try {
  294. Mutex::Lock _l(_lock);
  295. return _configuration.isOpen();
  296. } catch ( ... ) {
  297. return false;
  298. }
  299. }
  300. /**
  301. * Update multicast groups for this network's tap
  302. *
  303. * @return True if internal multicast group set has changed
  304. */
  305. inline bool updateMulticastGroups()
  306. {
  307. Mutex::Lock _l(_lock);
  308. return _tap.updateMulticastGroups(_multicastGroups);
  309. }
  310. /**
  311. * @return Latest set of multicast groups for this network's tap
  312. */
  313. inline std::set<MulticastGroup> multicastGroups() const
  314. {
  315. Mutex::Lock _l(_lock);
  316. return _multicastGroups;
  317. }
  318. /**
  319. * Set or update this network's configuration
  320. *
  321. * This is called by PacketDecoder when an update comes over the wire, or
  322. * internally when an old config is reloaded from disk.
  323. *
  324. * @param conf Configuration in key/value dictionary form
  325. */
  326. void setConfiguration(const Config &conf);
  327. /**
  328. * Causes this network to request an updated configuration from its master node now
  329. */
  330. void requestConfiguration();
  331. /**
  332. * Add or update a peer's membership certificate
  333. *
  334. * The certificate must already have been validated via signature checking.
  335. *
  336. * @param peer Peer that owns certificate
  337. * @param cert Certificate itself
  338. */
  339. void addMembershipCertificate(const Address &peer,const Certificate &cert);
  340. /**
  341. * @param peer Peer address to check
  342. * @return True if peer is allowed to communicate on this network
  343. */
  344. bool isAllowed(const Address &peer) const;
  345. /**
  346. * Perform cleanup and possibly save state
  347. */
  348. void clean();
  349. /**
  350. * @return Time of last updated configuration or 0 if none
  351. */
  352. inline uint64_t lastConfigUpdate() const
  353. throw()
  354. {
  355. return _lastConfigUpdate;
  356. }
  357. private:
  358. static void _CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data);
  359. const RuntimeEnvironment *_r;
  360. // Tap and tap multicast memberships
  361. EthernetTap _tap;
  362. std::set<MulticastGroup> _multicastGroups;
  363. // Membership certificates supplied by peers
  364. std::map<Address,Certificate> _membershipCertificates;
  365. // Configuration from network master node
  366. Config _configuration;
  367. Certificate _myCertificate;
  368. uint64_t _id;
  369. volatile uint64_t _lastConfigUpdate;
  370. volatile bool _destroyOnDelete;
  371. Mutex _lock;
  372. AtomicCounter __refCount;
  373. };
  374. } // naemspace ZeroTier
  375. #endif