Network.cpp 11 KB

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