NodeConfig.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 <memory>
  30. #include <string>
  31. #include <json/json.h>
  32. #include "NodeConfig.hpp"
  33. #include "RuntimeEnvironment.hpp"
  34. #include "Defaults.hpp"
  35. #include "Utils.hpp"
  36. #include "Logger.hpp"
  37. namespace ZeroTier {
  38. NodeConfig::NodeConfig(const RuntimeEnvironment *renv,const std::string &url) :
  39. _r(renv),
  40. _lastAutoconfigure(0),
  41. _lastAutoconfigureLastModified(),
  42. _url(url),
  43. _autoconfigureLock(),
  44. _networks(),
  45. _networks_m()
  46. {
  47. }
  48. NodeConfig::~NodeConfig()
  49. {
  50. _autoconfigureLock.lock(); // wait for any autoconfs to finish
  51. _autoconfigureLock.unlock();
  52. }
  53. void NodeConfig::whackAllTaps()
  54. {
  55. std::vector< SharedPtr<Network> > nwlist;
  56. Mutex::Lock _l(_networks_m);
  57. for(std::map< uint64_t,SharedPtr<Network> >::const_iterator n(_networks.begin());n!=_networks.end();++n)
  58. n->second->tap().whack();
  59. }
  60. void NodeConfig::refreshConfiguration()
  61. {
  62. _autoconfigureLock.lock(); // unlocked when handler gets called
  63. TRACE("refreshing autoconfigure URL %s (if modified since: '%s')",_url.c_str(),_lastAutoconfigureLastModified.c_str());
  64. std::map<std::string,std::string> reqHeaders;
  65. reqHeaders["X-ZT-ID"] = _r->identity.toString(false);
  66. reqHeaders["X-ZT-OVSH"] = _r->ownershipVerificationSecretHash;
  67. if (_lastAutoconfigureLastModified.length())
  68. reqHeaders["If-Modified-Since"] = _lastAutoconfigureLastModified;
  69. new Http::Request(Http::HTTP_METHOD_GET,_url,reqHeaders,std::string(),&NodeConfig::_CBautoconfHandler,this);
  70. }
  71. void NodeConfig::__CBautoconfHandler(const std::string &lastModified,const std::string &body)
  72. {
  73. try {
  74. Json::Value root;
  75. Json::Reader reader;
  76. std::string dec(_r->identity.decrypt(_r->configAuthority,body.data(),body.length()));
  77. if (!dec.length()) {
  78. LOG("autoconfigure from %s failed: data did not decrypt as from config authority %s",_url.c_str(),_r->configAuthority.address().toString().c_str());
  79. return;
  80. }
  81. TRACE("decrypted autoconf: %s",dec.c_str());
  82. if (!reader.parse(dec,root,false)) {
  83. LOG("autoconfigure from %s failed: JSON parse error: %s",_url.c_str(),reader.getFormattedErrorMessages().c_str());
  84. return;
  85. }
  86. if (!root.isObject()) {
  87. LOG("autoconfigure from %s failed: not a JSON object",_url.c_str());
  88. return;
  89. }
  90. // Configure networks
  91. const Json::Value &networks = root["_networks"];
  92. if (networks.isArray()) {
  93. Mutex::Lock _l(_networks_m);
  94. for(unsigned int ni=0;ni<networks.size();++ni) {
  95. if (networks[ni].isObject()) {
  96. const Json::Value &nwid_ = networks[ni]["id"];
  97. uint64_t nwid = nwid_.isNumeric() ? (uint64_t)nwid_.asUInt64() : (uint64_t)strtoull(networks[ni]["id"].asString().c_str(),(char **)0,10);
  98. if (nwid) {
  99. SharedPtr<Network> nw;
  100. std::map< uint64_t,SharedPtr<Network> >::iterator nwent(_networks.find(nwid));
  101. if (nwent != _networks.end())
  102. nw = nwent->second;
  103. else {
  104. try {
  105. nw = SharedPtr<Network>(new Network(_r,nwid));
  106. _networks[nwid] = nw;
  107. } catch (std::exception &exc) {
  108. LOG("unable to create network %llu: %s",nwid,exc.what());
  109. } catch ( ... ) {
  110. LOG("unable to create network %llu: unknown exception",nwid);
  111. }
  112. }
  113. if (nw) {
  114. Mutex::Lock _l2(nw->_lock);
  115. nw->_open = networks[ni]["isOpen"].asBool();
  116. // Ensure that TAP device has all the right IP addresses
  117. // TODO: IPv6 might work a tad differently
  118. std::set<InetAddress> allIps;
  119. const Json::Value &addresses = networks[ni]["_addresses"];
  120. if (addresses.isArray()) {
  121. for(unsigned int ai=0;ai<addresses.size();++ai) {
  122. if (addresses[ai].isString()) {
  123. InetAddress addr(addresses[ai].asString());
  124. if (addr) {
  125. TRACE("network %llu IP/netmask: %s",nwid,addr.toString().c_str());
  126. allIps.insert(addr);
  127. }
  128. }
  129. }
  130. }
  131. nw->_tap.setIps(allIps);
  132. // NOTE: the _members field is optional for open networks,
  133. // since members of open nets do not need to check membership
  134. // of packet senders and mutlicasters.
  135. const Json::Value &members = networks[ni]["_members"];
  136. nw->_members.clear();
  137. if (members.isArray()) {
  138. for(unsigned int mi=0;mi<members.size();++mi) {
  139. std::string rawAddr(Utils::unhex(members[mi].asString()));
  140. if (rawAddr.length() == ZT_ADDRESS_LENGTH) {
  141. Address addr(rawAddr.data());
  142. if ((addr)&&(!addr.isReserved())) {
  143. //TRACE("network %llu member: %s",nwid,addr.toString().c_str());
  144. nw->_members.insert(addr);
  145. }
  146. }
  147. }
  148. }
  149. }
  150. } else {
  151. TRACE("ignored networks[%u], 'id' field missing");
  152. }
  153. } else {
  154. TRACE("ignored networks[%u], not a JSON object",ni);
  155. }
  156. }
  157. }
  158. _lastAutoconfigure = Utils::now();
  159. _lastAutoconfigureLastModified = lastModified;
  160. } catch (std::exception &exc) {
  161. TRACE("exception parsing autoconf URL response: %s",exc.what());
  162. } catch ( ... ) {
  163. TRACE("unexpected exception parsing autoconf URL response");
  164. }
  165. }
  166. bool NodeConfig::_CBautoconfHandler(Http::Request *req,void *arg,const std::string &url,int code,const std::map<std::string,std::string> &headers,const std::string &body)
  167. {
  168. #ifdef ZT_TRACE
  169. const RuntimeEnvironment *_r = ((NodeConfig *)arg)->_r;
  170. #endif
  171. if (code == 200) {
  172. TRACE("200 got autoconfigure response from %s: %u bytes",url.c_str(),(unsigned int)body.length());
  173. std::map<std::string,std::string>::const_iterator lm(headers.find("Last-Modified"));
  174. if (lm != headers.end())
  175. ((NodeConfig *)arg)->__CBautoconfHandler(lm->second,body);
  176. else ((NodeConfig *)arg)->__CBautoconfHandler(std::string(),body);
  177. } else if (code == 304) {
  178. TRACE("304 autoconfigure deferred, remote URL %s not modified",url.c_str());
  179. ((NodeConfig *)arg)->_lastAutoconfigure = Utils::now(); // still considered a success
  180. } else if (code == 409) { // conflict, ID address in use by another ID
  181. TRACE("%d autoconfigure failed from %s",code,url.c_str());
  182. } else {
  183. TRACE("%d autoconfigure failed from %s",code,url.c_str());
  184. }
  185. ((NodeConfig *)arg)->_autoconfigureLock.unlock();
  186. return false; // causes Request to delete itself
  187. }
  188. } // namespace ZeroTier