Network.cpp 20 KB

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