Network.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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->_multicastPrefixBits = ZT_DEFAULT_MULTICAST_PREFIX_BITS;
  85. nw->_multicastDepth = ZT_DEFAULT_MULTICAST_DEPTH;
  86. nw->_status = NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  87. memset(nw->_etWhitelist,0,sizeof(nw->_etWhitelist));
  88. nw->_id = id;
  89. nw->_lastConfigUpdate = 0;
  90. nw->_destroyOnDelete = false;
  91. if (nw->controller() == renv->identity.address()) // netconf masters can't really join networks
  92. throw std::runtime_error("cannot join a network for which I am the netconf master");
  93. nw->_restoreState();
  94. nw->_ready = true; // enable handling of Ethernet frames
  95. nw->requestConfiguration();
  96. return nw;
  97. }
  98. void Network::setConfiguration(const Network::Config &conf,bool saveToDisk)
  99. {
  100. Mutex::Lock _l(_lock);
  101. try {
  102. if (conf.networkId() == _id) { // sanity check
  103. _configuration = conf;
  104. // Grab some things from conf for faster lookup and memoize them
  105. _myCertificate = conf.certificateOfMembership();
  106. _mcRates = conf.multicastRates();
  107. _staticAddresses = conf.staticAddresses();
  108. _isOpen = conf.isOpen();
  109. _emulateArp = conf.emulateArp();
  110. _emulateNdp = conf.emulateNdp();
  111. _multicastPrefixBits = conf.multicastPrefixBits();
  112. _multicastDepth = conf.multicastDepth();
  113. _lastConfigUpdate = Utils::now();
  114. _tap->setIps(_staticAddresses);
  115. _tap->setDisplayName((std::string("ZeroTier One [") + conf.name() + "]").c_str());
  116. // Expand ethertype whitelist into fast-lookup bit field (more memoization)
  117. memset(_etWhitelist,0,sizeof(_etWhitelist));
  118. std::set<unsigned int> wl(conf.etherTypes());
  119. for(std::set<unsigned int>::const_iterator t(wl.begin());t!=wl.end();++t)
  120. _etWhitelist[*t / 8] |= (unsigned char)(1 << (*t % 8));
  121. _status = NETWORK_OK;
  122. if (saveToDisk) {
  123. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  124. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  125. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  126. }
  127. }
  128. }
  129. } catch ( ... ) {
  130. // If conf is invalid, reset everything
  131. _configuration = Config();
  132. _myCertificate = CertificateOfMembership();
  133. _mcRates = MulticastRates();
  134. _staticAddresses.clear();
  135. _isOpen = false;
  136. _emulateArp = false;
  137. _emulateNdp = false;
  138. _status = NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  139. _lastConfigUpdate = 0;
  140. LOG("unexpected exception handling config for network %.16llx, retrying fetch...",(unsigned long long)_id);
  141. }
  142. }
  143. void Network::requestConfiguration()
  144. {
  145. if (controller() == _r->identity.address()) {
  146. // netconf master cannot be a member of its own nets
  147. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  148. return;
  149. }
  150. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  151. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  152. outp.append((uint64_t)_id);
  153. outp.append((uint16_t)0); // no meta-data
  154. _r->sw->send(outp,true);
  155. }
  156. void Network::addMembershipCertificate(const CertificateOfMembership &cert)
  157. {
  158. Mutex::Lock _l(_lock);
  159. // We go ahead and accept certs provisionally even if _isOpen is true, since
  160. // that might be changed in short order if the user is fiddling in the UI.
  161. // These will be purged on clean() for open networks eventually.
  162. _membershipCertificates[cert.issuedTo()] = cert;
  163. }
  164. bool Network::isAllowed(const Address &peer) const
  165. {
  166. // Exceptions can occur if we do not yet have *our* configuration.
  167. try {
  168. Mutex::Lock _l(_lock);
  169. if (_isOpen)
  170. return true; // network is public
  171. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  172. if (pc == _membershipCertificates.end())
  173. return false; // no certificate on file
  174. return _myCertificate.agreesWith(pc->second); // is other cert valid against ours?
  175. } catch (std::exception &exc) {
  176. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  177. } catch ( ... ) {
  178. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  179. }
  180. return false; // default position on any failure
  181. }
  182. void Network::clean()
  183. {
  184. Mutex::Lock _l(_lock);
  185. uint64_t timestampMaxDelta = _myCertificate.timestampMaxDelta();
  186. if (_isOpen) {
  187. // Open (public) networks do not track certs or cert pushes at all.
  188. _membershipCertificates.clear();
  189. _lastPushedMembershipCertificate.clear();
  190. } else if (timestampMaxDelta) {
  191. // Clean certificates that are no longer valid from the cache.
  192. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  193. if (_myCertificate.agreesWith(c->second))
  194. ++c;
  195. else _membershipCertificates.erase(c++);
  196. }
  197. // Clean entries from the last pushed tracking map if they're so old as
  198. // to be no longer relevant.
  199. uint64_t forgetIfBefore = Utils::now() - (timestampMaxDelta * 3);
  200. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  201. if (lp->second < forgetIfBefore)
  202. _lastPushedMembershipCertificate.erase(lp++);
  203. else ++lp;
  204. }
  205. }
  206. }
  207. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  208. {
  209. if (!((Network *)arg)->isUp())
  210. return;
  211. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  212. if (_r->shutdownInProgress)
  213. return;
  214. try {
  215. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  216. } catch (std::exception &exc) {
  217. TRACE("unexpected exception handling local packet: %s",exc.what());
  218. } catch ( ... ) {
  219. TRACE("unexpected exception handling local packet");
  220. }
  221. }
  222. void Network::_pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  223. {
  224. uint64_t timestampMaxDelta = _myCertificate.timestampMaxDelta();
  225. if (!timestampMaxDelta)
  226. return; // still waiting on my own cert
  227. uint64_t &lastPushed = _lastPushedMembershipCertificate[peer];
  228. if ((force)||((now - lastPushed) > (timestampMaxDelta / 2))) {
  229. lastPushed = now;
  230. Packet outp(peer,_r->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  231. _myCertificate.serialize(outp);
  232. _r->sw->send(outp,true);
  233. }
  234. }
  235. void Network::_restoreState()
  236. {
  237. if (!_id)
  238. return; // sanity check
  239. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  240. std::string idstr(idString());
  241. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".conf");
  242. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".mcerts");
  243. // Read configuration file containing last config from netconf master
  244. {
  245. std::string confs;
  246. if (Utils::readFile(confPath.c_str(),confs)) {
  247. try {
  248. if (confs.length())
  249. setConfiguration(Config(confs),false);
  250. } catch ( ... ) {} // ignore invalid config on disk, we will re-request from netconf master
  251. } else {
  252. // If the conf file isn't present, "touch" it so we'll remember
  253. // the existence of this network.
  254. FILE *tmp = fopen(confPath.c_str(),"wb");
  255. if (tmp)
  256. fclose(tmp);
  257. }
  258. }
  259. // Read most recent multicast cert dump
  260. if ((!_isOpen)&&(Utils::fileExists(mcdbPath.c_str()))) {
  261. CertificateOfMembership com;
  262. Mutex::Lock _l(_lock);
  263. _membershipCertificates.clear();
  264. try {
  265. FILE *mcdb = fopen(mcdbPath.c_str(),"rb");
  266. if (mcdb) {
  267. for(;;) {
  268. long rlen = (long)fread(buf.data() + buf.size(),1,ZT_NETWORK_CERT_WRITE_BUF_SIZE - buf.size(),mcdb);
  269. if (rlen <= 0)
  270. break;
  271. buf.setSize(buf.size() + (unsigned int)rlen);
  272. unsigned int ptr = 0;
  273. while ((ptr < (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  274. ptr += com.deserialize(buf,ptr);
  275. if (com.issuedTo())
  276. _membershipCertificates[com.issuedTo()] = com;
  277. }
  278. if (ptr) {
  279. memmove(buf.data(),buf.data() + ptr,buf.size() - ptr);
  280. buf.setSize(buf.size() - ptr);
  281. }
  282. }
  283. }
  284. } catch ( ... ) {
  285. // Membership cert dump file invalid. We'll re-learn them off the net.
  286. _membershipCertificates.clear();
  287. Utils::rm(mcdbPath);
  288. }
  289. }
  290. }
  291. void Network::_dumpMulticastCerts()
  292. {
  293. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  294. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  295. Mutex::Lock _l(_lock);
  296. if ((!_id)||(_isOpen)) {
  297. Utils::rm(mcdbPath);
  298. return;
  299. }
  300. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  301. if (!mcdb)
  302. return;
  303. if (fwrite("ZTMCD0",6,1,mcdb) != 1) {
  304. Utils::rm(mcdbPath);
  305. return;
  306. }
  307. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();++c) {
  308. try {
  309. c->second.serialize(buf);
  310. if (buf.size() >= (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2)) {
  311. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  312. fclose(mcdb);
  313. Utils::rm(mcdbPath);
  314. return;
  315. }
  316. buf.clear();
  317. }
  318. } catch ( ... ) {
  319. // Sanity check... no cert will ever be big enough to overflow buf
  320. fclose(mcdb);
  321. Utils::rm(mcdbPath);
  322. return;
  323. }
  324. }
  325. if (buf.size()) {
  326. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  327. fclose(mcdb);
  328. Utils::rm(mcdbPath);
  329. return;
  330. }
  331. }
  332. fclose(mcdb);
  333. }
  334. } // namespace ZeroTier