Network.cpp 18 KB

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