Network.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2015 ZeroTier Networks
  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. int Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  233. {
  234. try {
  235. SharedPtr<NetworkConfig> newConfig(new NetworkConfig(conf)); // throws if invalid
  236. {
  237. Mutex::Lock _l(_lock);
  238. if ((_config)&&(*_config == *newConfig))
  239. return 1; // OK but duplicate
  240. }
  241. if (applyConfiguration(newConfig)) {
  242. if (saveToDisk) {
  243. std::string confPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  244. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  245. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  246. } else {
  247. Utils::lockDownFile(confPath.c_str(),false);
  248. }
  249. }
  250. return 2; // OK and configuration has changed
  251. }
  252. } catch ( ... ) {
  253. LOG("ignored invalid configuration for network %.16llx (dictionary decode failed)",(unsigned long long)_id);
  254. }
  255. return 0;
  256. }
  257. void Network::requestConfiguration()
  258. {
  259. if (_id == ZT_TEST_NETWORK_ID) // pseudo-network-ID, no netconf master
  260. return;
  261. if (controller() == RR->identity.address()) {
  262. // netconf master cannot be a member of its own nets
  263. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  264. return;
  265. }
  266. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  267. Packet outp(controller(),RR->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  268. outp.append((uint64_t)_id);
  269. outp.append((uint16_t)0); // no meta-data
  270. RR->sw->send(outp,true);
  271. }
  272. void Network::addMembershipCertificate(const CertificateOfMembership &cert,bool forceAccept)
  273. {
  274. if (!cert) // sanity check
  275. return;
  276. Mutex::Lock _l(_lock);
  277. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  278. // Nothing to do if the cert hasn't changed -- we get duplicates due to zealous cert pushing
  279. if (old == cert)
  280. return;
  281. // Check signature, log and return if cert is invalid
  282. if (!forceAccept) {
  283. if (cert.signedBy() != controller()) {
  284. 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());
  285. return;
  286. }
  287. SharedPtr<Peer> signer(RR->topology->getPeer(cert.signedBy()));
  288. if (!signer) {
  289. // This would be rather odd, since this is our netconf master... could happen
  290. // if we get packets before we've gotten config.
  291. RR->sw->requestWhois(cert.signedBy());
  292. return;
  293. }
  294. if (!cert.verify(signer->identity())) {
  295. LOG("rejected network membership certificate for %.16llx signed by %s: signature check failed",(unsigned long long)_id,cert.signedBy().toString().c_str());
  296. return;
  297. }
  298. }
  299. // If we made it past authentication, update cert
  300. if (cert.timestamp() >= old.timestamp())
  301. old = cert;
  302. }
  303. bool Network::peerNeedsOurMembershipCertificate(const Address &to,uint64_t now)
  304. {
  305. Mutex::Lock _l(_lock);
  306. if ((_config)&&(!_config->isPublic())&&(_config->com())) {
  307. uint64_t pushInterval = _config->com().timestampMaxDelta() / 2;
  308. if (pushInterval) {
  309. // Give a 1s margin around +/- 1/2 max delta to account for network latency
  310. if (pushInterval > 1000)
  311. pushInterval -= 1000;
  312. uint64_t &lastPushed = _lastPushedMembershipCertificate[to];
  313. if ((now - lastPushed) > pushInterval) {
  314. lastPushed = now;
  315. return true;
  316. }
  317. }
  318. }
  319. return false;
  320. }
  321. bool Network::isAllowed(const Address &peer) const
  322. {
  323. try {
  324. Mutex::Lock _l(_lock);
  325. if (!_config)
  326. return false;
  327. if (_config->isPublic())
  328. return true;
  329. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  330. if (pc == _membershipCertificates.end())
  331. return false; // no certificate on file
  332. return _config->com().agreesWith(pc->second); // is other cert valid against ours?
  333. } catch (std::exception &exc) {
  334. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  335. } catch ( ... ) {
  336. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  337. }
  338. return false; // default position on any failure
  339. }
  340. void Network::clean()
  341. {
  342. uint64_t now = Utils::now();
  343. Mutex::Lock _l(_lock);
  344. if (_destroyed)
  345. return;
  346. if ((_config)&&(_config->isPublic())) {
  347. // Open (public) networks do not track certs or cert pushes at all.
  348. _membershipCertificates.clear();
  349. _lastPushedMembershipCertificate.clear();
  350. } else if (_config) {
  351. // Clean certificates that are no longer valid from the cache.
  352. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  353. if (_config->com().agreesWith(c->second))
  354. ++c;
  355. else _membershipCertificates.erase(c++);
  356. }
  357. // Clean entries from the last pushed tracking map if they're so old as
  358. // to be no longer relevant.
  359. uint64_t forgetIfBefore = now - (_config->com().timestampMaxDelta() * 3ULL);
  360. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  361. if (lp->second < forgetIfBefore)
  362. _lastPushedMembershipCertificate.erase(lp++);
  363. else ++lp;
  364. }
  365. }
  366. // Clean learned multicast groups if we haven't heard from them in a while
  367. for(std::map<MulticastGroup,uint64_t>::iterator mg(_multicastGroupsBehindMe.begin());mg!=_multicastGroupsBehindMe.end();) {
  368. if ((now - mg->second) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  369. _multicastGroupsBehindMe.erase(mg++);
  370. else ++mg;
  371. }
  372. }
  373. Network::Status Network::status() const
  374. {
  375. Mutex::Lock _l(_lock);
  376. switch(_netconfFailure) {
  377. case NETCONF_FAILURE_ACCESS_DENIED:
  378. return NETWORK_ACCESS_DENIED;
  379. case NETCONF_FAILURE_NOT_FOUND:
  380. return NETWORK_NOT_FOUND;
  381. case NETCONF_FAILURE_NONE:
  382. return ((_lastConfigUpdate > 0) ? ((_tap) ? NETWORK_OK : NETWORK_INITIALIZING) : NETWORK_WAITING_FOR_FIRST_AUTOCONF);
  383. //case NETCONF_FAILURE_INIT_FAILED:
  384. default:
  385. return NETWORK_INITIALIZATION_FAILED;
  386. }
  387. }
  388. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  389. {
  390. Mutex::Lock _l(_lock);
  391. _remoteBridgeRoutes[mac] = addr;
  392. // If _remoteBridgeRoutes exceeds sanity limit, trim worst offenders until below -- denial of service circuit breaker
  393. while (_remoteBridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  394. std::map<Address,unsigned long> counts;
  395. Address maxAddr;
  396. unsigned long maxCount = 0;
  397. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();++br) {
  398. unsigned long c = ++counts[br->second];
  399. if (c > maxCount) {
  400. maxCount = c;
  401. maxAddr = br->second;
  402. }
  403. }
  404. for(std::map<MAC,Address>::iterator br(_remoteBridgeRoutes.begin());br!=_remoteBridgeRoutes.end();) {
  405. if (br->second == maxAddr)
  406. _remoteBridgeRoutes.erase(br++);
  407. else ++br;
  408. }
  409. }
  410. }
  411. void Network::setEnabled(bool enabled)
  412. {
  413. Mutex::Lock _l(_lock);
  414. _enabled = enabled;
  415. if (_tap)
  416. _tap->setEnabled(enabled);
  417. }
  418. void Network::destroy()
  419. {
  420. Mutex::Lock _l(_lock);
  421. _enabled = false;
  422. _destroyed = true;
  423. if (_setupThread)
  424. Thread::join(_setupThread);
  425. _setupThread = Thread();
  426. if (_tap)
  427. RR->tapFactory->close(_tap,true);
  428. _tap = (EthernetTap *)0;
  429. }
  430. // Ethernet tap creation thread -- required on some platforms where tap
  431. // creation may be time consuming (e.g. Windows). Thread exits after tap
  432. // device setup.
  433. void Network::threadMain()
  434. throw()
  435. {
  436. char fname[1024],lcentry[128];
  437. Utils::snprintf(lcentry,sizeof(lcentry),"_dev_for_%.16llx",(unsigned long long)_id);
  438. EthernetTap *t = (EthernetTap *)0;
  439. try {
  440. std::string desiredDevice(_nc->getLocalConfig(lcentry));
  441. _mkNetworkFriendlyName(fname,sizeof(fname));
  442. 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);
  443. std::string dn(t->deviceName());
  444. if ((dn.length())&&(dn != desiredDevice))
  445. _nc->putLocalConfig(lcentry,dn);
  446. } catch (std::exception &exc) {
  447. delete t;
  448. t = (EthernetTap *)0;
  449. LOG("network %.16llx failed to initialize: %s",_id,exc.what());
  450. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  451. } catch ( ... ) {
  452. delete t;
  453. t = (EthernetTap *)0;
  454. LOG("network %.16llx failed to initialize: unknown error",_id);
  455. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  456. }
  457. {
  458. Mutex::Lock _l(_lock);
  459. if (_tap) // the tap creation thread can technically be re-launched, though this isn't done right now
  460. RR->tapFactory->close(_tap,false);
  461. _tap = t;
  462. if (t) {
  463. if (_config) {
  464. for(std::vector<InetAddress>::const_iterator newip(_config->staticIps().begin());newip!=_config->staticIps().end();++newip)
  465. t->addIP(*newip);
  466. }
  467. t->setEnabled(_enabled);
  468. }
  469. }
  470. rescanMulticastGroups();
  471. }
  472. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  473. {
  474. SharedPtr<Network> network((Network *)arg,true);
  475. if ((!network)||(!network->_enabled)||(network->status() != NETWORK_OK))
  476. return;
  477. try {
  478. network->RR->sw->onLocalEthernet(network,from,to,etherType,data);
  479. } catch (std::exception &exc) {
  480. TRACE("unexpected exception handling local packet: %s",exc.what());
  481. } catch ( ... ) {
  482. TRACE("unexpected exception handling local packet");
  483. }
  484. }
  485. void Network::_restoreState()
  486. {
  487. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  488. std::string idstr(idString());
  489. std::string confPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".conf");
  490. std::string mcdbPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".mcerts");
  491. if (_id == ZT_TEST_NETWORK_ID) {
  492. applyConfiguration(NetworkConfig::createTestNetworkConfig(RR->identity.address()));
  493. // "Touch" path to this ID to remember test network membership
  494. FILE *tmp = fopen(confPath.c_str(),"w");
  495. if (tmp) fclose(tmp);
  496. } else {
  497. // Read configuration file containing last config from netconf master
  498. {
  499. std::string confs;
  500. if (Utils::readFile(confPath.c_str(),confs)) {
  501. try {
  502. if (confs.length())
  503. setConfiguration(Dictionary(confs),false);
  504. } catch ( ... ) {} // ignore invalid config on disk, we will re-request from netconf master
  505. } else {
  506. // "Touch" path to remember membership in lieu of real config from netconf master
  507. FILE *tmp = fopen(confPath.c_str(),"w");
  508. if (tmp) fclose(tmp);
  509. }
  510. }
  511. }
  512. { // Read most recent membership cert dump if there is one
  513. Mutex::Lock _l(_lock);
  514. if ((_config)&&(!_config->isPublic())&&(Utils::fileExists(mcdbPath.c_str()))) {
  515. CertificateOfMembership com;
  516. _membershipCertificates.clear();
  517. FILE *mcdb = fopen(mcdbPath.c_str(),"rb");
  518. if (mcdb) {
  519. try {
  520. char magic[6];
  521. if ((fread(magic,6,1,mcdb) == 1)&&(!memcmp("ZTMCD0",magic,6))) {
  522. long rlen = 0;
  523. do {
  524. 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);
  525. if (rlen < 0) rlen = 0;
  526. buf.setSize(buf.size() + (unsigned int)rlen);
  527. unsigned int ptr = 0;
  528. while ((ptr < (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  529. ptr += com.deserialize(buf,ptr);
  530. if (com.issuedTo())
  531. _membershipCertificates[com.issuedTo()] = com;
  532. }
  533. buf.behead(ptr);
  534. } while (rlen > 0);
  535. fclose(mcdb);
  536. } else {
  537. fclose(mcdb);
  538. Utils::rm(mcdbPath);
  539. }
  540. } catch ( ... ) {
  541. // Membership cert dump file invalid. We'll re-learn them off the net.
  542. _membershipCertificates.clear();
  543. fclose(mcdb);
  544. Utils::rm(mcdbPath);
  545. }
  546. }
  547. }
  548. }
  549. }
  550. void Network::_dumpMembershipCerts()
  551. {
  552. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  553. std::string mcdbPath(RR->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  554. Mutex::Lock _l(_lock);
  555. if (!_config)
  556. return;
  557. if ((!_id)||(_config->isPublic())) {
  558. Utils::rm(mcdbPath);
  559. return;
  560. }
  561. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  562. if (!mcdb)
  563. return;
  564. if (fwrite("ZTMCD0",6,1,mcdb) != 1) {
  565. fclose(mcdb);
  566. Utils::rm(mcdbPath);
  567. return;
  568. }
  569. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();++c) {
  570. buf.clear();
  571. c->second.serialize(buf);
  572. if (buf.size() > 0) {
  573. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  574. fclose(mcdb);
  575. Utils::rm(mcdbPath);
  576. return;
  577. }
  578. }
  579. }
  580. fclose(mcdb);
  581. Utils::lockDownFile(mcdbPath.c_str(),false);
  582. }
  583. } // namespace ZeroTier