JSONDB.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. void JSONDB::saveNetwork(const uint64_t networkId,const nlohmann::json &networkConfig)
  101. {
  102. char n[256];
  103. Utils::snprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  104. writeRaw(n,OSUtils::jsonDump(networkConfig));
  105. {
  106. Mutex::Lock _l(_networks_m);
  107. _networks[networkId].config = networkConfig;
  108. }
  109. _recomputeSummaryInfo(networkId);
  110. }
  111. void JSONDB::saveNetworkMember(const uint64_t networkId,const uint64_t nodeId,const nlohmann::json &memberConfig)
  112. {
  113. char n[256];
  114. Utils::snprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  115. writeRaw(n,OSUtils::jsonDump(memberConfig));
  116. {
  117. Mutex::Lock _l(_networks_m);
  118. _networks[networkId].members[nodeId] = memberConfig;
  119. }
  120. _recomputeSummaryInfo(networkId);
  121. }
  122. nlohmann::json JSONDB::eraseNetwork(const uint64_t networkId)
  123. {
  124. if (!_httpAddr) { // Member deletion is done by Central in harnessed mode, and deleting the cache network entry also deletes all members
  125. std::vector<uint64_t> memberIds;
  126. {
  127. Mutex::Lock _l(_networks_m);
  128. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  129. if (i == _networks.end())
  130. return _EMPTY_JSON;
  131. for(std::unordered_map<uint64_t,nlohmann::json>::iterator m(i->second.members.begin());m!=i->second.members.end();++m)
  132. memberIds.push_back(m->first);
  133. }
  134. for(std::vector<uint64_t>::iterator m(memberIds.begin());m!=memberIds.end();++m)
  135. eraseNetworkMember(networkId,*m,false);
  136. }
  137. char n[256];
  138. Utils::snprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  139. if (_httpAddr) {
  140. // Deletion is currently done by Central in harnessed mode
  141. //std::map<std::string,std::string> headers;
  142. //std::string body;
  143. //Http::DEL(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  144. } else {
  145. const std::string path(_genPath(n,false));
  146. if (path.length())
  147. OSUtils::rm(path.c_str());
  148. }
  149. {
  150. Mutex::Lock _l(_networks_m);
  151. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  152. if (i == _networks.end())
  153. return _EMPTY_JSON; // sanity check, shouldn't happen
  154. nlohmann::json tmp(i->second.config);
  155. _networks.erase(i);
  156. return tmp;
  157. }
  158. }
  159. nlohmann::json JSONDB::eraseNetworkMember(const uint64_t networkId,const uint64_t nodeId,bool recomputeSummaryInfo)
  160. {
  161. char n[256];
  162. Utils::snprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  163. if (_httpAddr) {
  164. // Deletion is currently done by the caller in Central harnessed mode
  165. //std::map<std::string,std::string> headers;
  166. //std::string body;
  167. //Http::DEL(1048576,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  168. } else {
  169. const std::string path(_genPath(n,false));
  170. if (path.length())
  171. OSUtils::rm(path.c_str());
  172. }
  173. {
  174. Mutex::Lock _l(_networks_m);
  175. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  176. if (i == _networks.end())
  177. return _EMPTY_JSON;
  178. std::unordered_map<uint64_t,nlohmann::json>::iterator j(i->second.members.find(nodeId));
  179. if (j == i->second.members.end())
  180. return _EMPTY_JSON;
  181. nlohmann::json tmp(j->second);
  182. i->second.members.erase(j);
  183. if (recomputeSummaryInfo)
  184. _recomputeSummaryInfo(networkId);
  185. return tmp;
  186. }
  187. }
  188. void JSONDB::threadMain()
  189. throw()
  190. {
  191. std::vector<uint64_t> todo;
  192. while (_summaryThreadRun) {
  193. Thread::sleep(10);
  194. {
  195. Mutex::Lock _l(_summaryThread_m);
  196. if (_summaryThreadToDo.empty())
  197. continue;
  198. else _summaryThreadToDo.swap(todo);
  199. }
  200. const uint64_t now = OSUtils::now();
  201. for(std::vector<uint64_t>::iterator ii(todo.begin());ii!=todo.end();++ii) {
  202. const uint64_t networkId = *ii;
  203. Mutex::Lock _l(_networks_m);
  204. std::unordered_map<uint64_t,_NW>::iterator n(_networks.find(networkId));
  205. if (n != _networks.end()) {
  206. NetworkSummaryInfo &ns = n->second.summaryInfo;
  207. ns.activeBridges.clear();
  208. ns.allocatedIps.clear();
  209. ns.authorizedMemberCount = 0;
  210. ns.activeMemberCount = 0;
  211. ns.totalMemberCount = 0;
  212. ns.mostRecentDeauthTime = 0;
  213. for(std::unordered_map<uint64_t,nlohmann::json>::const_iterator m(n->second.members.begin());m!=n->second.members.end();++m) {
  214. try {
  215. if (OSUtils::jsonBool(m->second["authorized"],false)) {
  216. ++ns.authorizedMemberCount;
  217. try {
  218. const nlohmann::json &mlog = m->second["recentLog"];
  219. if ((mlog.is_array())&&(mlog.size() > 0)) {
  220. const nlohmann::json &mlog1 = mlog[0];
  221. if (mlog1.is_object()) {
  222. if ((now - OSUtils::jsonInt(mlog1["ts"],0ULL)) < (ZT_NETWORK_AUTOCONF_DELAY * 2))
  223. ++ns.activeMemberCount;
  224. }
  225. }
  226. } catch ( ... ) {}
  227. try {
  228. if (OSUtils::jsonBool(m->second["activeBridge"],false))
  229. ns.activeBridges.push_back(Address(m->first));
  230. } catch ( ... ) {}
  231. try {
  232. const nlohmann::json &mips = m->second["ipAssignments"];
  233. if (mips.is_array()) {
  234. for(unsigned long i=0;i<mips.size();++i) {
  235. InetAddress mip(OSUtils::jsonString(mips[i],""));
  236. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  237. ns.allocatedIps.push_back(mip);
  238. }
  239. }
  240. } catch ( ... ) {}
  241. } else {
  242. try {
  243. ns.mostRecentDeauthTime = std::max(ns.mostRecentDeauthTime,OSUtils::jsonInt(m->second["lastDeauthorizedTime"],0ULL));
  244. } catch ( ... ) {}
  245. }
  246. ++ns.totalMemberCount;
  247. } catch ( ... ) {}
  248. }
  249. std::sort(ns.activeBridges.begin(),ns.activeBridges.end());
  250. std::sort(ns.allocatedIps.begin(),ns.allocatedIps.end());
  251. n->second.summaryInfoLastComputed = now;
  252. }
  253. }
  254. todo.clear();
  255. }
  256. }
  257. bool JSONDB::_load(const std::string &p)
  258. {
  259. if (_httpAddr) {
  260. std::string body;
  261. std::map<std::string,std::string> headers;
  262. 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);
  263. if (sc == 200) {
  264. try {
  265. nlohmann::json dbImg(OSUtils::jsonParse(body));
  266. std::string tmp;
  267. if (dbImg.is_object()) {
  268. Mutex::Lock _l(_networks_m);
  269. for(nlohmann::json::iterator i(dbImg.begin());i!=dbImg.end();++i) {
  270. nlohmann::json &j = i.value();
  271. if (j.is_object()) {
  272. std::string id(OSUtils::jsonString(j["id"],"0"));
  273. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  274. if ((id.length() == 16)&&(objtype == "network")) {
  275. const uint64_t nwid = Utils::hexStrToU64(id.c_str());
  276. if (nwid)
  277. _networks[nwid].config = j;
  278. } else if ((id.length() == 10)&&(objtype == "member")) {
  279. const uint64_t mid = Utils::hexStrToU64(id.c_str());
  280. const uint64_t nwid = Utils::hexStrToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  281. if ((mid)&&(nwid))
  282. _networks[nwid].members[mid] = j;
  283. }
  284. }
  285. }
  286. return true;
  287. }
  288. } catch ( ... ) {} // invalid JSON, so maybe incomplete request
  289. }
  290. return false;
  291. } else {
  292. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  293. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  294. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  295. std::string buf;
  296. if (OSUtils::readFile((p + ZT_PATH_SEPARATOR_S + *di).c_str(),buf)) {
  297. try {
  298. nlohmann::json j(OSUtils::jsonParse(buf));
  299. std::string id(OSUtils::jsonString(j["id"],"0"));
  300. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  301. if ((id.length() == 16)&&(objtype == "network")) {
  302. const uint64_t nwid = Utils::strToU64(id.c_str());
  303. if (nwid) {
  304. Mutex::Lock _l(_networks_m);
  305. _networks[nwid].config = j;
  306. }
  307. } else if ((id.length() == 10)&&(objtype == "member")) {
  308. const uint64_t mid = Utils::strToU64(id.c_str());
  309. const uint64_t nwid = Utils::strToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  310. if ((mid)&&(nwid)) {
  311. Mutex::Lock _l(_networks_m);
  312. _networks[nwid].members[mid] = j;
  313. }
  314. }
  315. } catch ( ... ) {}
  316. }
  317. } else {
  318. this->_load((p + ZT_PATH_SEPARATOR_S + *di));
  319. }
  320. }
  321. return true;
  322. }
  323. }
  324. void JSONDB::_recomputeSummaryInfo(const uint64_t networkId)
  325. {
  326. Mutex::Lock _l(_summaryThread_m);
  327. if (std::find(_summaryThreadToDo.begin(),_summaryThreadToDo.end(),networkId) == _summaryThreadToDo.end())
  328. _summaryThreadToDo.push_back(networkId);
  329. if (!_summaryThread)
  330. _summaryThread = Thread::start(this);
  331. }
  332. std::string JSONDB::_genPath(const std::string &n,bool create)
  333. {
  334. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  335. if (pt.size() == 0)
  336. return std::string();
  337. char sep;
  338. if (_httpAddr) {
  339. sep = '/';
  340. create = false;
  341. } else {
  342. sep = ZT_PATH_SEPARATOR;
  343. }
  344. std::string p(_basePath);
  345. if (create) OSUtils::mkdir(p.c_str());
  346. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  347. p.push_back(sep);
  348. p.append(pt[i]);
  349. if (create) OSUtils::mkdir(p.c_str());
  350. }
  351. p.push_back(sep);
  352. p.append(pt[pt.size()-1]);
  353. p.append(".json");
  354. return p;
  355. }
  356. } // namespace ZeroTier