Network.cpp 20 KB

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