Network.cpp 14 KB

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