Network.cpp 10.0 KB

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