NodeConfig.cpp 6.9 KB

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