Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. #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. Thread::join(_setupThread);
  60. if (_tap)
  61. _r->tapFactory->close(_tap,_destroyOnDelete);
  62. if (_destroyOnDelete) {
  63. Utils::rm(std::string(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf"));
  64. Utils::rm(std::string(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts"));
  65. } else {
  66. clean();
  67. _dumpMulticastCerts();
  68. }
  69. }
  70. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,NodeConfig *nc,uint64_t id)
  71. {
  72. /* We construct Network via a static method to ensure that it is immediately
  73. * wrapped in a SharedPtr<>. Otherwise if there is traffic on the Ethernet
  74. * tap device, a SharedPtr<> wrap can occur in the Ethernet frame handler
  75. * that then causes the Network instance to be deleted before it is finished
  76. * being constructed. C++ edge cases, how I love thee. */
  77. SharedPtr<Network> nw(new Network());
  78. nw->_id = id;
  79. nw->_nc = nc;
  80. nw->_mac.fromAddress(renv->identity.address(),id);
  81. nw->_r = renv;
  82. nw->_tap = (EthernetTap *)0;
  83. nw->_enabled = true;
  84. nw->_lastConfigUpdate = 0;
  85. nw->_destroyOnDelete = false;
  86. nw->_netconfFailure = NETCONF_FAILURE_NONE;
  87. if (nw->controller() == renv->identity.address()) // TODO: fix Switch to allow packets to self
  88. throw std::runtime_error("cannot join a network for which I am the netconf master");
  89. try {
  90. nw->_restoreState();
  91. nw->requestConfiguration();
  92. } catch ( ... ) {
  93. TRACE("exception in network setup thread in _restoreState() or requestConfiguration()!");
  94. nw->_lastConfigUpdate = 0; // call requestConfiguration() again
  95. }
  96. return nw;
  97. }
  98. bool Network::updateMulticastGroups()
  99. {
  100. Mutex::Lock _l(_lock);
  101. EthernetTap *t = _tap;
  102. if (t) {
  103. // Grab current groups from the local tap
  104. bool updated = t->updateMulticastGroups(_multicastGroups);
  105. // Merge in learned groups from any hosts bridged in behind us
  106. for(std::map<MulticastGroup,uint64_t>::const_iterator mg(_bridgedMulticastGroups.begin());mg!=_bridgedMulticastGroups.end();++mg)
  107. _multicastGroups.insert(mg->first);
  108. // Add or remove BROADCAST group based on broadcast enabled netconf flag
  109. if ((_config)&&(_config->enableBroadcast())) {
  110. if (_multicastGroups.count(BROADCAST))
  111. return updated;
  112. else {
  113. _multicastGroups.insert(BROADCAST);
  114. return true;
  115. }
  116. } else {
  117. if (_multicastGroups.count(BROADCAST)) {
  118. _multicastGroups.erase(BROADCAST);
  119. return true;
  120. } else return updated;
  121. }
  122. } else return false;
  123. }
  124. bool Network::setConfiguration(const Dictionary &conf,bool saveToDisk)
  125. {
  126. Mutex::Lock _l(_lock);
  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. uint64_t now = Utils::now();
  212. if ((_config)&&(_config->isPublic())) {
  213. // Open (public) networks do not track certs or cert pushes at all.
  214. _membershipCertificates.clear();
  215. _lastPushedMembershipCertificate.clear();
  216. } else if (_config) {
  217. // Clean certificates that are no longer valid from the cache.
  218. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();) {
  219. if (_config->com().agreesWith(c->second))
  220. ++c;
  221. else _membershipCertificates.erase(c++);
  222. }
  223. // Clean entries from the last pushed tracking map if they're so old as
  224. // to be no longer relevant.
  225. uint64_t forgetIfBefore = now - (_config->com().timestampMaxDelta() * 3ULL);
  226. for(std::map<Address,uint64_t>::iterator lp(_lastPushedMembershipCertificate.begin());lp!=_lastPushedMembershipCertificate.end();) {
  227. if (lp->second < forgetIfBefore)
  228. _lastPushedMembershipCertificate.erase(lp++);
  229. else ++lp;
  230. }
  231. }
  232. // Clean learned multicast groups if we haven't heard from them in a while
  233. for(std::map<MulticastGroup,uint64_t>::iterator mg(_bridgedMulticastGroups.begin());mg!=_bridgedMulticastGroups.end();) {
  234. if ((now - mg->second) > (ZT_MULTICAST_LIKE_EXPIRE * 2))
  235. _bridgedMulticastGroups.erase(mg++);
  236. else ++mg;
  237. }
  238. }
  239. Network::Status Network::status() const
  240. {
  241. Mutex::Lock _l(_lock);
  242. if (_tap) {
  243. switch(_netconfFailure) {
  244. case NETCONF_FAILURE_ACCESS_DENIED:
  245. return NETWORK_ACCESS_DENIED;
  246. case NETCONF_FAILURE_NOT_FOUND:
  247. return NETWORK_NOT_FOUND;
  248. case NETCONF_FAILURE_NONE:
  249. if (_lastConfigUpdate > 0)
  250. return NETWORK_OK;
  251. else return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  252. case NETCONF_FAILURE_INIT_FAILED:
  253. default:
  254. return NETWORK_INITIALIZATION_FAILED;
  255. }
  256. } else if (_netconfFailure == NETCONF_FAILURE_INIT_FAILED) {
  257. return NETWORK_INITIALIZATION_FAILED;
  258. } else return NETWORK_INITIALIZING;
  259. }
  260. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  261. {
  262. if ((!((Network *)arg)->_enabled)||(((Network *)arg)->status() != NETWORK_OK))
  263. return;
  264. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  265. if (_r->shutdownInProgress)
  266. return;
  267. try {
  268. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  269. } catch (std::exception &exc) {
  270. TRACE("unexpected exception handling local packet: %s",exc.what());
  271. } catch ( ... ) {
  272. TRACE("unexpected exception handling local packet");
  273. }
  274. }
  275. void Network::_pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  276. {
  277. uint64_t pushTimeout = _config->com().timestampMaxDelta() / 2;
  278. if (!pushTimeout)
  279. return; // still waiting on my own cert
  280. if (pushTimeout > 1000)
  281. pushTimeout -= 1000;
  282. uint64_t &lastPushed = _lastPushedMembershipCertificate[peer];
  283. if ((force)||((now - lastPushed) > pushTimeout)) {
  284. lastPushed = now;
  285. TRACE("pushing membership cert for %.16llx to %s",(unsigned long long)_id,peer.toString().c_str());
  286. Packet outp(peer,_r->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  287. _config->com().serialize(outp);
  288. _r->sw->send(outp,true);
  289. }
  290. }
  291. // Ethernet tap creation thread -- required on some platforms where tap
  292. // creation may be time consuming (e.g. Windows).
  293. void Network::threadMain()
  294. throw()
  295. {
  296. char fname[1024],lcentry[128];
  297. Utils::snprintf(lcentry,sizeof(lcentry),"_dev_for_%.16llx",(unsigned long long)_id);
  298. EthernetTap *t;
  299. try {
  300. std::string desiredDevice(_nc->getLocalConfig(lcentry));
  301. _mkNetworkFriendlyName(fname,sizeof(fname));
  302. 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);
  303. std::string dn(t->deviceName());
  304. if ((dn.length())&&(dn != desiredDevice))
  305. _nc->putLocalConfig(lcentry,dn);
  306. } catch (std::exception &exc) {
  307. delete t;
  308. t = (EthernetTap *)0;
  309. LOG("network %.16llx failed to initialize: %s",_id,exc.what());
  310. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  311. } catch ( ... ) {
  312. delete t;
  313. t = (EthernetTap *)0;
  314. LOG("network %.16llx failed to initialize: unknown error",_id);
  315. _netconfFailure = NETCONF_FAILURE_INIT_FAILED;
  316. }
  317. {
  318. Mutex::Lock _l(_lock);
  319. if (_tap) // the tap creation thread can technically be re-launched, though this isn't done right now
  320. _r->tapFactory->close(_tap,_destroyOnDelete);
  321. _tap = t;
  322. if (t) {
  323. if (_config)
  324. t->setIps(_config->staticIps());
  325. t->setEnabled(_enabled);
  326. }
  327. }
  328. }
  329. void Network::learnBridgeRoute(const MAC &mac,const Address &addr)
  330. {
  331. Mutex::Lock _l(_lock);
  332. _bridgeRoutes[mac] = addr;
  333. // If _bridgeRoutes exceeds sanity limit, trim worst offenders until below -- denial of service circuit breaker
  334. while (_bridgeRoutes.size() > ZT_MAX_BRIDGE_ROUTES) {
  335. std::map<Address,unsigned long> counts;
  336. Address maxAddr;
  337. unsigned long maxCount = 0;
  338. for(std::map<MAC,Address>::iterator br(_bridgeRoutes.begin());br!=_bridgeRoutes.end();++br) {
  339. unsigned long c = ++counts[br->second];
  340. if (c > maxCount) {
  341. maxCount = c;
  342. maxAddr = br->second;
  343. }
  344. }
  345. for(std::map<MAC,Address>::iterator br(_bridgeRoutes.begin());br!=_bridgeRoutes.end();) {
  346. if (br->second == maxAddr)
  347. _bridgeRoutes.erase(br++);
  348. else ++br;
  349. }
  350. }
  351. }
  352. void Network::setEnabled(bool enabled)
  353. {
  354. Mutex::Lock _l(_lock);
  355. _enabled = enabled;
  356. if (_tap)
  357. _tap->setEnabled(enabled);
  358. }
  359. void Network::_restoreState()
  360. {
  361. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  362. std::string idstr(idString());
  363. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".conf");
  364. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idstr + ".mcerts");
  365. // Read configuration file containing last config from netconf master
  366. {
  367. std::string confs;
  368. if (Utils::readFile(confPath.c_str(),confs)) {
  369. try {
  370. if (confs.length())
  371. setConfiguration(Dictionary(confs),false);
  372. } catch ( ... ) {} // ignore invalid config on disk, we will re-request from netconf master
  373. } else {
  374. // If the conf file isn't present, "touch" it so we'll remember
  375. // the existence of this network.
  376. FILE *tmp = fopen(confPath.c_str(),"w");
  377. if (tmp)
  378. fclose(tmp);
  379. }
  380. }
  381. // Read most recent multicast cert dump
  382. if ((_config)&&(!_config->isPublic())&&(Utils::fileExists(mcdbPath.c_str()))) {
  383. CertificateOfMembership com;
  384. Mutex::Lock _l(_lock);
  385. _membershipCertificates.clear();
  386. FILE *mcdb = fopen(mcdbPath.c_str(),"rb");
  387. if (mcdb) {
  388. try {
  389. char magic[6];
  390. if ((fread(magic,6,1,mcdb) == 1)&&(!memcmp("ZTMCD0",magic,6))) {
  391. long rlen = 0;
  392. do {
  393. long rlen = (long)fread(buf.data() + buf.size(),1,ZT_NETWORK_CERT_WRITE_BUF_SIZE - buf.size(),mcdb);
  394. if (rlen < 0) rlen = 0;
  395. buf.setSize(buf.size() + (unsigned int)rlen);
  396. unsigned int ptr = 0;
  397. while ((ptr < (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2))&&(ptr < buf.size())) {
  398. ptr += com.deserialize(buf,ptr);
  399. if (com.issuedTo())
  400. _membershipCertificates[com.issuedTo()] = com;
  401. }
  402. if (ptr) {
  403. memmove(buf.data(),buf.data() + ptr,buf.size() - ptr);
  404. buf.setSize(buf.size() - ptr);
  405. }
  406. } while (rlen > 0);
  407. fclose(mcdb);
  408. } else {
  409. fclose(mcdb);
  410. Utils::rm(mcdbPath);
  411. }
  412. } catch ( ... ) {
  413. // Membership cert dump file invalid. We'll re-learn them off the net.
  414. _membershipCertificates.clear();
  415. fclose(mcdb);
  416. Utils::rm(mcdbPath);
  417. }
  418. }
  419. }
  420. }
  421. void Network::_dumpMulticastCerts()
  422. {
  423. Buffer<ZT_NETWORK_CERT_WRITE_BUF_SIZE> buf;
  424. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  425. Mutex::Lock _l(_lock);
  426. if (!_config)
  427. return;
  428. if ((!_id)||(_config->isPublic())) {
  429. Utils::rm(mcdbPath);
  430. return;
  431. }
  432. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  433. if (!mcdb)
  434. return;
  435. if (fwrite("ZTMCD0",6,1,mcdb) != 1) {
  436. fclose(mcdb);
  437. Utils::rm(mcdbPath);
  438. return;
  439. }
  440. for(std::map<Address,CertificateOfMembership>::iterator c=(_membershipCertificates.begin());c!=_membershipCertificates.end();++c) {
  441. try {
  442. c->second.serialize(buf);
  443. if (buf.size() >= (ZT_NETWORK_CERT_WRITE_BUF_SIZE / 2)) {
  444. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  445. fclose(mcdb);
  446. Utils::rm(mcdbPath);
  447. return;
  448. }
  449. buf.clear();
  450. }
  451. } catch ( ... ) {
  452. // Sanity check... no cert will ever be big enough to overflow buf
  453. fclose(mcdb);
  454. Utils::rm(mcdbPath);
  455. return;
  456. }
  457. }
  458. if (buf.size()) {
  459. if (fwrite(buf.data(),buf.size(),1,mcdb) != 1) {
  460. fclose(mcdb);
  461. Utils::rm(mcdbPath);
  462. return;
  463. }
  464. }
  465. fclose(mcdb);
  466. Utils::lockDownFile(mcdbPath.c_str(),false);
  467. }
  468. } // namespace ZeroTier