Network.cpp 14 KB

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