Network.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. #include <stdio.h>
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <math.h>
  31. #include <algorithm>
  32. #include "Constants.hpp"
  33. #include "RuntimeEnvironment.hpp"
  34. #include "NodeConfig.hpp"
  35. #include "Network.hpp"
  36. #include "Switch.hpp"
  37. #include "Packet.hpp"
  38. #include "Utils.hpp"
  39. #include "Buffer.hpp"
  40. #define ZT_NETWORK_CERT_WRITE_BUF_SIZE 524288
  41. namespace ZeroTier {
  42. const Network::MulticastRates::Rate Network::MulticastRates::GLOBAL_DEFAULT_RATE(65535,65535,64);
  43. const char *Network::statusString(const Status s)
  44. throw()
  45. {
  46. switch(s) {
  47. case NETWORK_WAITING_FOR_FIRST_AUTOCONF: return "WAITING_FOR_FIRST_AUTOCONF";
  48. case NETWORK_OK: return "OK";
  49. case NETWORK_ACCESS_DENIED: return "ACCESS_DENIED";
  50. case NETWORK_NOT_FOUND: return "NOT_FOUND";
  51. }
  52. return "(invalid)";
  53. }
  54. Network::~Network()
  55. {
  56. delete _tap;
  57. if (_destroyOnDelete) {
  58. Utils::rm(std::string(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf"));
  59. Utils::rm(std::string(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts"));
  60. } else {
  61. // Causes flush of membership certs to disk
  62. clean();
  63. _dumpMulticastCerts();
  64. }
  65. }
  66. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,uint64_t id)
  67. throw(std::runtime_error)
  68. {
  69. // Tag to identify tap device -- used on some OSes like Windows
  70. char tag[32];
  71. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)id);
  72. // We construct Network via a static method to ensure that it is immediately
  73. // wrapped in a SharedPtr<>. Otherwise if there is traffic on the Ethernet
  74. // tap device, a SharedPtr<> wrap can occur in the Ethernet frame handler
  75. // that then causes the Network instance to be deleted before it is finished
  76. // being constructed. C++ edge cases, how I love thee.
  77. SharedPtr<Network> nw(new Network());
  78. nw->_ready = false; // disable handling of Ethernet frames during construct
  79. nw->_r = renv;
  80. nw->_tap = new EthernetTap(renv,tag,renv->identity.address().toMAC(),ZT_IF_MTU,&_CBhandleTapData,nw.ptr());
  81. nw->_isOpen = false;
  82. nw->_emulateArp = false;
  83. nw->_emulateNdp = false;
  84. nw->_arpCacheTtl = 0;
  85. nw->_ndpCacheTtl = 0;
  86. nw->_multicastPrefixBits = ZT_DEFAULT_MULTICAST_PREFIX_BITS;
  87. nw->_multicastDepth = ZT_DEFAULT_MULTICAST_DEPTH;
  88. nw->_status = NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  89. memset(nw->_etWhitelist,0,sizeof(nw->_etWhitelist));
  90. nw->_id = id;
  91. nw->_lastConfigUpdate = 0;
  92. nw->_destroyOnDelete = false;
  93. if (nw->controller() == renv->identity.address()) // netconf masters can't really join networks
  94. throw std::runtime_error("cannot join a network for which I am the netconf master");
  95. nw->_restoreState();
  96. nw->_ready = true; // enable handling of Ethernet frames
  97. nw->requestConfiguration();
  98. return nw;
  99. }
  100. void Network::setConfiguration(const Network::Config &conf,bool saveToDisk)
  101. {
  102. Mutex::Lock _l(_lock);
  103. try {
  104. if (conf.networkId() == _id) { // sanity check
  105. _configuration = conf;
  106. // Grab some things from conf for faster lookup and memoize them
  107. _myCertificate = conf.certificateOfMembership();
  108. _mcRates = conf.multicastRates();
  109. _staticAddresses = conf.staticAddresses();
  110. _isOpen = conf.isOpen();
  111. _emulateArp = conf.emulateArp();
  112. _emulateNdp = conf.emulateNdp();
  113. _arpCacheTtl = conf.arpCacheTtl();
  114. _ndpCacheTtl = conf.ndpCacheTtl();
  115. _multicastPrefixBits = conf.multicastPrefixBits();
  116. _multicastDepth = conf.multicastDepth();
  117. _lastConfigUpdate = Utils::now();
  118. _tap->setIps(_staticAddresses);
  119. _tap->setDisplayName((std::string("ZeroTier One [") + conf.name() + "]").c_str());
  120. // Expand ethertype whitelist into fast-lookup bit field (more memoization)
  121. memset(_etWhitelist,0,sizeof(_etWhitelist));
  122. std::set<unsigned int> wl(conf.etherTypes());
  123. for(std::set<unsigned int>::const_iterator t(wl.begin());t!=wl.end();++t)
  124. _etWhitelist[*t / 8] |= (unsigned char)(1 << (*t % 8));
  125. _status = NETWORK_OK;
  126. if (saveToDisk) {
  127. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  128. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  129. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  130. }
  131. }
  132. }
  133. } catch ( ... ) {
  134. // If conf is invalid, reset everything
  135. _configuration = Config();
  136. _myCertificate = CertificateOfMembership();
  137. _mcRates = MulticastRates();
  138. _staticAddresses.clear();
  139. _isOpen = false;
  140. _emulateArp = false;
  141. _emulateNdp = false;
  142. _arpCacheTtl = 0;
  143. _ndpCacheTtl = 0;
  144. _status = NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  145. _lastConfigUpdate = 0;
  146. LOG("unexpected exception handling config for network %.16llx, retrying fetch...",(unsigned long long)_id);
  147. }
  148. }
  149. void Network::requestConfiguration()
  150. {
  151. if (controller() == _r->identity.address()) {
  152. // netconf master cannot be a member of its own nets
  153. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  154. return;
  155. }
  156. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  157. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  158. outp.append((uint64_t)_id);
  159. outp.append((uint16_t)0); // no meta-data
  160. _r->sw->send(outp,true);
  161. }
  162. void Network::addMembershipCertificate(const CertificateOfMembership &cert)
  163. {
  164. Mutex::Lock _l(_lock);
  165. // We go ahead and accept certs provisionally even if _isOpen is true, since
  166. // that might be changed in short order if the user is fiddling in the UI.
  167. // These will be purged on clean() for open networks eventually.
  168. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  169. if (cert.timestamp() >= old.timestamp())
  170. old = cert;
  171. }
  172. bool Network::isAllowed(const Address &peer) const
  173. {
  174. // Exceptions can occur if we do not yet have *our* configuration.
  175. try {
  176. Mutex::Lock _l(_lock);
  177. if (_isOpen)
  178. return true; // network is public
  179. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  180. if (pc == _membershipCertificates.end())
  181. return false; // no certificate on file
  182. return _myCertificate.agreesWith(pc->second); // is other cert valid against ours?
  183. } catch (std::exception &exc) {
  184. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  185. } catch ( ... ) {
  186. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  187. }
  188. return false; // default position on any failure
  189. }
  190. void Network::clean()
  191. {
  192. Mutex::Lock _l(_lock);
  193. uint64_t timestampMaxDelta = _myCertificate.timestampMaxDelta();
  194. if (_isOpen) {
  195. // Open (public) networks do not track certs or cert pushes at all.
  196. _membershipCertificates.clear();
  197. _lastPushedMembershipCertificate.clear();
  198. } else if (timestampMaxDelta) {
  199. // Clean certificates that are no longer valid from the cache.
  200. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  201. if (_myCertificate.agreesWith(c->second))
  202. ++c;
  203. else _membershipCertificates.erase(c++);
  204. }
  205. // Clean entries from the last pushed tracking map if they're so old as
  206. // to be no longer relevant.
  207. uint64_t forgetIfBefore = Utils::now() - (timestampMaxDelta * 3);
  208. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  209. if (lp->second < forgetIfBefore)
  210. _lastPushedMembershipCertificate.erase(lp++);
  211. else ++lp;
  212. }
  213. }
  214. }
  215. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  216. {
  217. if (!((Network *)arg)->isUp())
  218. return;
  219. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  220. if (_r->shutdownInProgress)
  221. return;
  222. try {
  223. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  224. } catch (std::exception &exc) {
  225. TRACE("unexpected exception handling local packet: %s",exc.what());
  226. } catch ( ... ) {
  227. TRACE("unexpected exception handling local packet");
  228. }
  229. }
  230. void Network::_pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  231. {
  232. uint64_t timestampMaxDelta = _myCertificate.timestampMaxDelta();
  233. if (!timestampMaxDelta)
  234. return; // still waiting on my own cert
  235. uint64_t &lastPushed = _lastPushedMembershipCertificate[peer];
  236. if ((force)||((now - lastPushed) > (timestampMaxDelta / 2))) {
  237. lastPushed = now;
  238. Packet outp(peer,_r->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  239. _myCertificate.serialize(outp);
  240. _r->sw->send(outp,true);
  241. }
  242. }
  243. void Network::_restoreState()
  244. {
  245. if (!_id)
  246. return; // sanity check
  247. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  248. std::string idstr(idString());
  249. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".conf");
  250. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".mcerts");
  251. // Read configuration file containing last config from netconf master
  252. {
  253. std::string confs;
  254. if (Utils::readFile(confPath.c_str(),confs)) {
  255. try {
  256. if (confs.length())
  257. setConfiguration(Config(confs),false);
  258. } catch ( ... ) {} // ignore invalid config on disk, we will re-request from netconf master
  259. } else {
  260. // If the conf file isn't present, "touch" it so we'll remember
  261. // the existence of this network.
  262. FILE *tmp = fopen(confPath.c_str(),"wb");
  263. if (tmp)
  264. fclose(tmp);
  265. }
  266. }
  267. // Read most recent multicast cert dump
  268. if ((!_isOpen)&&(Utils::fileExists(mcdbPath.c_str()))) {
  269. CertificateOfMembership com;
  270. Mutex::Lock _l(_lock);
  271. _membershipCertificates.clear();
  272. FILE *mcdb = fopen(mcdbPath.c_str(),"rb");
  273. if (mcdb) {
  274. try {
  275. char magic[6];
  276. if ((fread(magic,6,1,mcdb) == 1)&&(!memcmp("ZTMCD0",magic,6))) {
  277. for(;;) {
  278. long rlen = (long)fread(buf.data() + buf.size(),1,ZT_NETWORK_CERT_WRITE_BUF_SIZE - buf.size(),mcdb);
  279. if (rlen <= 0)
  280. break;
  281. buf.setSize(buf.size() + (unsigned int)rlen);
  282. unsigned int ptr = 0;
  283. while ((ptr < (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  284. ptr += com.deserialize(buf,ptr);
  285. if (com.issuedTo())
  286. _membershipCertificates[com.issuedTo()] = com;
  287. }
  288. if (ptr) {
  289. memmove(buf.data(),buf.data() + ptr,buf.size() - ptr);
  290. buf.setSize(buf.size() - ptr);
  291. }
  292. }
  293. fclose(mcdb);
  294. } else {
  295. fclose(mcdb);
  296. Utils::rm(mcdbPath);
  297. }
  298. } catch ( ... ) {
  299. // Membership cert dump file invalid. We'll re-learn them off the net.
  300. _membershipCertificates.clear();
  301. fclose(mcdb);
  302. Utils::rm(mcdbPath);
  303. }
  304. }
  305. }
  306. }
  307. void Network::_dumpMulticastCerts()
  308. {
  309. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  310. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  311. Mutex::Lock _l(_lock);
  312. if ((!_id)||(_isOpen)) {
  313. Utils::rm(mcdbPath);
  314. return;
  315. }
  316. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  317. if (!mcdb)
  318. return;
  319. if (fwrite("ZTMCD0",6,1,mcdb) != 1) {
  320. Utils::rm(mcdbPath);
  321. return;
  322. }
  323. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();++c) {
  324. try {
  325. c->second.serialize(buf);
  326. if (buf.size() >= (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2)) {
  327. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  328. fclose(mcdb);
  329. Utils::rm(mcdbPath);
  330. return;
  331. }
  332. buf.clear();
  333. }
  334. } catch ( ... ) {
  335. // Sanity check... no cert will ever be big enough to overflow buf
  336. fclose(mcdb);
  337. Utils::rm(mcdbPath);
  338. return;
  339. }
  340. }
  341. if (buf.size()) {
  342. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  343. fclose(mcdb);
  344. Utils::rm(mcdbPath);
  345. return;
  346. }
  347. }
  348. fclose(mcdb);
  349. }
  350. } // namespace ZeroTier