Network.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  163. if (cert.timestamp() >= old.timestamp())
  164. old = cert;
  165. }
  166. bool Network::isAllowed(const Address &peer) const
  167. {
  168. // Exceptions can occur if we do not yet have *our* configuration.
  169. try {
  170. Mutex::Lock _l(_lock);
  171. if (_isOpen)
  172. return true; // network is public
  173. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  174. if (pc == _membershipCertificates.end())
  175. return false; // no certificate on file
  176. return _myCertificate.agreesWith(pc->second); // is other cert valid against ours?
  177. } catch (std::exception &exc) {
  178. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  179. } catch ( ... ) {
  180. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  181. }
  182. return false; // default position on any failure
  183. }
  184. void Network::clean()
  185. {
  186. Mutex::Lock _l(_lock);
  187. uint64_t timestampMaxDelta = _myCertificate.timestampMaxDelta();
  188. if (_isOpen) {
  189. // Open (public) networks do not track certs or cert pushes at all.
  190. _membershipCertificates.clear();
  191. _lastPushedMembershipCertificate.clear();
  192. } else if (timestampMaxDelta) {
  193. // Clean certificates that are no longer valid from the cache.
  194. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  195. if (_myCertificate.agreesWith(c->second))
  196. ++c;
  197. else _membershipCertificates.erase(c++);
  198. }
  199. // Clean entries from the last pushed tracking map if they're so old as
  200. // to be no longer relevant.
  201. uint64_t forgetIfBefore = Utils::now() - (timestampMaxDelta * 3);
  202. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  203. if (lp->second < forgetIfBefore)
  204. _lastPushedMembershipCertificate.erase(lp++);
  205. else ++lp;
  206. }
  207. }
  208. }
  209. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  210. {
  211. if (!((Network *)arg)->isUp())
  212. return;
  213. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  214. if (_r->shutdownInProgress)
  215. return;
  216. try {
  217. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  218. } catch (std::exception &exc) {
  219. TRACE("unexpected exception handling local packet: %s",exc.what());
  220. } catch ( ... ) {
  221. TRACE("unexpected exception handling local packet");
  222. }
  223. }
  224. void Network::_pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  225. {
  226. uint64_t timestampMaxDelta = _myCertificate.timestampMaxDelta();
  227. if (!timestampMaxDelta)
  228. return; // still waiting on my own cert
  229. uint64_t &lastPushed = _lastPushedMembershipCertificate[peer];
  230. if ((force)||((now - lastPushed) > (timestampMaxDelta / 2))) {
  231. lastPushed = now;
  232. Packet outp(peer,_r->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  233. _myCertificate.serialize(outp);
  234. _r->sw->send(outp,true);
  235. }
  236. }
  237. void Network::_restoreState()
  238. {
  239. if (!_id)
  240. return; // sanity check
  241. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  242. std::string idstr(idString());
  243. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".conf");
  244. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".mcerts");
  245. // Read configuration file containing last config from netconf master
  246. {
  247. std::string confs;
  248. if (Utils::readFile(confPath.c_str(),confs)) {
  249. try {
  250. if (confs.length())
  251. setConfiguration(Config(confs),false);
  252. } catch ( ... ) {} // ignore invalid config on disk, we will re-request from netconf master
  253. } else {
  254. // If the conf file isn't present, "touch" it so we'll remember
  255. // the existence of this network.
  256. FILE *tmp = fopen(confPath.c_str(),"wb");
  257. if (tmp)
  258. fclose(tmp);
  259. }
  260. }
  261. // Read most recent multicast cert dump
  262. if ((!_isOpen)&&(Utils::fileExists(mcdbPath.c_str()))) {
  263. CertificateOfMembership com;
  264. Mutex::Lock _l(_lock);
  265. _membershipCertificates.clear();
  266. FILE *mcdb = fopen(mcdbPath.c_str(),"rb");
  267. if (mcdb) {
  268. try {
  269. char magic[6];
  270. if ((fread(magic,6,1,mcdb) == 1)&&(!memcmp("ZTMCD0",magic,6))) {
  271. for(;;) {
  272. long rlen = (long)fread(buf.data() + buf.size(),1,ZT_NETWORK_CERT_WRITE_BUF_SIZE - buf.size(),mcdb);
  273. if (rlen <= 0)
  274. break;
  275. buf.setSize(buf.size() + (unsigned int)rlen);
  276. unsigned int ptr = 0;
  277. while ((ptr < (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  278. ptr += com.deserialize(buf,ptr);
  279. if (com.issuedTo())
  280. _membershipCertificates[com.issuedTo()] = com;
  281. }
  282. if (ptr) {
  283. memmove(buf.data(),buf.data() + ptr,buf.size() - ptr);
  284. buf.setSize(buf.size() - ptr);
  285. }
  286. }
  287. fclose(mcdb);
  288. } else {
  289. fclose(mcdb);
  290. Utils::rm(mcdbPath);
  291. }
  292. } catch ( ... ) {
  293. // Membership cert dump file invalid. We'll re-learn them off the net.
  294. _membershipCertificates.clear();
  295. fclose(mcdb);
  296. Utils::rm(mcdbPath);
  297. }
  298. }
  299. }
  300. }
  301. void Network::_dumpMulticastCerts()
  302. {
  303. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  304. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  305. Mutex::Lock _l(_lock);
  306. if ((!_id)||(_isOpen)) {
  307. Utils::rm(mcdbPath);
  308. return;
  309. }
  310. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  311. if (!mcdb)
  312. return;
  313. if (fwrite("ZTMCD0",6,1,mcdb) != 1) {
  314. Utils::rm(mcdbPath);
  315. return;
  316. }
  317. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();++c) {
  318. try {
  319. c->second.serialize(buf);
  320. if (buf.size() >= (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2)) {
  321. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  322. fclose(mcdb);
  323. Utils::rm(mcdbPath);
  324. return;
  325. }
  326. buf.clear();
  327. }
  328. } catch ( ... ) {
  329. // Sanity check... no cert will ever be big enough to overflow buf
  330. fclose(mcdb);
  331. Utils::rm(mcdbPath);
  332. return;
  333. }
  334. }
  335. if (buf.size()) {
  336. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  337. fclose(mcdb);
  338. Utils::rm(mcdbPath);
  339. return;
  340. }
  341. }
  342. fclose(mcdb);
  343. }
  344. } // namespace ZeroTier