Network.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. void Network::pushMembershipCertificate(const Address &peer,bool force,uint64_t now)
  151. {
  152. Mutex::Lock _l(_lock);
  153. if (_isOpen)
  154. return;
  155. uint64_t timestampMaxDelta = _myCertificate.timestampMaxDelta();
  156. if (!timestampMaxDelta) {
  157. LOG("unable to push my certificate to %s for network %.16llx: certificate invalid, missing required timestamp field",peer.toString().c_str(),_id);
  158. return; // required field missing!
  159. }
  160. uint64_t &lastPushed = _lastPushedMembershipCertificate[peer];
  161. if ((force)||((now - lastPushed) > (timestampMaxDelta / 2))) {
  162. lastPushed = now;
  163. Packet outp(peer,_r->identity.address(),Packet::VERB_NETWORK_MEMBERSHIP_CERTIFICATE);
  164. outp.append((uint64_t)_id);
  165. _myCertificate.serialize(outp);
  166. _r->sw->send(outp,true);
  167. }
  168. }
  169. bool Network::isAllowed(const Address &peer) const
  170. {
  171. // Exceptions can occur if we do not yet have *our* configuration.
  172. try {
  173. Mutex::Lock _l(_lock);
  174. if (_isOpen)
  175. return true;
  176. std::map<Address,CertificateOfMembership>::const_iterator pc(_membershipCertificates.find(peer));
  177. if (pc == _membershipCertificates.end())
  178. return false;
  179. return _myCertificate.agreesWith(pc->second);
  180. } catch (std::exception &exc) {
  181. TRACE("isAllowed() check failed for peer %s: unexpected exception: %s",peer.toString().c_str(),exc.what());
  182. } catch ( ... ) {
  183. TRACE("isAllowed() check failed for peer %s: unexpected exception: unknown exception",peer.toString().c_str());
  184. }
  185. return false;
  186. }
  187. void Network::clean()
  188. {
  189. std::string mcdbPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".mcerts");
  190. Mutex::Lock _l(_lock);
  191. if ((!_id)||(_isOpen)) {
  192. _membershipCertificates.clear();
  193. Utils::rm(mcdbPath);
  194. } else {
  195. FILE *mcdb = fopen(mcdbPath.c_str(),"wb");
  196. bool writeError = false;
  197. if (!mcdb) {
  198. LOG("error: unable to open membership cert database at: %s",mcdbPath.c_str());
  199. } else {
  200. if ((writeError)||(fwrite("MCDB0",5,1,mcdb) != 1)) // version
  201. writeError = true;
  202. }
  203. for(std::map<Address,CertificateOfMembership>::iterator i=(_membershipCertificates.begin());i!=_membershipCertificates.end();) {
  204. if (_myCertificate.agreesWith(i->second)) {
  205. if ((!writeError)&&(mcdb)) {
  206. char tmp[ZT_ADDRESS_LENGTH];
  207. i->first.copyTo(tmp,ZT_ADDRESS_LENGTH);
  208. if ((writeError)||(fwrite(tmp,ZT_ADDRESS_LENGTH,1,mcdb) != 1))
  209. writeError = true;
  210. std::string c(i->second.toString());
  211. uint32_t cl = Utils::hton((uint32_t)c.length());
  212. if ((writeError)||(fwrite(&cl,sizeof(cl),1,mcdb) != 1))
  213. writeError = true;
  214. if ((writeError)||(fwrite(c.data(),c.length(),1,mcdb) != 1))
  215. writeError = true;
  216. }
  217. ++i;
  218. } else _membershipCertificates.erase(i++);
  219. }
  220. if (mcdb)
  221. fclose(mcdb);
  222. if (writeError) {
  223. Utils::rm(mcdbPath);
  224. LOG("error: unable to write to membership cert database at: %s",mcdbPath.c_str());
  225. }
  226. }
  227. }
  228. Network::Status Network::status() const
  229. {
  230. Mutex::Lock _l(_lock);
  231. if (_configuration)
  232. return NETWORK_OK;
  233. return NETWORK_WAITING_FOR_FIRST_AUTOCONF;
  234. }
  235. void Network::_CBhandleTapData(void *arg,const MAC &from,const MAC &to,unsigned int etherType,const Buffer<4096> &data)
  236. {
  237. if (!((Network *)arg)->_ready)
  238. return;
  239. const RuntimeEnvironment *_r = ((Network *)arg)->_r;
  240. if (_r->shutdownInProgress)
  241. return;
  242. try {
  243. _r->sw->onLocalEthernet(SharedPtr<Network>((Network *)arg),from,to,etherType,data);
  244. } catch (std::exception &exc) {
  245. TRACE("unexpected exception handling local packet: %s",exc.what());
  246. } catch ( ... ) {
  247. TRACE("unexpected exception handling local packet");
  248. }
  249. }
  250. void Network::_restoreState()
  251. {
  252. std::string confPath(_r->homePath + ZT_PATH_SEPARATOR_S + "networks.d" + ZT_PATH_SEPARATOR_S + idString() + ".conf");
  253. std::string confs;
  254. if (Utils::readFile(confPath.c_str(),confs)) {
  255. try {
  256. if (confs.length())
  257. setConfiguration(Config(confs));
  258. } catch ( ... ) {} // ignore invalid config on disk, we will re-request
  259. } else {
  260. // If the conf file isn't present, "touch" it so we'll remember
  261. // the existence of this network.
  262. FILE *tmp = fopen(confPath.c_str(),"w");
  263. if (tmp)
  264. fclose(tmp);
  265. }
  266. // TODO: restore membership certs
  267. }
  268. } // namespace ZeroTier