JSONDB.cpp 14 KB

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