Network.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 "Constants.hpp"
  32. #include "RuntimeEnvironment.hpp"
  33. #include "NodeConfig.hpp"
  34. #include "Network.hpp"
  35. #include "Switch.hpp"
  36. #include "Packet.hpp"
  37. #include "Utils.hpp"
  38. namespace ZeroTier {
  39. void Network::CertificateOfMembership::addParameter(uint64_t id,uint64_t value,uint64_t maxDelta)
  40. {
  41. _params.push_back(_Parameter(id,value,maxDelta));
  42. std::sort(_params.begin(),_params.end(),_SortByIdComparison());
  43. }
  44. std::string Network::CertificateOfMembership::toString() const
  45. {
  46. uint64_t tmp[3000];
  47. unsigned long n = 0;
  48. for(std::vector<_Parameter>::const_iterator p(_params.begin());p!=_params.end();++p) {
  49. tmp[n++] = Utils::hton(p->id);
  50. tmp[n++] = Utils::hton(p->value);
  51. tmp[n++] = Utils::hton(p->maxDelta);
  52. if (n >= 3000)
  53. break; // sanity check -- certificates will never even approach this size
  54. }
  55. return Utils::hex(tmp,sizeof(uint64_t) * n);
  56. }
  57. void Network::CertificateOfMembership::fromString(const char *s)
  58. {
  59. std::string tmp(Utils::unhex(s));
  60. _params.clear();
  61. const char *ptr = tmp.data();
  62. unsigned long remaining = tmp.length();
  63. while (remaining >= 24) {
  64. _Parameter p;
  65. p.id = Utils::ntoh(*((const uint64_t *)(ptr)));
  66. p.value = Utils::ntoh(*((const uint64_t *)(ptr + 8)));
  67. p.maxDelta = Utils::ntoh(*((const uint64_t *)(ptr + 16)));
  68. _params.push_back(p);
  69. ptr += 24;
  70. remaining -= 24;
  71. }
  72. }
  73. bool Network::CertificateOfMembership::compare(const CertificateOfMembership &other) const
  74. throw()
  75. {
  76. unsigned long myidx = 0;
  77. unsigned long otheridx = 0;
  78. while (myidx < _params.size()) {
  79. // Fail if we're at the end of other, since this means the field is
  80. // missing.
  81. if (otheridx >= other._params.size())
  82. return false;
  83. // Seek to corresponding tuple in other, ignoring tuples that
  84. // we may not have. If we run off the end of other, the tuple is
  85. // missing. This works because tuples are sorted by ID.
  86. while (other._params[otheridx].id != _params[myidx].id) {
  87. ++otheridx;
  88. if (otheridx >= other._params.size())
  89. return false;
  90. }
  91. // Compare to determine if the absolute value of the difference
  92. // between these two parameters is within our maxDelta.
  93. uint64_t a = _params[myidx].value;
  94. uint64_t b = other._params[myidx].value;
  95. if (a >= b) {
  96. if ((a - b) > _params[myidx].maxDelta)
  97. return false;
  98. } else {
  99. if ((b - a) > _params[myidx].maxDelta)
  100. return false;
  101. }
  102. ++myidx;
  103. }
  104. return true;
  105. }
  106. const Network::MulticastRates::Rate Network::MulticastRates::GLOBAL_DEFAULT_RATE(65535,65535,64);
  107. const char *Network::statusString(const Status s)
  108. throw()
  109. {
  110. switch(s) {
  111. case NETWORK_WAITING_FOR_FIRST_AUTOCONF: return "WAITING_FOR_FIRST_AUTOCONF";
  112. case NETWORK_OK: return "OK";
  113. case NETWORK_ACCESS_DENIED: return "ACCESS_DENIED";
  114. }
  115. return "(invalid)";
  116. }
  117. Network::~Network()
  118. {
  119. delete _tap;
  120. if (_destroyOnDelete) {
  121. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  122. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  123. Utils::rm(confPath);
  124. Utils::rm(mcdbPath);
  125. } else {
  126. // Causes flush of membership certs to disk
  127. clean();
  128. }
  129. }
  130. SharedPtr<Network> Network::newInstance(const RuntimeEnvironment *renv,uint64_t id)
  131. throw(std::runtime_error)
  132. {
  133. // Tag to identify tap device -- used on some OSes like Windows
  134. char tag[32];
  135. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)id);
  136. // We construct Network via a static method to ensure that it is immediately
  137. // wrapped in a SharedPtr<>. Otherwise if there is traffic on the Ethernet
  138. // tap device, a SharedPtr<> wrap can occur in the Ethernet frame handler
  139. // that then causes the Network instance to be deleted before it is finished
  140. // being constructed. C++ edge cases, how I love thee.
  141. SharedPtr<Network> nw(new Network());
  142. memset(nw->_multicastHistory,0,sizeof(nw->_multicastHistory));
  143. nw->_multicastHistoryPtr = 0;
  144. nw->_ready = false; // disable handling of Ethernet frames during construct
  145. nw->_r = renv;
  146. nw->_tap = new EthernetTap(renv,tag,renv->identity.address().toMAC(),ZT_IF_MTU,&_CBhandleTapData,nw.ptr());
  147. nw->_isOpen = false;
  148. memset(nw->_etWhitelist,0,sizeof(nw->_etWhitelist));
  149. nw->_id = id;
  150. nw->_lastConfigUpdate = 0;
  151. nw->_destroyOnDelete = false;
  152. if (nw->controller() == renv->identity.address()) // sanity check, this isn't supported for now
  153. throw std::runtime_error("cannot add a network for which I am the netconf master");
  154. nw->_restoreState();
  155. nw->_ready = true; // enable handling of Ethernet frames
  156. nw->requestConfiguration();
  157. return nw;
  158. }
  159. void Network::setConfiguration(const Network::Config &conf)
  160. {
  161. Mutex::Lock _l(_lock);
  162. try {
  163. if (conf.networkId() == _id) { // sanity check
  164. _configuration = conf;
  165. // Grab some things from conf for faster lookup and memoize them
  166. _myCertificate = conf.certificateOfMembership();
  167. _mcRates = conf.multicastRates();
  168. _staticAddresses = conf.staticAddresses();
  169. _isOpen = conf.isOpen();
  170. _lastConfigUpdate = Utils::now();
  171. _tap->setIps(_staticAddresses);
  172. _tap->setDisplayName((std::string("ZeroTier One [") + conf.name() + "]").c_str());
  173. // Expand ethertype whitelist into fast-lookup bit field
  174. memset(_etWhitelist,0,sizeof(_etWhitelist));
  175. std::set<unsigned int> wl(conf.etherTypes());
  176. for(std::set<unsigned int>::const_iterator t(wl.begin());t!=wl.end();++t)
  177. _etWhitelist[*t / 8] |= (unsigned char)(1 << (*t % 8));
  178. // Save most recent configuration to disk in networks.d
  179. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  180. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  181. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  182. }
  183. }
  184. } catch ( ... ) {
  185. // If conf is invalid, reset everything
  186. _configuration = Config();
  187. _myCertificate = CertificateOfMembership();
  188. _mcRates = MulticastRates();
  189. _staticAddresses.clear();
  190. _isOpen = false;
  191. _lastConfigUpdate = 0;
  192. LOG("unexpected exception handling config for network %.16llx, retrying fetch...",(unsigned long long)_id);
  193. }
  194. }
  195. void Network::requestConfiguration()
  196. {
  197. if (controller() == _r->identity.address()) {
  198. // FIXME: Right now the netconf master cannot be a member of its own nets
  199. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  200. return;
  201. }
  202. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  203. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  204. outp.append((uint64_t)_id);
  205. outp.append((uint16_t)0); // no meta-data
  206. _r->sw->send(outp,true);
  207. }
  208. void Network::addMembershipCertificate(const Address &peer,const CertificateOfMembership &cert)
  209. {
  210. Mutex::Lock _l(_lock);
  211. if (!_isOpen)
  212. _membershipCertificates[peer] = cert;
  213. }
  214. bool Network::isAllowed(const Address &peer) const
  215. {
  216. // Exceptions can occur if we do not yet have *our* configuration.
  217. try {
  218. Mutex::Lock _l(_lock);
  219. if (_isOpen)
  220. return true;
  221. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  222. if (pc == _membershipCertificates.end())
  223. return false;
  224. return _myCertificate.compare(pc->second);
  225. } catch (std::exception &exc) {
  226. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  227. } catch ( ... ) {
  228. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  229. }
  230. return false;
  231. }
  232. void Network::clean()
  233. {
  234. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  235. Mutex::Lock _l(_lock);
  236. if ((!_id)||(_isOpen)) {
  237. _membershipCertificates.clear();
  238. Utils::rm(mcdbPath);
  239. } else {
  240. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  241. bool writeError = false;
  242. if (!mcdb) {
  243. LOG("error: unable to open membership cert database at: %s",mcdbPath.c_str());
  244. } else {
  245. if ((writeError)||(fwrite("MCDB0",5,1,mcdb) != 1)) // version
  246. writeError = true;
  247. }
  248. for(std::map<Address,CertificateOfMembership>::iterator i=(_membershipCertificates.begin());i!=_membershipCertificates.end();) {
  249. if (_myCertificate.compare(i->second)) {
  250. if ((!writeError)&&(mcdb)) {
  251. char tmp[ZT_ADDRESS_LENGTH];
  252. i->first.copyTo(tmp,ZT_ADDRESS_LENGTH);
  253. if ((writeError)||(fwrite(tmp,ZT_ADDRESS_LENGTH,1,mcdb) != 1))
  254. writeError = true;
  255. std::string c(i->second.toString());
  256. uint32_t cl = Utils::hton((uint32_t)c.length());
  257. if ((writeError)||(fwrite(&cl,sizeof(cl),1,mcdb) != 1))
  258. writeError = true;
  259. if ((writeError)||(fwrite(c.data(),c.length(),1,mcdb) != 1))
  260. writeError = true;
  261. }
  262. ++i;
  263. } else _membershipCertificates.erase(i++);
  264. }
  265. if (mcdb)
  266. fclose(mcdb);
  267. if (writeError) {
  268. Utils::rm(mcdbPath);
  269. LOG("error: unable to write to membership cert database at: %s",mcdbPath.c_str());
  270. }
  271. }
  272. }
  273. Network::Status Network::status() const
  274. {
  275. Mutex::Lock _l(_lock);
  276. if (_configuration)
  277. return NETWORK_OK;
  278. return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  279. }
  280. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  281. {
  282. if (!((Network *)arg)->_ready)
  283. return;
  284. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  285. if (_r->shutdownInProgress)
  286. return;
  287. try {
  288. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  289. } catch (std::exception &exc) {
  290. TRACE("unexpected exception handling local packet: %s",exc.what());
  291. } catch ( ... ) {
  292. TRACE("unexpected exception handling local packet");
  293. }
  294. }
  295. void Network::_restoreState()
  296. {
  297. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  298. std::string confs;
  299. if (Utils::readFile(confPath.c_str(),confs)) {
  300. try {
  301. if (confs.length())
  302. setConfiguration(Config(confs));
  303. } catch ( ... ) {} // ignore invalid config on disk, we will re-request
  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(),"w");
  308. if (tmp)
  309. fclose(tmp);
  310. }
  311. // TODO: restore membership certs
  312. }
  313. } // namespace ZeroTier