Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. Thread::join(_setupThread);
  61. {
  62. Mutex::Lock _l(_lock);
  63. if (_tap)
  64. _r->tapFactory->close(_tap,_destroyed);
  65. }
  66. if (_destroyed) {
  67. Utils::rm(std::string(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf"));
  68. Utils::rm(std::string(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts"));
  69. } else {
  70. clean();
  71. _dumpMulticastCerts();
  72. }
  73. }
  74. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,NodeConfig *nc,uint64_t id)
  75. {
  76. SharedPtr<Network> nw(new Network());
  77. nw->_id = id;
  78. nw->_nc = nc;
  79. nw->_mac.fromAddress(renv->identity.address(),id);
  80. nw->_r = renv;
  81. nw->_tap = (EthernetTap *)0;
  82. nw->_enabled = true;
  83. nw->_lastConfigUpdate = 0;
  84. nw->_destroyed = false;
  85. nw->_netconfFailure = NETCONF_FAILURE_NONE;
  86. if (nw->controller() == renv->identity.address()) // TODO: fix Switch to allow packets to self
  87. throw std::runtime_error("cannot join a network for which I am the netconf master");
  88. try {
  89. nw->_restoreState();
  90. nw->requestConfiguration();
  91. } catch ( ... ) {
  92. nw->_lastConfigUpdate = 0; // call requestConfiguration() again
  93. }
  94. return nw;
  95. }
  96. bool Network::updateMulticastGroups()
  97. {
  98. Mutex::Lock _l(_lock);
  99. EthernetTap *t = _tap;
  100. if (t) {
  101. // Grab current groups from the local tap
  102. bool updated = t->updateMulticastGroups(_multicastGroups);
  103. // Merge in learned groups from any hosts bridged in behind us
  104. for(std::map<MulticastGroup,uint64_t>::const_iterator mg(_bridgedMulticastGroups.begin());mg!=_bridgedMulticastGroups.end();++mg)
  105. _multicastGroups.insert(mg->first);
  106. // Add or remove BROADCAST group based on broadcast enabled netconf flag
  107. if ((_config)&&(_config->enableBroadcast())) {
  108. if (_multicastGroups.count(BROADCAST))
  109. return updated;
  110. else {
  111. _multicastGroups.insert(BROADCAST);
  112. return true;
  113. }
  114. } else {
  115. if (_multicastGroups.count(BROADCAST)) {
  116. _multicastGroups.erase(BROADCAST);
  117. return true;
  118. } else return updated;
  119. }
  120. } else return false;
  121. }
  122. bool Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  123. {
  124. Mutex::Lock _l(_lock);
  125. if (_destroyed)
  126. return false;
  127. try {
  128. SharedPtr<NetworkConfig> newConfig(new NetworkConfig(conf)); // throws if invalid
  129. if ((newConfig->networkId() == _id)&&(newConfig->issuedTo() == _r->identity.address())) {
  130. _config = newConfig;
  131. _lastConfigUpdate = Utils::now();
  132. _netconfFailure = NETCONF_FAILURE_NONE;
  133. if (saveToDisk) {
  134. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  135. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  136. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  137. } else {
  138. Utils::lockDownFile(confPath.c_str(),false);
  139. }
  140. }
  141. EthernetTap *t = _tap;
  142. if (t) {
  143. char fname[1024];
  144. _mkNetworkFriendlyName(fname,sizeof(fname));
  145. t->setIps(newConfig->staticIps());
  146. t->setFriendlyName(fname);
  147. } else {
  148. if (!_setupThread)
  149. _setupThread = Thread::start<Network>(this);
  150. }
  151. return true;
  152. } else {
  153. LOG("ignored invalid configuration for network %.16llx (configuration contains mismatched network ID or issued-to address)",(unsigned long long)_id);
  154. }
  155. } catch (std::exception &exc) {
  156. LOG("ignored invalid configuration for network %.16llx (%s)",(unsigned long long)_id,exc.what());
  157. } catch ( ... ) {
  158. LOG("ignored invalid configuration for network %.16llx (unknown exception)",(unsigned long long)_id);
  159. }
  160. return false;
  161. }
  162. void Network::requestConfiguration()
  163. {
  164. if (controller() == _r->identity.address()) {
  165. // netconf master cannot be a member of its own nets
  166. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  167. return;
  168. }
  169. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  170. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  171. outp.append((uint64_t)_id);
  172. outp.append((uint16_t)0); // no meta-data
  173. _r->sw->send(outp,true);
  174. }
  175. void Network::addMembershipCertificate(const CertificateOfMembership &cert)
  176. {
  177. if (!cert) // sanity check
  178. return;
  179. Mutex::Lock _l(_lock);
  180. // We go ahead and accept certs provisionally even if _isOpen is true, since
  181. // that might be changed in short order if the user is fiddling in the UI.
  182. // These will be purged on clean() for open networks eventually.
  183. CertificateOfMembership &old = _membershipCertificates[cert.issuedTo()];
  184. if (cert.timestamp() >= old.timestamp()) {
  185. //TRACE("got new certificate for %s on network %.16llx",cert.issuedTo().toString().c_str(),cert.networkId());
  186. old = cert;
  187. }
  188. }
  189. bool Network::isAllowed(const Address &peer) const
  190. {
  191. try {
  192. Mutex::Lock _l(_lock);
  193. if (!_config)
  194. return false;
  195. if (_config->isPublic())
  196. return true;
  197. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  198. if (pc == _membershipCertificates.end())
  199. return false; // no certificate on file
  200. return _config->com().agreesWith(pc->second); // is other cert valid against ours?
  201. } catch (std::exception &exc) {
  202. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  203. } catch ( ... ) {
  204. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  205. }
  206. return false; // default position on any failure
  207. }
  208. void Network::clean()
  209. {
  210. Mutex::Lock _l(_lock);
  211. if (_destroyed)
  212. return;
  213. uint64_t now = Utils::now();
  214. if ((_config)&&(_config->isPublic())) {
  215. // Open (public) networks do not track certs or cert pushes at all.
  216. _membershipCertificates.clear();
  217. _lastPushedMembershipCertificate.clear();
  218. } else if (_config) {
  219. // Clean certificates that are no longer valid from the cache.
  220. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  221. if (_config->com().agreesWith(c->second))
  222. ++c;
  223. else _membershipCertificates.erase(c++);
  224. }
  225. // Clean entries from the last pushed tracking map if they're so old as
  226. // to be no longer relevant.
  227. uint64_t forgetIfBefore = now - (_config->com().timestampMaxDelta() * 3ULL);
  228. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  229. if (lp->second < forgetIfBefore)
  230. _lastPushedMembershipCertificate.erase(lp++);
  231. else ++lp;
  232. }
  233. }
  234. // Clean learned multicast groups if we haven't heard from them in a while
  235. for(std::map<MulticastGroup,uint64_t>::iterator mg(_bridgedMulticastGroups.begin());mg!=_bridgedMulticastGroups.end();) {
  236. if ((now - mg->second) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  237. _bridgedMulticastGroups.erase(mg++);
  238. else ++mg;
  239. }
  240. }
  241. Network::Status Network::status() const
  242. {
  243. Mutex::Lock _l(_lock);
  244. switch(_netconfFailure) {
  245. case NETCONF_FAILURE_ACCESS_DENIED:
  246. return NETWORK_ACCESS_DENIED;
  247. case NETCONF_FAILURE_NOT_FOUND:
  248. return NETWORK_NOT_FOUND;
  249. case NETCONF_FAILURE_NONE:
  250. return ((_lastConfigUpdate > 0) ? ((_tap) ? NETWORK_OK : NETWORK_INITIALIZING) : NETWORK_WAITING_FOR_FIRST_AUTOCONF);
  251. //case NETCONF_FAILURE_INIT_FAILED:
  252. default:
  253. return NETWORK_INITIALIZATION_FAILED;
  254. }
  255. }
  256. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  257. {
  258. if ((!((Network *)arg)->_enabled)||(((Network *)arg)->status() != NETWORK_OK))
  259. return;
  260. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  261. if (_r->shutdownInProgress)
  262. return;
  263. try {
  264. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  265. } catch (std::exception &exc) {
  266. TRACE("unexpected exception handling local packet: %s",exc.what());
  267. } catch ( ... ) {
  268. TRACE("unexpected exception handling local packet");
  269. }
  270. }
  271. void Network::_pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  272. {
  273. uint64_t pushTimeout = _config->com().timestampMaxDelta() / 2;
  274. if (!pushTimeout)
  275. return; // still waiting on my own cert
  276. if (pushTimeout > 1000)
  277. pushTimeout -= 1000;
  278. uint64_t &lastPushed = _lastPushedMembershipCertificate[peer];
  279. if ((force)||((now - lastPushed) > pushTimeout)) {
  280. lastPushed = now;
  281. TRACE("pushing membership cert for %.16llx to %s",(unsigned long long)_id,peer.toString().c_str());
  282. Packet outp(peer,_r->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  283. _config->com().serialize(outp);
  284. _r->sw->send(outp,true);
  285. }
  286. }
  287. // Ethernet tap creation thread -- required on some platforms where tap
  288. // creation may be time consuming (e.g. Windows).
  289. void Network::threadMain()
  290. throw()
  291. {
  292. char fname[1024],lcentry[128];
  293. Utils::snprintf(lcentry,sizeof(lcentry),"_dev_for_%.16llx",(unsigned long long)_id);
  294. EthernetTap *t = (EthernetTap *)0;
  295. try {
  296. std::string desiredDevice(_nc->getLocalConfig(lcentry));
  297. _mkNetworkFriendlyName(fname,sizeof(fname));
  298. t = _r->tapFactory->open(_mac,ZT_IF_MTU,ZT_DEFAULT_IF_METRIC,_id,(desiredDevice.length() > 0) ? desiredDevice.c_str() : (const char *)0,fname,_CBhandleTapData,this);
  299. std::string dn(t->deviceName());
  300. if ((dn.length())&&(dn != desiredDevice))
  301. _nc->putLocalConfig(lcentry,dn);
  302. } catch (std::exception &exc) {
  303. delete t;
  304. t = (EthernetTap *)0;
  305. LOG("network %.16llx failed to initialize: %s",_id,exc.what());
  306. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  307. } catch ( ... ) {
  308. delete t;
  309. t = (EthernetTap *)0;
  310. LOG("network %.16llx failed to initialize: unknown error",_id);
  311. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  312. }
  313. {
  314. Mutex::Lock _l(_lock);
  315. if (_tap) // the tap creation thread can technically be re-launched, though this isn't done right now
  316. _r->tapFactory->close(_tap,false);
  317. _tap = t;
  318. if (t) {
  319. if (_config)
  320. t->setIps(_config->staticIps());
  321. t->setEnabled(_enabled);
  322. }
  323. }
  324. }
  325. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  326. {
  327. Mutex::Lock _l(_lock);
  328. _bridgeRoutes[mac] = addr;
  329. // If _bridgeRoutes exceeds sanity limit, trim worst offenders until below -- denial of service circuit breaker
  330. while (_bridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  331. std::map<Address,unsigned long> counts;
  332. Address maxAddr;
  333. unsigned long maxCount = 0;
  334. for(std::map<MAC,Address>::iterator br(_bridgeRoutes.begin());br!=_bridgeRoutes.end();++br) {
  335. unsigned long c = ++counts[br->second];
  336. if (c > maxCount) {
  337. maxCount = c;
  338. maxAddr = br->second;
  339. }
  340. }
  341. for(std::map<MAC,Address>::iterator br(_bridgeRoutes.begin());br!=_bridgeRoutes.end();) {
  342. if (br->second == maxAddr)
  343. _bridgeRoutes.erase(br++);
  344. else ++br;
  345. }
  346. }
  347. }
  348. void Network::setEnabled(bool enabled)
  349. {
  350. Mutex::Lock _l(_lock);
  351. _enabled = enabled;
  352. if (_tap)
  353. _tap->setEnabled(enabled);
  354. }
  355. void Network::destroy()
  356. {
  357. Mutex::Lock _l(_lock);
  358. _enabled = false;
  359. _destroyed = true;
  360. Thread::join(_setupThread);
  361. if (_tap)
  362. _r->tapFactory->close(_tap,true);
  363. _tap = (EthernetTap *)0;
  364. }
  365. void Network::_restoreState()
  366. {
  367. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  368. std::string idstr(idString());
  369. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".conf");
  370. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".mcerts");
  371. // Read configuration file containing last config from netconf master
  372. {
  373. std::string confs;
  374. if (Utils::readFile(confPath.c_str(),confs)) {
  375. try {
  376. if (confs.length())
  377. setConfiguration(Dictionary(confs),false);
  378. } catch ( ... ) {} // ignore invalid config on disk, we will re-request from netconf master
  379. } else {
  380. // If the conf file isn't present, "touch" it so we'll remember
  381. // the existence of this network.
  382. FILE *tmp = fopen(confPath.c_str(),"w");
  383. if (tmp)
  384. fclose(tmp);
  385. }
  386. }
  387. // Read most recent multicast cert dump
  388. if ((_config)&&(!_config->isPublic())&&(Utils::fileExists(mcdbPath.c_str()))) {
  389. CertificateOfMembership com;
  390. Mutex::Lock _l(_lock);
  391. _membershipCertificates.clear();
  392. FILE *mcdb = fopen(mcdbPath.c_str(),"rb");
  393. if (mcdb) {
  394. try {
  395. char magic[6];
  396. if ((fread(magic,6,1,mcdb) == 1)&&(!memcmp("ZTMCD0",magic,6))) {
  397. long rlen = 0;
  398. do {
  399. long rlen = (long)fread(buf.data() + buf.size(),1,ZT_NETWORK_CERT_WRITE_BUF_SIZE - buf.size(),mcdb);
  400. if (rlen < 0) rlen = 0;
  401. buf.setSize(buf.size() + (unsigned int)rlen);
  402. unsigned int ptr = 0;
  403. while ((ptr < (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  404. ptr += com.deserialize(buf,ptr);
  405. if (com.issuedTo())
  406. _membershipCertificates[com.issuedTo()] = com;
  407. }
  408. if (ptr) {
  409. memmove(buf.data(),buf.data() + ptr,buf.size() - ptr);
  410. buf.setSize(buf.size() - ptr);
  411. }
  412. } while (rlen > 0);
  413. fclose(mcdb);
  414. } else {
  415. fclose(mcdb);
  416. Utils::rm(mcdbPath);
  417. }
  418. } catch ( ... ) {
  419. // Membership cert dump file invalid. We'll re-learn them off the net.
  420. _membershipCertificates.clear();
  421. fclose(mcdb);
  422. Utils::rm(mcdbPath);
  423. }
  424. }
  425. }
  426. }
  427. void Network::_dumpMulticastCerts()
  428. {
  429. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  430. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  431. Mutex::Lock _l(_lock);
  432. if (!_config)
  433. return;
  434. if ((!_id)||(_config->isPublic())) {
  435. Utils::rm(mcdbPath);
  436. return;
  437. }
  438. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  439. if (!mcdb)
  440. return;
  441. if (fwrite("ZTMCD0",6,1,mcdb) != 1) {
  442. fclose(mcdb);
  443. Utils::rm(mcdbPath);
  444. return;
  445. }
  446. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();++c) {
  447. try {
  448. c->second.serialize(buf);
  449. if (buf.size() >= (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2)) {
  450. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  451. fclose(mcdb);
  452. Utils::rm(mcdbPath);
  453. return;
  454. }
  455. buf.clear();
  456. }
  457. } catch ( ... ) {
  458. // Sanity check... no cert will ever be big enough to overflow buf
  459. fclose(mcdb);
  460. Utils::rm(mcdbPath);
  461. return;
  462. }
  463. }
  464. if (buf.size()) {
  465. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  466. fclose(mcdb);
  467. Utils::rm(mcdbPath);
  468. return;
  469. }
  470. }
  471. fclose(mcdb);
  472. Utils::lockDownFile(mcdbPath.c_str(),false);
  473. }
  474. } // namespace ZeroTier