Network.cpp 21 KB

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