Network.cpp 12 KB

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