Network.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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 "Constants.hpp"
  32. #include "Network.hpp"
  33. #include "RuntimeEnvironment.hpp"
  34. #include "NodeConfig.hpp"
  35. #include "Switch.hpp"
  36. #include "Packet.hpp"
  37. #include "Buffer.hpp"
  38. #include "EthernetTap.hpp"
  39. #include "EthernetTapFactory.hpp"
  40. #include "RoutingTable.hpp"
  41. #define ZT_NETWORK_CERT_WRITE_BUF_SIZE 131072
  42. namespace ZeroTier {
  43. const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xff),0);
  44. const char *Network::statusString(const Status s)
  45. throw()
  46. {
  47. switch(s) {
  48. case NETWORK_INITIALIZING: return "INITIALIZING";
  49. case NETWORK_WAITING_FOR_FIRST_AUTOCONF: return "WAITING_FOR_FIRST_AUTOCONF";
  50. case NETWORK_OK: return "OK";
  51. case NETWORK_ACCESS_DENIED: return "ACCESS_DENIED";
  52. case NETWORK_NOT_FOUND: return "NOT_FOUND";
  53. case NETWORK_INITIALIZATION_FAILED: return "INITIALIZATION_FAILED";
  54. case NETWORK_NO_MORE_DEVICES: return "NO_MORE_DEVICES";
  55. }
  56. return "(invalid)";
  57. }
  58. Network::~Network()
  59. {
  60. _lock.lock();
  61. if ((_setupThread)&&(!_destroyed)) {
  62. _lock.unlock();
  63. Thread::join(_setupThread);
  64. } else _lock.unlock();
  65. {
  66. Mutex::Lock _l(_lock);
  67. if (_tap)
  68. RR->tapFactory->close(_tap,_destroyed);
  69. }
  70. if (_destroyed) {
  71. Utils::rm(std::string(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf"));
  72. Utils::rm(std::string(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts"));
  73. } else {
  74. clean();
  75. _dumpMembershipCerts();
  76. }
  77. }
  78. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,NodeConfig *nc,uint64_t id)
  79. {
  80. SharedPtr<Network> nw(new Network());
  81. nw->_id = id;
  82. nw->_nc = nc;
  83. nw->_mac.fromAddress(renv->identity.address(),id);
  84. nw->RR = renv;
  85. nw->_tap = (EthernetTap *)0;
  86. nw->_enabled = true;
  87. nw->_lastConfigUpdate = 0;
  88. nw->_destroyed = false;
  89. nw->_netconfFailure = NETCONF_FAILURE_NONE;
  90. if (nw->controller() == renv->identity.address()) // TODO: fix Switch to allow packets to self
  91. throw std::runtime_error("cannot join a network for which I am the netconf master");
  92. try {
  93. nw->_restoreState();
  94. nw->requestConfiguration();
  95. } catch ( ... ) {
  96. nw->_lastConfigUpdate = 0; // call requestConfiguration() again
  97. }
  98. return nw;
  99. }
  100. bool Network::updateMulticastGroups()
  101. {
  102. Mutex::Lock _l(_lock);
  103. EthernetTap *t = _tap;
  104. if (t) {
  105. // Grab current groups from the local tap
  106. bool updated = t->updateMulticastGroups(_myMulticastGroups);
  107. // Merge in learned groups from any hosts bridged in behind us
  108. for(std::map<MulticastGroup,uint64_t>::const_iterator mg(_multicastGroupsBehindMe.begin());mg!=_multicastGroupsBehindMe.end();++mg)
  109. _myMulticastGroups.insert(mg->first);
  110. // Add or remove BROADCAST group based on broadcast enabled netconf flag
  111. if ((_config)&&(_config->enableBroadcast())) {
  112. if (_myMulticastGroups.count(BROADCAST))
  113. return updated;
  114. else {
  115. _myMulticastGroups.insert(BROADCAST);
  116. return true;
  117. }
  118. } else {
  119. if (_myMulticastGroups.count(BROADCAST)) {
  120. _myMulticastGroups.erase(BROADCAST);
  121. return true;
  122. } else return updated;
  123. }
  124. } else return false;
  125. }
  126. bool Network::applyConfiguration(const SharedPtr<NetworkConfig> &conf)
  127. {
  128. Mutex::Lock _l(_lock);
  129. if (_destroyed)
  130. return false;
  131. try {
  132. if ((conf->networkId() == _id)&&(conf->issuedTo() == RR->identity.address())) {
  133. std::set<InetAddress> oldStaticIps;
  134. if (_config)
  135. oldStaticIps = _config->staticIps();
  136. _config = conf;
  137. _lastConfigUpdate = Utils::now();
  138. _netconfFailure = NETCONF_FAILURE_NONE;
  139. EthernetTap *t = _tap;
  140. if (t) {
  141. char fname[1024];
  142. _mkNetworkFriendlyName(fname,sizeof(fname));
  143. t->setFriendlyName(fname);
  144. // Remove previously configured static IPs that are gone
  145. for(std::set<InetAddress>::const_iterator oldip(oldStaticIps.begin());oldip!=oldStaticIps.end();++oldip) {
  146. if (!_config->staticIps().count(*oldip))
  147. t->removeIP(*oldip);
  148. }
  149. // Add new static IPs that were not in previous config
  150. for(std::set<InetAddress>::const_iterator newip(_config->staticIps().begin());newip!=_config->staticIps().end();++newip) {
  151. if (!oldStaticIps.count(*newip))
  152. t->addIP(*newip);
  153. }
  154. #ifdef __APPLE__
  155. // Make sure there's an IPv6 link-local address on Macs if IPv6 is enabled
  156. // Other OSes don't need this -- Mac seems not to want to auto-assign
  157. // This might go away once we integrate properly w/Mac network setup stuff.
  158. if (_config->permitsEtherType(ZT_ETHERTYPE_IPV6)) {
  159. bool haveV6LinkLocal = false;
  160. std::set<InetAddress> ips(t->ips());
  161. for(std::set<InetAddress>::const_iterator i(ips.begin());i!=ips.end();++i) {
  162. if ((i->isV6())&&(i->isLinkLocal())) {
  163. haveV6LinkLocal = true;
  164. break;
  165. }
  166. }
  167. if (!haveV6LinkLocal)
  168. t->addIP(InetAddress::makeIpv6LinkLocal(_mac));
  169. }
  170. #endif // __APPLE__
  171. // ... IPs that were never controlled by static assignment are left
  172. // alone, as these may be DHCP or user-configured.
  173. } else {
  174. if (!_setupThread)
  175. _setupThread = Thread::start<Network>(this);
  176. }
  177. return true;
  178. } else {
  179. LOG("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  180. }
  181. } catch (std::exception &exc) {
  182. LOG("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  183. } catch ( ... ) {
  184. LOG("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  185. }
  186. return false;
  187. }
  188. bool Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  189. {
  190. try {
  191. SharedPtr<NetworkConfig> newConfig(new NetworkConfig(conf)); // throws if invalid
  192. if (applyConfiguration(newConfig)) {
  193. if (saveToDisk) {
  194. std::string confPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  195. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  196. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  197. } else {
  198. Utils::lockDownFile(confPath.c_str(),false);
  199. }
  200. }
  201. return true;
  202. }
  203. } catch ( ... ) {
  204. LOG("ignored invalid configuration for network %.16llx (dictionary decode failed)",(unsigned long long)_id);
  205. }
  206. return false;
  207. }
  208. void Network::requestConfiguration()
  209. {
  210. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, no netconf master
  211. return;
  212. if (controller() == RR->identity.address()) {
  213. // netconf master cannot be a member of its own nets
  214. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  215. return;
  216. }
  217. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  218. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  219. outp.append((uint64_t)_id);
  220. outp.append((uint16_t)0); // no meta-data
  221. RR->sw->send(outp,true);
  222. }
  223. void Network::addMembershipCertificate(const CertificateOfMembership &cert,bool forceAccept)
  224. {
  225. if (!cert) // sanity check
  226. return;
  227. if (!forceAccept) {
  228. if (cert.signedBy() != controller())
  229. return;
  230. SharedPtr<Peer> signer(RR->topology->getPeer(cert.signedBy()));
  231. if (!signer)
  232. return; // we should already have done a WHOIS on this peer, since this is our netconf master
  233. if (!cert.verify(signer->identity()))
  234. return;
  235. }
  236. Mutex::Lock _l(_lock);
  237. // We go ahead and accept certs provisionally even if _isOpen is true, since
  238. // that might be changed in short order if the user is fiddling in the UI.
  239. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  240. if (cert.timestamp() >= old.timestamp()) {
  241. //TRACE("got new certificate for %s on network %.16llx",cert.issuedTo().toString().c_str(),cert.networkId());
  242. old = cert;
  243. }
  244. }
  245. bool Network::isAllowed(const Address &peer) const
  246. {
  247. try {
  248. Mutex::Lock _l(_lock);
  249. if (!_config)
  250. return false;
  251. if (_config->isPublic())
  252. return true;
  253. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  254. if (pc == _membershipCertificates.end())
  255. return false; // no certificate on file
  256. return _config->com().agreesWith(pc->second); // is other cert valid against ours?
  257. } catch (std::exception &exc) {
  258. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  259. } catch ( ... ) {
  260. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  261. }
  262. return false; // default position on any failure
  263. }
  264. void Network::clean()
  265. {
  266. uint64_t now = Utils::now();
  267. Mutex::Lock _l(_lock);
  268. if (_destroyed)
  269. return;
  270. if ((_config)&&(_config->isPublic())) {
  271. // Open (public) networks do not track certs or cert pushes at all.
  272. _membershipCertificates.clear();
  273. _lastPushedMembershipCertificate.clear();
  274. } else if (_config) {
  275. // Clean certificates that are no longer valid from the cache.
  276. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  277. if (_config->com().agreesWith(c->second))
  278. ++c;
  279. else _membershipCertificates.erase(c++);
  280. }
  281. // Clean entries from the last pushed tracking map if they're so old as
  282. // to be no longer relevant.
  283. uint64_t forgetIfBefore = now - (_config->com().timestampMaxDelta() * 3ULL);
  284. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  285. if (lp->second < forgetIfBefore)
  286. _lastPushedMembershipCertificate.erase(lp++);
  287. else ++lp;
  288. }
  289. }
  290. // Clean learned multicast groups if we haven't heard from them in a while
  291. for(std::map<MulticastGroup,uint64_t>::iterator mg(_multicastGroupsBehindMe.begin());mg!=_multicastGroupsBehindMe.end();) {
  292. if ((now - mg->second) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  293. _multicastGroupsBehindMe.erase(mg++);
  294. else ++mg;
  295. }
  296. }
  297. Network::Status Network::status() const
  298. {
  299. Mutex::Lock _l(_lock);
  300. switch(_netconfFailure) {
  301. case NETCONF_FAILURE_ACCESS_DENIED:
  302. return NETWORK_ACCESS_DENIED;
  303. case NETCONF_FAILURE_NOT_FOUND:
  304. return NETWORK_NOT_FOUND;
  305. case NETCONF_FAILURE_NONE:
  306. return ((_lastConfigUpdate > 0) ? ((_tap) ? NETWORK_OK : NETWORK_INITIALIZING) : NETWORK_WAITING_FOR_FIRST_AUTOCONF);
  307. //case NETCONF_FAILURE_INIT_FAILED:
  308. default:
  309. return NETWORK_INITIALIZATION_FAILED;
  310. }
  311. }
  312. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  313. {
  314. Mutex::Lock _l(_lock);
  315. _remoteBridgeRoutes[mac] = addr;
  316. // If _remoteBridgeRoutes exceeds sanity limit, trim worst offenders until below -- denial of service circuit breaker
  317. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  318. std::map<Address,unsigned long> counts;
  319. Address maxAddr;
  320. unsigned long maxCount = 0;
  321. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();++br) {
  322. unsigned long c = ++counts[br->second];
  323. if (c > maxCount) {
  324. maxCount = c;
  325. maxAddr = br->second;
  326. }
  327. }
  328. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();) {
  329. if (br->second == maxAddr)
  330. _remoteBridgeRoutes.erase(br++);
  331. else ++br;
  332. }
  333. }
  334. }
  335. void Network::setEnabled(bool enabled)
  336. {
  337. Mutex::Lock _l(_lock);
  338. _enabled = enabled;
  339. if (_tap)
  340. _tap->setEnabled(enabled);
  341. }
  342. void Network::destroy()
  343. {
  344. Mutex::Lock _l(_lock);
  345. _enabled = false;
  346. _destroyed = true;
  347. if (_setupThread)
  348. Thread::join(_setupThread);
  349. _setupThread = Thread();
  350. if (_tap)
  351. RR->tapFactory->close(_tap,true);
  352. _tap = (EthernetTap *)0;
  353. }
  354. // Ethernet tap creation thread -- required on some platforms where tap
  355. // creation may be time consuming (e.g. Windows). Thread exits after tap
  356. // device setup.
  357. void Network::threadMain()
  358. throw()
  359. {
  360. char fname[1024],lcentry[128];
  361. Utils::snprintf(lcentry,sizeof(lcentry),"_dev_for_%.16llx",(unsigned long long)_id);
  362. EthernetTap *t = (EthernetTap *)0;
  363. try {
  364. std::string desiredDevice(_nc->getLocalConfig(lcentry));
  365. _mkNetworkFriendlyName(fname,sizeof(fname));
  366. t = RR->tapFactory->open(_mac,ZT_IF_MTU,ZT_DEFAULT_IF_METRIC,_id,(desiredDevice.length() > 0) ? desiredDevice.c_str() : (const char *)0,fname,_CBhandleTapData,this);
  367. std::string dn(t->deviceName());
  368. if ((dn.length())&&(dn != desiredDevice))
  369. _nc->putLocalConfig(lcentry,dn);
  370. } catch (std::exception &exc) {
  371. delete t;
  372. t = (EthernetTap *)0;
  373. LOG("network %.16llx failed to initialize: %s",_id,exc.what());
  374. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  375. } catch ( ... ) {
  376. delete t;
  377. t = (EthernetTap *)0;
  378. LOG("network %.16llx failed to initialize: unknown error",_id);
  379. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  380. }
  381. {
  382. Mutex::Lock _l(_lock);
  383. if (_tap) // the tap creation thread can technically be re-launched, though this isn't done right now
  384. RR->tapFactory->close(_tap,false);
  385. _tap = t;
  386. if (t) {
  387. if (_config) {
  388. for(std::set<InetAddress>::const_iterator newip(_config->staticIps().begin());newip!=_config->staticIps().end();++newip)
  389. t->addIP(*newip);
  390. }
  391. t->setEnabled(_enabled);
  392. }
  393. }
  394. }
  395. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  396. {
  397. if ((!((Network *)arg)->_enabled)||(((Network *)arg)->status() != NETWORK_OK))
  398. return;
  399. const RuntimeEnvironment *RR = ((Network *)arg)->RR;
  400. if (RR->shutdownInProgress)
  401. return;
  402. try {
  403. RR->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  404. } catch (std::exception &exc) {
  405. TRACE("unexpected exception handling local packet: %s",exc.what());
  406. } catch ( ... ) {
  407. TRACE("unexpected exception handling local packet");
  408. }
  409. }
  410. void Network::_pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  411. {
  412. // assumes _lock is locked and _config is not null
  413. uint64_t pushTimeout = _config->com().timestampMaxDelta() / 2;
  414. // Zero means we're still waiting on our own cert
  415. if (!pushTimeout)
  416. return;
  417. // Give a 1s margin around +/- 1/2 max delta to account for latency
  418. if (pushTimeout > 1000)
  419. pushTimeout -= 1000;
  420. uint64_t &lastPushed = _lastPushedMembershipCertificate[peer];
  421. if ((force)||((now - lastPushed) > pushTimeout)) {
  422. lastPushed = now;
  423. TRACE("pushing membership cert for %.16llx to %s",(unsigned long long)_id,peer.toString().c_str());
  424. Packet outp(peer,RR->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  425. _config->com().serialize(outp);
  426. RR->sw->send(outp,true);
  427. }
  428. }
  429. void Network::_restoreState()
  430. {
  431. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  432. std::string idstr(idString());
  433. std::string confPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".conf");
  434. std::string mcdbPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".mcerts");
  435. if (_id == ZT_TEST_NETWORK_ID) {
  436. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  437. // "Touch" path to this ID to remember test network membership
  438. FILE *tmp = fopen(confPath.c_str(),"w");
  439. if (tmp) fclose(tmp);
  440. } else {
  441. // Read configuration file containing last config from netconf master
  442. {
  443. std::string confs;
  444. if (Utils::readFile(confPath.c_str(),confs)) {
  445. try {
  446. if (confs.length())
  447. setConfiguration(Dictionary(confs),false);
  448. } catch ( ... ) {} // ignore invalid config on disk, we will re-request from netconf master
  449. } else {
  450. // "Touch" path to remember membership in lieu of real config from netconf master
  451. FILE *tmp = fopen(confPath.c_str(),"w");
  452. if (tmp) fclose(tmp);
  453. }
  454. }
  455. }
  456. { // Read most recent membership cert dump if there is one
  457. Mutex::Lock _l(_lock);
  458. if ((_config)&&(!_config->isPublic())&&(Utils::fileExists(mcdbPath.c_str()))) {
  459. CertificateOfMembership com;
  460. _membershipCertificates.clear();
  461. FILE *mcdb = fopen(mcdbPath.c_str(),"rb");
  462. if (mcdb) {
  463. try {
  464. char magic[6];
  465. if ((fread(magic,6,1,mcdb) == 1)&&(!memcmp("ZTMCD0",magic,6))) {
  466. long rlen = 0;
  467. do {
  468. long rlen = (long)fread(const_cast<char *>(static_cast<const char *>(buf.data())) + buf.size(),1,ZT_NETWORK_CERT_WRITE_BUF_SIZE - buf.size(),mcdb);
  469. if (rlen < 0) rlen = 0;
  470. buf.setSize(buf.size() + (unsigned int)rlen);
  471. unsigned int ptr = 0;
  472. while ((ptr < (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  473. ptr += com.deserialize(buf,ptr);
  474. if (com.issuedTo())
  475. _membershipCertificates[com.issuedTo()] = com;
  476. }
  477. buf.behead(ptr);
  478. } while (rlen > 0);
  479. fclose(mcdb);
  480. } else {
  481. fclose(mcdb);
  482. Utils::rm(mcdbPath);
  483. }
  484. } catch ( ... ) {
  485. // Membership cert dump file invalid. We'll re-learn them off the net.
  486. _membershipCertificates.clear();
  487. fclose(mcdb);
  488. Utils::rm(mcdbPath);
  489. }
  490. }
  491. }
  492. }
  493. }
  494. void Network::_dumpMembershipCerts()
  495. {
  496. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  497. std::string mcdbPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  498. Mutex::Lock _l(_lock);
  499. if (!_config)
  500. return;
  501. if ((!_id)||(_config->isPublic())) {
  502. Utils::rm(mcdbPath);
  503. return;
  504. }
  505. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  506. if (!mcdb)
  507. return;
  508. if (fwrite("ZTMCD0",6,1,mcdb) != 1) {
  509. fclose(mcdb);
  510. Utils::rm(mcdbPath);
  511. return;
  512. }
  513. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();++c) {
  514. try {
  515. c->second.serialize(buf);
  516. if (buf.size() >= (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2)) {
  517. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  518. fclose(mcdb);
  519. Utils::rm(mcdbPath);
  520. return;
  521. }
  522. buf.clear();
  523. }
  524. } catch ( ... ) {
  525. // Sanity check... no cert will ever be big enough to overflow buf
  526. fclose(mcdb);
  527. Utils::rm(mcdbPath);
  528. return;
  529. }
  530. }
  531. if (buf.size()) {
  532. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  533. fclose(mcdb);
  534. Utils::rm(mcdbPath);
  535. return;
  536. }
  537. }
  538. fclose(mcdb);
  539. Utils::lockDownFile(mcdbPath.c_str(),false);
  540. }
  541. } // namespace ZeroTier