Network.cpp 20 KB

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