JSONDB.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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.c_str());
  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. OSUtils::ztsnprintf(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(0,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. return (_networks.find(networkId) != _networks.end());
  104. }
  105. bool JSONDB::getNetwork(const uint64_t networkId,nlohmann::json &config) const
  106. {
  107. Mutex::Lock _l(_networks_m);
  108. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  109. if (i == _networks.end())
  110. return false;
  111. config = nlohmann::json::from_msgpack(i->second.config);
  112. return true;
  113. }
  114. bool JSONDB::getNetworkSummaryInfo(const uint64_t networkId,NetworkSummaryInfo &ns) const
  115. {
  116. Mutex::Lock _l(_networks_m);
  117. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  118. if (i == _networks.end())
  119. return false;
  120. ns = i->second.summaryInfo;
  121. return true;
  122. }
  123. int JSONDB::getNetworkAndMember(const uint64_t networkId,const uint64_t nodeId,nlohmann::json &networkConfig,nlohmann::json &memberConfig,NetworkSummaryInfo &ns) const
  124. {
  125. Mutex::Lock _l(_networks_m);
  126. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  127. if (i == _networks.end())
  128. return 0;
  129. const std::unordered_map< uint64_t,std::vector<uint8_t> >::const_iterator j(i->second.members.find(nodeId));
  130. if (j == i->second.members.end())
  131. return 1;
  132. networkConfig = nlohmann::json::from_msgpack(i->second.config);
  133. memberConfig = nlohmann::json::from_msgpack(j->second);
  134. ns = i->second.summaryInfo;
  135. return 3;
  136. }
  137. bool JSONDB::getNetworkMember(const uint64_t networkId,const uint64_t nodeId,nlohmann::json &memberConfig) const
  138. {
  139. Mutex::Lock _l(_networks_m);
  140. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  141. if (i == _networks.end())
  142. return false;
  143. const std::unordered_map< uint64_t,std::vector<uint8_t> >::const_iterator j(i->second.members.find(nodeId));
  144. if (j == i->second.members.end())
  145. return false;
  146. memberConfig = nlohmann::json::from_msgpack(j->second);
  147. return true;
  148. }
  149. void JSONDB::saveNetwork(const uint64_t networkId,const nlohmann::json &networkConfig)
  150. {
  151. char n[64];
  152. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  153. writeRaw(n,OSUtils::jsonDump(networkConfig));
  154. {
  155. Mutex::Lock _l(_networks_m);
  156. _networks[networkId].config = nlohmann::json::to_msgpack(networkConfig);
  157. }
  158. _recomputeSummaryInfo(networkId);
  159. }
  160. void JSONDB::saveNetworkMember(const uint64_t networkId,const uint64_t nodeId,const nlohmann::json &memberConfig)
  161. {
  162. char n[256];
  163. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  164. writeRaw(n,OSUtils::jsonDump(memberConfig));
  165. {
  166. Mutex::Lock _l(_networks_m);
  167. _networks[networkId].members[nodeId] = nlohmann::json::to_msgpack(memberConfig);
  168. }
  169. _recomputeSummaryInfo(networkId);
  170. }
  171. nlohmann::json JSONDB::eraseNetwork(const uint64_t networkId)
  172. {
  173. if (!_httpAddr) { // Member deletion is done by Central in harnessed mode, and deleting the cache network entry also deletes all members
  174. std::vector<uint64_t> memberIds;
  175. {
  176. Mutex::Lock _l(_networks_m);
  177. const std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  178. if (i == _networks.end())
  179. return _EMPTY_JSON;
  180. for(std::unordered_map< uint64_t,std::vector<uint8_t> >::iterator m(i->second.members.begin());m!=i->second.members.end();++m)
  181. memberIds.push_back(m->first);
  182. }
  183. for(std::vector<uint64_t>::iterator m(memberIds.begin());m!=memberIds.end();++m)
  184. eraseNetworkMember(networkId,*m,false);
  185. }
  186. char n[256];
  187. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  188. if (_httpAddr) {
  189. // Deletion is currently done by Central in harnessed mode
  190. //std::map<std::string,std::string> headers;
  191. //std::string body;
  192. //Http::DEL(0,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  193. } else {
  194. const std::string path(_genPath(n,false));
  195. if (path.length())
  196. OSUtils::rm(path.c_str());
  197. }
  198. {
  199. Mutex::Lock _l(_networks_m);
  200. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  201. if (i == _networks.end())
  202. return _EMPTY_JSON; // sanity check, shouldn't happen
  203. nlohmann::json tmp(nlohmann::json::from_msgpack(i->second.config));
  204. _networks.erase(i);
  205. return tmp;
  206. }
  207. }
  208. nlohmann::json JSONDB::eraseNetworkMember(const uint64_t networkId,const uint64_t nodeId,bool recomputeSummaryInfo)
  209. {
  210. char n[256];
  211. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  212. if (_httpAddr) {
  213. // Deletion is currently done by the caller in Central harnessed mode
  214. //std::map<std::string,std::string> headers;
  215. //std::string body;
  216. //Http::DEL(0,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  217. } else {
  218. const std::string path(_genPath(n,false));
  219. if (path.length())
  220. OSUtils::rm(path.c_str());
  221. }
  222. {
  223. Mutex::Lock _l(_networks_m);
  224. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  225. if (i == _networks.end())
  226. return _EMPTY_JSON;
  227. std::unordered_map< uint64_t,std::vector<uint8_t> >::iterator j(i->second.members.find(nodeId));
  228. if (j == i->second.members.end())
  229. return _EMPTY_JSON;
  230. nlohmann::json tmp(j->second);
  231. i->second.members.erase(j);
  232. if (recomputeSummaryInfo)
  233. _recomputeSummaryInfo(networkId);
  234. return tmp;
  235. }
  236. }
  237. void JSONDB::threadMain()
  238. throw()
  239. {
  240. std::vector<uint64_t> todo;
  241. while (_summaryThreadRun) {
  242. Thread::sleep(10);
  243. {
  244. Mutex::Lock _l(_summaryThread_m);
  245. if (_summaryThreadToDo.empty())
  246. continue;
  247. else _summaryThreadToDo.swap(todo);
  248. }
  249. const uint64_t now = OSUtils::now();
  250. for(std::vector<uint64_t>::iterator ii(todo.begin());ii!=todo.end();++ii) {
  251. const uint64_t networkId = *ii;
  252. Mutex::Lock _l(_networks_m);
  253. std::unordered_map<uint64_t,_NW>::iterator n(_networks.find(networkId));
  254. if (n != _networks.end()) {
  255. NetworkSummaryInfo &ns = n->second.summaryInfo;
  256. ns.activeBridges.clear();
  257. ns.allocatedIps.clear();
  258. ns.authorizedMemberCount = 0;
  259. ns.activeMemberCount = 0;
  260. ns.totalMemberCount = 0;
  261. ns.mostRecentDeauthTime = 0;
  262. for(std::unordered_map< uint64_t,std::vector<uint8_t> >::const_iterator m(n->second.members.begin());m!=n->second.members.end();++m) {
  263. try {
  264. nlohmann::json member(nlohmann::json::from_msgpack(m->second));
  265. if (OSUtils::jsonBool(member["authorized"],false)) {
  266. ++ns.authorizedMemberCount;
  267. try {
  268. const nlohmann::json &mlog = member["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(member["activeBridge"],false))
  279. ns.activeBridges.push_back(Address(m->first));
  280. } catch ( ... ) {}
  281. try {
  282. const nlohmann::json &mips = member["ipAssignments"];
  283. if (mips.is_array()) {
  284. for(unsigned long i=0;i<mips.size();++i) {
  285. InetAddress mip(OSUtils::jsonString(mips[i],"").c_str());
  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(member["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. // In HTTP harnessed mode we download our entire working data set on startup.
  311. std::string body;
  312. std::map<std::string,std::string> headers;
  313. const unsigned int sc = Http::GET(0,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),_basePath.c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  314. if (sc == 200) {
  315. try {
  316. nlohmann::json dbImg(OSUtils::jsonParse(body));
  317. std::string tmp;
  318. if (dbImg.is_object()) {
  319. Mutex::Lock _l(_networks_m);
  320. for(nlohmann::json::iterator i(dbImg.begin());i!=dbImg.end();++i) {
  321. nlohmann::json &j = i.value();
  322. if (j.is_object()) {
  323. std::string id(OSUtils::jsonString(j["id"],"0"));
  324. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  325. if ((id.length() == 16)&&(objtype == "network")) {
  326. const uint64_t nwid = Utils::hexStrToU64(id.c_str());
  327. if (nwid)
  328. _networks[nwid].config = nlohmann::json::to_msgpack(j);
  329. } else if ((id.length() == 10)&&(objtype == "member")) {
  330. const uint64_t mid = Utils::hexStrToU64(id.c_str());
  331. const uint64_t nwid = Utils::hexStrToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  332. if ((mid)&&(nwid))
  333. _networks[nwid].members[mid] = nlohmann::json::to_msgpack(j);
  334. }
  335. }
  336. }
  337. return true;
  338. }
  339. } catch ( ... ) {} // invalid JSON, so maybe incomplete request
  340. }
  341. return false;
  342. } else {
  343. // In regular mode we recursively read it from controller.d/ on disk
  344. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  345. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  346. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  347. std::string buf;
  348. if (OSUtils::readFile((p + ZT_PATH_SEPARATOR_S + *di).c_str(),buf)) {
  349. try {
  350. nlohmann::json j(OSUtils::jsonParse(buf));
  351. std::string id(OSUtils::jsonString(j["id"],"0"));
  352. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  353. if ((id.length() == 16)&&(objtype == "network")) {
  354. const uint64_t nwid = Utils::hexStrToU64(id.c_str());
  355. if (nwid) {
  356. Mutex::Lock _l(_networks_m);
  357. _networks[nwid].config = nlohmann::json::to_msgpack(j);
  358. }
  359. } else if ((id.length() == 10)&&(objtype == "member")) {
  360. const uint64_t mid = Utils::hexStrToU64(id.c_str());
  361. const uint64_t nwid = Utils::hexStrToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  362. if ((mid)&&(nwid)) {
  363. Mutex::Lock _l(_networks_m);
  364. _networks[nwid].members[mid] = nlohmann::json::to_msgpack(j);
  365. }
  366. }
  367. } catch ( ... ) {}
  368. }
  369. } else {
  370. this->_load((p + ZT_PATH_SEPARATOR_S + *di));
  371. }
  372. }
  373. return true;
  374. }
  375. }
  376. void JSONDB::_recomputeSummaryInfo(const uint64_t networkId)
  377. {
  378. Mutex::Lock _l(_summaryThread_m);
  379. if (std::find(_summaryThreadToDo.begin(),_summaryThreadToDo.end(),networkId) == _summaryThreadToDo.end())
  380. _summaryThreadToDo.push_back(networkId);
  381. if (!_summaryThread)
  382. _summaryThread = Thread::start(this);
  383. }
  384. std::string JSONDB::_genPath(const std::string &n,bool create)
  385. {
  386. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  387. if (pt.size() == 0)
  388. return std::string();
  389. char sep;
  390. if (_httpAddr) {
  391. sep = '/';
  392. create = false;
  393. } else {
  394. sep = ZT_PATH_SEPARATOR;
  395. }
  396. std::string p(_basePath);
  397. if (create) OSUtils::mkdir(p.c_str());
  398. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  399. p.push_back(sep);
  400. p.append(pt[i]);
  401. if (create) OSUtils::mkdir(p.c_str());
  402. }
  403. p.push_back(sep);
  404. p.append(pt[pt.size()-1]);
  405. p.append(".json");
  406. return p;
  407. }
  408. } // namespace ZeroTier