Network.hpp 12 KB

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