Network.cpp 17 KB

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