JSONDB.cpp 12 KB

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