Network.cpp 14 KB

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