Network.cpp 16 KB

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