JSONDB.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. #include "JSONDB.hpp"
  19. #define ZT_JSONDB_HTTP_TIMEOUT 60000
  20. namespace ZeroTier {
  21. static const nlohmann::json _EMPTY_JSON(nlohmann::json::object());
  22. static const std::map<std::string,std::string> _ZT_JSONDB_GET_HEADERS;
  23. JSONDB::JSONDB(const std::string &basePath) :
  24. _basePath(basePath)
  25. {
  26. if ((_basePath.length() > 7)&&(_basePath.substr(0,7) == "http://")) {
  27. // TODO: this doesn't yet support IPv6 since bracketed address notiation isn't supported.
  28. // Typically it's just used with 127.0.0.1 anyway.
  29. std::string hn = _basePath.substr(7);
  30. std::size_t hnend = hn.find_first_of('/');
  31. if (hnend != std::string::npos)
  32. hn = hn.substr(0,hnend);
  33. std::size_t hnsep = hn.find_last_of(':');
  34. if (hnsep != std::string::npos)
  35. hn[hnsep] = '/';
  36. _httpAddr.fromString(hn);
  37. if (hnend != std::string::npos)
  38. _basePath = _basePath.substr(7 + hnend);
  39. if (_basePath.length() == 0)
  40. _basePath = "/";
  41. if (_basePath[0] != '/')
  42. _basePath = std::string("/") + _basePath;
  43. } else {
  44. OSUtils::mkdir(_basePath.c_str());
  45. OSUtils::lockDownFile(_basePath.c_str(),true); // networks might contain auth tokens, etc., so restrict directory permissions
  46. }
  47. unsigned int cnt = 0;
  48. while (!_load(_basePath)) {
  49. if ((++cnt & 7) == 0)
  50. fprintf(stderr,"WARNING: controller still waiting to read '%s'..." ZT_EOL_S,_basePath.c_str());
  51. Thread::sleep(250);
  52. }
  53. for(std::unordered_map<uint64_t,_NW>::iterator n(_networks.begin());n!=_networks.end();++n)
  54. _recomputeSummaryInfo(n->first);
  55. }
  56. JSONDB::~JSONDB()
  57. {
  58. {
  59. Mutex::Lock _l(_networks_m);
  60. _networks.clear();
  61. }
  62. {
  63. Mutex::Lock _l(_summaryThread_m);
  64. if (_summaryThread) {
  65. _updateSummaryInfoQueue.post(0);
  66. _updateSummaryInfoQueue.post(0);
  67. Thread::join(_summaryThread);
  68. }
  69. }
  70. }
  71. bool JSONDB::writeRaw(const std::string &n,const std::string &obj)
  72. {
  73. if (_httpAddr) {
  74. std::map<std::string,std::string> headers;
  75. std::string body;
  76. std::map<std::string,std::string> reqHeaders;
  77. char tmp[64];
  78. Utils::snprintf(tmp,sizeof(tmp),"%lu",(unsigned long)obj.length());
  79. reqHeaders["Content-Length"] = tmp;
  80. reqHeaders["Content-Type"] = "application/json";
  81. const unsigned int sc = Http::PUT(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),reqHeaders,obj.data(),(unsigned long)obj.length(),headers,body);
  82. return (sc == 200);
  83. } else {
  84. const std::string path(_genPath(n,true));
  85. if (!path.length())
  86. return false;
  87. return OSUtils::writeFile(path.c_str(),obj);
  88. }
  89. }
  90. void JSONDB::saveNetwork(const uint64_t networkId,const nlohmann::json &networkConfig)
  91. {
  92. char n[256];
  93. Utils::snprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  94. writeRaw(n,OSUtils::jsonDump(networkConfig));
  95. {
  96. Mutex::Lock _l(_networks_m);
  97. _networks[networkId].config = networkConfig;
  98. }
  99. //_recomputeSummaryInfo(networkId);
  100. }
  101. void JSONDB::saveNetworkMember(const uint64_t networkId,const uint64_t nodeId,const nlohmann::json &memberConfig)
  102. {
  103. char n[256];
  104. Utils::snprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  105. writeRaw(n,OSUtils::jsonDump(memberConfig));
  106. {
  107. Mutex::Lock _l(_networks_m);
  108. _networks[networkId].members[nodeId] = memberConfig;
  109. }
  110. _recomputeSummaryInfo(networkId);
  111. }
  112. nlohmann::json JSONDB::eraseNetwork(const uint64_t networkId)
  113. {
  114. if (!_httpAddr) { // Member deletion is done by Central in harnessed mode, and deleting the cache network entry also deletes all members
  115. std::vector<uint64_t> memberIds;
  116. {
  117. Mutex::Lock _l(_networks_m);
  118. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  119. if (i == _networks.end())
  120. return _EMPTY_JSON;
  121. for(std::unordered_map<uint64_t,nlohmann::json>::iterator m(i->second.members.begin());m!=i->second.members.end();++m)
  122. memberIds.push_back(m->first);
  123. }
  124. for(std::vector<uint64_t>::iterator m(memberIds.begin());m!=memberIds.end();++m)
  125. eraseNetworkMember(networkId,*m,false);
  126. }
  127. char n[256];
  128. Utils::snprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  129. if (_httpAddr) {
  130. // Deletion is currently done by Central in harnessed mode
  131. //std::map<std::string,std::string> headers;
  132. //std::string body;
  133. //Http::DEL(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  134. } else {
  135. const std::string path(_genPath(n,false));
  136. if (path.length())
  137. OSUtils::rm(path.c_str());
  138. }
  139. {
  140. Mutex::Lock _l(_networks_m);
  141. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  142. if (i == _networks.end())
  143. return _EMPTY_JSON; // sanity check, shouldn't happen
  144. nlohmann::json tmp(i->second.config);
  145. _networks.erase(i);
  146. return tmp;
  147. }
  148. }
  149. nlohmann::json JSONDB::eraseNetworkMember(const uint64_t networkId,const uint64_t nodeId,bool recomputeSummaryInfo)
  150. {
  151. char n[256];
  152. Utils::snprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  153. if (_httpAddr) {
  154. // Deletion is currently done by the caller in Central harnessed mode
  155. //std::map<std::string,std::string> headers;
  156. //std::string body;
  157. //Http::DEL(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  158. } else {
  159. const std::string path(_genPath(n,false));
  160. if (path.length())
  161. OSUtils::rm(path.c_str());
  162. }
  163. {
  164. Mutex::Lock _l(_networks_m);
  165. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  166. if (i == _networks.end())
  167. return _EMPTY_JSON;
  168. std::unordered_map<uint64_t,nlohmann::json>::iterator j(i->second.members.find(nodeId));
  169. if (j == i->second.members.end())
  170. return _EMPTY_JSON;
  171. nlohmann::json tmp(j->second);
  172. i->second.members.erase(j);
  173. if (recomputeSummaryInfo)
  174. _recomputeSummaryInfo(networkId);
  175. return tmp;
  176. }
  177. }
  178. void JSONDB::threadMain()
  179. throw()
  180. {
  181. uint64_t networkId = 0;
  182. while ((networkId = _updateSummaryInfoQueue.get()) != 0) {
  183. const uint64_t now = OSUtils::now();
  184. {
  185. Mutex::Lock _l(_networks_m);
  186. std::unordered_map<uint64_t,_NW>::iterator n(_networks.find(networkId));
  187. if (n != _networks.end()) {
  188. NetworkSummaryInfo &ns = n->second.summaryInfo;
  189. ns.activeBridges.clear();
  190. ns.allocatedIps.clear();
  191. ns.authorizedMemberCount = 0;
  192. ns.activeMemberCount = 0;
  193. ns.totalMemberCount = 0;
  194. ns.mostRecentDeauthTime = 0;
  195. for(std::unordered_map<uint64_t,nlohmann::json>::const_iterator m(n->second.members.begin());m!=n->second.members.end();++m) {
  196. try {
  197. if (OSUtils::jsonBool(m->second["authorized"],false)) {
  198. ++ns.authorizedMemberCount;
  199. try {
  200. const nlohmann::json &mlog = m->second["recentLog"];
  201. if ((mlog.is_array())&&(mlog.size() > 0)) {
  202. const nlohmann::json &mlog1 = mlog[0];
  203. if (mlog1.is_object()) {
  204. if ((now - OSUtils::jsonInt(mlog1["ts"],0ULL)) < (ZT_NETWORK_AUTOCONF_DELAY * 2))
  205. ++ns.activeMemberCount;
  206. }
  207. }
  208. } catch ( ... ) {}
  209. try {
  210. if (OSUtils::jsonBool(m->second["activeBridge"],false))
  211. ns.activeBridges.push_back(Address(m->first));
  212. } catch ( ... ) {}
  213. try {
  214. const nlohmann::json &mips = m->second["ipAssignments"];
  215. if (mips.is_array()) {
  216. for(unsigned long i=0;i<mips.size();++i) {
  217. InetAddress mip(OSUtils::jsonString(mips[i],""));
  218. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  219. ns.allocatedIps.push_back(mip);
  220. }
  221. }
  222. } catch ( ... ) {}
  223. } else {
  224. try {
  225. ns.mostRecentDeauthTime = std::max(ns.mostRecentDeauthTime,OSUtils::jsonInt(m->second["lastDeauthorizedTime"],0ULL));
  226. } catch ( ... ) {}
  227. }
  228. ++ns.totalMemberCount;
  229. } catch ( ... ) {}
  230. }
  231. std::sort(ns.activeBridges.begin(),ns.activeBridges.end());
  232. std::sort(ns.allocatedIps.begin(),ns.allocatedIps.end());
  233. n->second.summaryInfoLastComputed = now;
  234. }
  235. }
  236. }
  237. }
  238. bool JSONDB::_load(const std::string &p)
  239. {
  240. if (_httpAddr) {
  241. std::string body;
  242. std::map<std::string,std::string> headers;
  243. const unsigned int sc = Http::GET(2147483647,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),_basePath.c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  244. if (sc == 200) {
  245. try {
  246. nlohmann::json dbImg(OSUtils::jsonParse(body));
  247. std::string tmp;
  248. if (dbImg.is_object()) {
  249. Mutex::Lock _l(_networks_m);
  250. for(nlohmann::json::iterator i(dbImg.begin());i!=dbImg.end();++i) {
  251. nlohmann::json &j = i.value();
  252. if (j.is_object()) {
  253. std::string id(OSUtils::jsonString(j["id"],"0"));
  254. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  255. if ((id.length() == 16)&&(objtype == "network")) {
  256. const uint64_t nwid = Utils::hexStrToU64(id.c_str());
  257. if (nwid)
  258. _networks[nwid].config = j;
  259. } else if ((id.length() == 10)&&(objtype == "member")) {
  260. const uint64_t mid = Utils::hexStrToU64(id.c_str());
  261. const uint64_t nwid = Utils::hexStrToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  262. if ((mid)&&(nwid))
  263. _networks[nwid].members[mid] = j;
  264. }
  265. }
  266. }
  267. return true;
  268. }
  269. } catch ( ... ) {} // invalid JSON, so maybe incomplete request
  270. }
  271. return false;
  272. } else {
  273. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  274. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  275. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  276. std::string buf;
  277. if (OSUtils::readFile((p + ZT_PATH_SEPARATOR_S + *di).c_str(),buf)) {
  278. try {
  279. nlohmann::json j(OSUtils::jsonParse(buf));
  280. std::string id(OSUtils::jsonString(j["id"],"0"));
  281. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  282. if ((id.length() == 16)&&(objtype == "network")) {
  283. const uint64_t nwid = Utils::strToU64(id.c_str());
  284. if (nwid) {
  285. Mutex::Lock _l(_networks_m);
  286. _networks[nwid].config = j;
  287. }
  288. } else if ((id.length() == 10)&&(objtype == "member")) {
  289. const uint64_t mid = Utils::strToU64(id.c_str());
  290. const uint64_t nwid = Utils::strToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  291. if ((mid)&&(nwid)) {
  292. Mutex::Lock _l(_networks_m);
  293. _networks[nwid].members[mid] = j;
  294. }
  295. }
  296. } catch ( ... ) {}
  297. }
  298. } else {
  299. this->_load((p + ZT_PATH_SEPARATOR_S + *di));
  300. }
  301. }
  302. return true;
  303. }
  304. }
  305. void JSONDB::_recomputeSummaryInfo(const uint64_t networkId)
  306. {
  307. Mutex::Lock _l(_summaryThread_m);
  308. if (!_summaryThread)
  309. _summaryThread = Thread::start(this);
  310. _updateSummaryInfoQueue.post(networkId);
  311. }
  312. std::string JSONDB::_genPath(const std::string &n,bool create)
  313. {
  314. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  315. if (pt.size() == 0)
  316. return std::string();
  317. char sep;
  318. if (_httpAddr) {
  319. sep = '/';
  320. create = false;
  321. } else {
  322. sep = ZT_PATH_SEPARATOR;
  323. }
  324. std::string p(_basePath);
  325. if (create) OSUtils::mkdir(p.c_str());
  326. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  327. p.push_back(sep);
  328. p.append(pt[i]);
  329. if (create) OSUtils::mkdir(p.c_str());
  330. }
  331. p.push_back(sep);
  332. p.append(pt[pt.size()-1]);
  333. p.append(".json");
  334. return p;
  335. }
  336. } // namespace ZeroTier