Network.cpp 14 KB

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