Network.cpp 20 KB

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