Network.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 <openssl/sha.h>
  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. char tag[32];
  134. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)id);
  135. // We construct Network via a static method to ensure that it is immediately
  136. // wrapped in a SharedPtr<>. Otherwise if there is traffic on the Ethernet
  137. // tap device, a SharedPtr<> wrap can occur in the Ethernet frame handler
  138. // that then causes the Network instance to be deleted before it is finished
  139. // being constructed. C++ edge cases, how I love thee.
  140. SharedPtr<Network> nw(new Network());
  141. nw->_ready = false; // disable handling of Ethernet frames during construct
  142. nw->_r = renv;
  143. nw->_tap = new EthernetTap(renv,tag,renv->identity.address().toMAC(),ZT_IF_MTU,&_CBhandleTapData,nw.ptr());
  144. memset(nw->_etWhitelist,0,sizeof(nw->_etWhitelist));
  145. nw->_id = id;
  146. nw->_lastConfigUpdate = 0;
  147. nw->_destroyOnDelete = false;
  148. if (nw->controller() == renv->identity.address()) // sanity check, this isn't supported for now
  149. throw std::runtime_error("cannot add a network for which I am the netconf master");
  150. nw->_restoreState();
  151. nw->_ready = true; // enable handling of Ethernet frames
  152. nw->requestConfiguration();
  153. return nw;
  154. }
  155. void Network::setConfiguration(const Network::Config &conf)
  156. {
  157. Mutex::Lock _l(_lock);
  158. try {
  159. if (conf.networkId() == _id) { // sanity check
  160. _configuration = conf;
  161. _myCertificate = conf.certificateOfMembership();
  162. _mcRates = conf.multicastRates();
  163. _lastConfigUpdate = Utils::now();
  164. _tap->setIps(conf.staticAddresses());
  165. _tap->setDisplayName((std::string("ZeroTier One [") + conf.name() + "]").c_str());
  166. memset(_etWhitelist,0,sizeof(_etWhitelist));
  167. std::set<unsigned int> wl(conf.etherTypes());
  168. for(std::set<unsigned int>::const_iterator t(wl.begin());t!=wl.end();++t)
  169. _etWhitelist[*t / 8] |= (unsigned char)(1 << (*t % 8));
  170. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  171. if (!Utils::writeFile(confPath.c_str(),conf.toString())) {
  172. LOG("error: unable to write network configuration file at: %s",confPath.c_str());
  173. }
  174. }
  175. } catch ( ... ) {
  176. _configuration = Config();
  177. _myCertificate = CertificateOfMembership();
  178. _lastConfigUpdate = 0;
  179. LOG("unexpected exception handling config for network %.16llx, retrying fetch...",(unsigned long long)_id);
  180. }
  181. }
  182. void Network::requestConfiguration()
  183. {
  184. if (controller() == _r->identity.address()) {
  185. LOG("unable to request network configuration for network %.16llx: I am the network master, cannot query self",(unsigned long long)_id);
  186. return;
  187. }
  188. TRACE("requesting netconf for network %.16llx from netconf master %s",(unsigned long long)_id,controller().toString().c_str());
  189. Packet outp(controller(),_r->identity.address(),Packet::VERB_NETWORK_CONFIG_REQUEST);
  190. outp.append((uint64_t)_id);
  191. outp.append((uint16_t)0); // no meta-data
  192. _r->sw->send(outp,true);
  193. }
  194. void Network::addMembershipCertificate(const Address &peer,const CertificateOfMembership &cert)
  195. {
  196. Mutex::Lock _l(_lock);
  197. if (!_configuration.isOpen())
  198. _membershipCertificates[peer] = cert;
  199. }
  200. bool Network::isAllowed(const Address &peer) const
  201. {
  202. // Exceptions can occur if we do not yet have *our* configuration.
  203. try {
  204. Mutex::Lock _l(_lock);
  205. if (_configuration.isOpen())
  206. return true;
  207. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  208. if (pc == _membershipCertificates.end())
  209. return false;
  210. return _myCertificate.compare(pc->second);
  211. } catch (std::exception &exc) {
  212. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  213. } catch ( ... ) {
  214. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  215. }
  216. return false;
  217. }
  218. void Network::clean()
  219. {
  220. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  221. Mutex::Lock _l(_lock);
  222. if (_configuration.isOpen()) {
  223. _membershipCertificates.clear();
  224. Utils::rm(mcdbPath);
  225. } else {
  226. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  227. bool writeError = false;
  228. if (!mcdb) {
  229. LOG("error: unable to open membership cert database at: %s",mcdbPath.c_str());
  230. } else {
  231. if ((writeError)||(fwrite("MCDB0",5,1,mcdb) != 1)) // version
  232. writeError = true;
  233. }
  234. for(std::map<Address,CertificateOfMembership>::iterator i=(_membershipCertificates.begin());i!=_membershipCertificates.end();) {
  235. if (_myCertificate.compare(i->second)) {
  236. if ((!writeError)&&(mcdb)) {
  237. char tmp[ZT_ADDRESS_LENGTH];
  238. i->first.copyTo(tmp,ZT_ADDRESS_LENGTH);
  239. if ((writeError)||(fwrite(tmp,ZT_ADDRESS_LENGTH,1,mcdb) != 1))
  240. writeError = true;
  241. std::string c(i->second.toString());
  242. uint32_t cl = Utils::hton((uint32_t)c.length());
  243. if ((writeError)||(fwrite(&cl,sizeof(cl),1,mcdb) != 1))
  244. writeError = true;
  245. if ((writeError)||(fwrite(c.data(),c.length(),1,mcdb) != 1))
  246. writeError = true;
  247. }
  248. ++i;
  249. } else _membershipCertificates.erase(i++);
  250. }
  251. if (mcdb)
  252. fclose(mcdb);
  253. if (writeError) {
  254. Utils::rm(mcdbPath);
  255. LOG("error: unable to write to membership cert database at: %s",mcdbPath.c_str());
  256. }
  257. }
  258. }
  259. Network::Status Network::status() const
  260. {
  261. Mutex::Lock _l(_lock);
  262. if (_configuration)
  263. return NETWORK_OK;
  264. return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  265. }
  266. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  267. {
  268. if (!((Network *)arg)->_ready)
  269. return;
  270. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  271. if (_r->shutdownInProgress)
  272. return;
  273. try {
  274. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  275. } catch (std::exception &exc) {
  276. TRACE("unexpected exception handling local packet: %s",exc.what());
  277. } catch ( ... ) {
  278. TRACE("unexpected exception handling local packet");
  279. }
  280. }
  281. void Network::_restoreState()
  282. {
  283. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  284. std::string confs;
  285. if (Utils::readFile(confPath.c_str(),confs)) {
  286. try {
  287. if (confs.length())
  288. setConfiguration(Config(confs));
  289. } catch ( ... ) {} // ignore invalid config on disk, we will re-request
  290. } else {
  291. // If the conf file isn't present, "touch" it so we'll remember
  292. // the existence of this network.
  293. FILE *tmp = fopen(confPath.c_str(),"w");
  294. if (tmp)
  295. fclose(tmp);
  296. }
  297. // TODO: restore membership certs
  298. }
  299. } // namespace ZeroTier