Network.cpp 14 KB

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