JSONDB.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 <stdio.h>
  19. #include <stdlib.h>
  20. #include <stdint.h>
  21. #ifndef __WINDOWS__
  22. #include <unistd.h>
  23. #include <fcntl.h>
  24. #include <sys/time.h>
  25. #include <sys/types.h>
  26. #include <sys/socket.h>
  27. #include <sys/select.h>
  28. #endif
  29. #include "JSONDB.hpp"
  30. #define ZT_JSONDB_HTTP_TIMEOUT 60000
  31. namespace ZeroTier {
  32. static const nlohmann::json _EMPTY_JSON(nlohmann::json::object());
  33. static const std::map<std::string,std::string> _ZT_JSONDB_GET_HEADERS;
  34. JSONDB::JSONDB(const std::string &basePath) :
  35. _basePath(basePath),
  36. _rawInput(-1),
  37. _rawOutput(-1),
  38. _summaryThreadRun(true)
  39. {
  40. if ((_basePath.length() > 7)&&(_basePath.substr(0,7) == "http://")) {
  41. // If base path is http:// we run in HTTP mode
  42. // TODO: this doesn't yet support IPv6 since bracketed address notiation isn't supported.
  43. // Typically it's just used with 127.0.0.1 anyway.
  44. std::string hn = _basePath.substr(7);
  45. std::size_t hnend = hn.find_first_of('/');
  46. if (hnend != std::string::npos)
  47. hn = hn.substr(0,hnend);
  48. std::size_t hnsep = hn.find_last_of(':');
  49. if (hnsep != std::string::npos)
  50. hn[hnsep] = '/';
  51. _httpAddr.fromString(hn.c_str());
  52. if (hnend != std::string::npos)
  53. _basePath = _basePath.substr(7 + hnend);
  54. if (_basePath.length() == 0)
  55. _basePath = "/";
  56. if (_basePath[0] != '/')
  57. _basePath = std::string("/") + _basePath;
  58. #ifndef __WINDOWS__
  59. } else if (_basePath == "-") {
  60. // If base path is "-" we run in stdin/stdout mode and expect our database to be populated on startup via stdin
  61. // Not supported on Windows
  62. _rawInput = STDIN_FILENO;
  63. _rawOutput = STDOUT_FILENO;
  64. fcntl(_rawInput,F_SETFL,O_NONBLOCK);
  65. #endif
  66. } else {
  67. // Default mode of operation is to store files in the filesystem
  68. OSUtils::mkdir(_basePath.c_str());
  69. OSUtils::lockDownFile(_basePath.c_str(),true); // networks might contain auth tokens, etc., so restrict directory permissions
  70. }
  71. if (_rawInput < 0) {
  72. unsigned int cnt = 0;
  73. while (!_load(_basePath)) {
  74. if ((++cnt & 7) == 0)
  75. fprintf(stderr,"WARNING: controller still waiting to read '%s'..." ZT_EOL_S,_basePath.c_str());
  76. Thread::sleep(250);
  77. }
  78. }
  79. for(std::unordered_map<uint64_t,_NW>::iterator n(_networks.begin());n!=_networks.end();++n)
  80. _recomputeSummaryInfo(n->first);
  81. for(;;) {
  82. _summaryThread_m.lock();
  83. if (_summaryThreadToDo.empty()) {
  84. _summaryThread_m.unlock();
  85. break;
  86. }
  87. _summaryThread_m.unlock();
  88. Thread::sleep(50);
  89. }
  90. }
  91. JSONDB::~JSONDB()
  92. {
  93. {
  94. Mutex::Lock _l(_networks_m);
  95. _networks.clear();
  96. }
  97. Thread t;
  98. {
  99. Mutex::Lock _l(_summaryThread_m);
  100. _summaryThreadRun = false;
  101. t = _summaryThread;
  102. }
  103. if (t)
  104. Thread::join(t);
  105. }
  106. bool JSONDB::writeRaw(const std::string &n,const std::string &obj)
  107. {
  108. if (_rawOutput >= 0) {
  109. #ifndef __WINDOWS__
  110. if (obj.length() > 0) {
  111. Mutex::Lock _l(_rawLock);
  112. if (write(_rawOutput,obj.c_str(),obj.length() + 1) > 0)
  113. return true;
  114. } else {
  115. return true;
  116. }
  117. #endif
  118. return false;
  119. } else if (_httpAddr) {
  120. std::map<std::string,std::string> headers;
  121. std::string body;
  122. std::map<std::string,std::string> reqHeaders;
  123. char tmp[64];
  124. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%lu",(unsigned long)obj.length());
  125. reqHeaders["Content-Length"] = tmp;
  126. reqHeaders["Content-Type"] = "application/json";
  127. 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);
  128. return (sc == 200);
  129. } else {
  130. const std::string path(_genPath(n,true));
  131. if (!path.length())
  132. return false;
  133. return OSUtils::writeFile(path.c_str(),obj);
  134. }
  135. }
  136. bool JSONDB::hasNetwork(const uint64_t networkId) const
  137. {
  138. Mutex::Lock _l(_networks_m);
  139. return (_networks.find(networkId) != _networks.end());
  140. }
  141. bool JSONDB::getNetwork(const uint64_t networkId,nlohmann::json &config) const
  142. {
  143. Mutex::Lock _l(_networks_m);
  144. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  145. if (i == _networks.end())
  146. return false;
  147. config = nlohmann::json::from_msgpack(i->second.config);
  148. return true;
  149. }
  150. bool JSONDB::getNetworkSummaryInfo(const uint64_t networkId,NetworkSummaryInfo &ns) const
  151. {
  152. Mutex::Lock _l(_networks_m);
  153. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  154. if (i == _networks.end())
  155. return false;
  156. ns = i->second.summaryInfo;
  157. return true;
  158. }
  159. int JSONDB::getNetworkAndMember(const uint64_t networkId,const uint64_t nodeId,nlohmann::json &networkConfig,nlohmann::json &memberConfig,NetworkSummaryInfo &ns) const
  160. {
  161. Mutex::Lock _l(_networks_m);
  162. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  163. if (i == _networks.end())
  164. return 0;
  165. const std::unordered_map< uint64_t,std::vector<uint8_t> >::const_iterator j(i->second.members.find(nodeId));
  166. if (j == i->second.members.end())
  167. return 1;
  168. networkConfig = nlohmann::json::from_msgpack(i->second.config);
  169. memberConfig = nlohmann::json::from_msgpack(j->second);
  170. ns = i->second.summaryInfo;
  171. return 3;
  172. }
  173. bool JSONDB::getNetworkMember(const uint64_t networkId,const uint64_t nodeId,nlohmann::json &memberConfig) const
  174. {
  175. Mutex::Lock _l(_networks_m);
  176. const std::unordered_map<uint64_t,_NW>::const_iterator i(_networks.find(networkId));
  177. if (i == _networks.end())
  178. return false;
  179. const std::unordered_map< uint64_t,std::vector<uint8_t> >::const_iterator j(i->second.members.find(nodeId));
  180. if (j == i->second.members.end())
  181. return false;
  182. memberConfig = nlohmann::json::from_msgpack(j->second);
  183. return true;
  184. }
  185. void JSONDB::saveNetwork(const uint64_t networkId,const nlohmann::json &networkConfig)
  186. {
  187. char n[64];
  188. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  189. writeRaw(n,OSUtils::jsonDump(networkConfig));
  190. {
  191. Mutex::Lock _l(_networks_m);
  192. _networks[networkId].config = nlohmann::json::to_msgpack(networkConfig);
  193. }
  194. _recomputeSummaryInfo(networkId);
  195. }
  196. void JSONDB::saveNetworkMember(const uint64_t networkId,const uint64_t nodeId,const nlohmann::json &memberConfig)
  197. {
  198. char n[256];
  199. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  200. writeRaw(n,OSUtils::jsonDump(memberConfig));
  201. {
  202. Mutex::Lock _l(_networks_m);
  203. _networks[networkId].members[nodeId] = nlohmann::json::to_msgpack(memberConfig);
  204. _members[nodeId].insert(networkId);
  205. }
  206. _recomputeSummaryInfo(networkId);
  207. }
  208. nlohmann::json JSONDB::eraseNetwork(const uint64_t networkId)
  209. {
  210. if (!_httpAddr) { // Member deletion is done by Central in harnessed mode, and deleting the cache network entry also deletes all members
  211. std::vector<uint64_t> memberIds;
  212. {
  213. Mutex::Lock _l(_networks_m);
  214. const std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  215. if (i == _networks.end())
  216. return _EMPTY_JSON;
  217. for(std::unordered_map< uint64_t,std::vector<uint8_t> >::iterator m(i->second.members.begin());m!=i->second.members.end();++m)
  218. memberIds.push_back(m->first);
  219. }
  220. for(std::vector<uint64_t>::iterator m(memberIds.begin());m!=memberIds.end();++m)
  221. eraseNetworkMember(networkId,*m,false);
  222. }
  223. char n[256];
  224. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  225. if (_rawOutput >= 0) {
  226. // In harnessed mode, deletes occur in Central or other management
  227. // software and do not need to be executed this way.
  228. } else if (_httpAddr) {
  229. std::map<std::string,std::string> headers;
  230. std::string body;
  231. Http::DEL(0,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  232. } else {
  233. const std::string path(_genPath(n,false));
  234. if (path.length())
  235. OSUtils::rm(path.c_str());
  236. }
  237. {
  238. Mutex::Lock _l(_networks_m);
  239. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  240. if (i == _networks.end())
  241. return _EMPTY_JSON; // sanity check, shouldn't happen
  242. nlohmann::json tmp(nlohmann::json::from_msgpack(i->second.config));
  243. _networks.erase(i);
  244. return tmp;
  245. }
  246. }
  247. nlohmann::json JSONDB::eraseNetworkMember(const uint64_t networkId,const uint64_t nodeId,bool recomputeSummaryInfo)
  248. {
  249. char n[256];
  250. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  251. if (_rawOutput >= 0) {
  252. // In harnessed mode, deletes occur in Central or other management
  253. // software and do not need to be executed this way.
  254. } else if (_httpAddr) {
  255. std::map<std::string,std::string> headers;
  256. std::string body;
  257. Http::DEL(0,ZT_JSONDB_HTTP_TIMEOUT,reinterpret_cast<const struct sockaddr *>(&_httpAddr),(_basePath+"/"+n).c_str(),_ZT_JSONDB_GET_HEADERS,headers,body);
  258. } else {
  259. const std::string path(_genPath(n,false));
  260. if (path.length())
  261. OSUtils::rm(path.c_str());
  262. }
  263. {
  264. Mutex::Lock _l(_networks_m);
  265. _members[nodeId].erase(networkId);
  266. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  267. if (i == _networks.end())
  268. return _EMPTY_JSON;
  269. std::unordered_map< uint64_t,std::vector<uint8_t> >::iterator j(i->second.members.find(nodeId));
  270. if (j == i->second.members.end())
  271. return _EMPTY_JSON;
  272. nlohmann::json tmp(j->second);
  273. i->second.members.erase(j);
  274. if (recomputeSummaryInfo)
  275. _recomputeSummaryInfo(networkId);
  276. return tmp;
  277. }
  278. }
  279. void JSONDB::threadMain()
  280. throw()
  281. {
  282. #ifndef __WINDOWS__
  283. fd_set readfds,nullfds;
  284. char *const readbuf = (_rawInput >= 0) ? (new char[1048576]) : (char *)0;
  285. std::string rawInputBuf;
  286. FD_ZERO(&readfds);
  287. FD_ZERO(&nullfds);
  288. #endif
  289. std::vector<uint64_t> todo;
  290. while (_summaryThreadRun) {
  291. #ifndef __WINDOWS__
  292. if (_rawInput < 0) {
  293. Thread::sleep(25);
  294. } else {
  295. FD_SET(_rawInput,&readfds);
  296. struct timeval tv;
  297. tv.tv_sec = 0;
  298. tv.tv_usec = 25000;
  299. select(_rawInput+1,&readfds,&nullfds,&nullfds,&tv);
  300. if (FD_ISSET(_rawInput,&readfds)) {
  301. const long rn = (long)read(_rawInput,readbuf,1048576);
  302. for(long i=0;i<rn;++i) {
  303. if (readbuf[i]) {
  304. rawInputBuf.push_back(readbuf[i]);
  305. } else if (rawInputBuf.length() > 0) {
  306. _add(OSUtils::jsonParse(rawInputBuf));
  307. rawInputBuf.clear();
  308. }
  309. }
  310. continue; // we only want to do the stuff below this every few dozen ms or so, so pause again
  311. }
  312. }
  313. #else
  314. Thread::sleep(25);
  315. #endif
  316. {
  317. Mutex::Lock _l(_summaryThread_m);
  318. if (_summaryThreadToDo.empty())
  319. continue;
  320. else _summaryThreadToDo.swap(todo);
  321. }
  322. const uint64_t now = OSUtils::now();
  323. for(std::vector<uint64_t>::iterator ii(todo.begin());ii!=todo.end();++ii) {
  324. const uint64_t networkId = *ii;
  325. Mutex::Lock _l(_networks_m);
  326. std::unordered_map<uint64_t,_NW>::iterator n(_networks.find(networkId));
  327. if (n != _networks.end()) {
  328. NetworkSummaryInfo &ns = n->second.summaryInfo;
  329. ns.activeBridges.clear();
  330. ns.allocatedIps.clear();
  331. ns.authorizedMemberCount = 0;
  332. ns.activeMemberCount = 0;
  333. ns.totalMemberCount = 0;
  334. ns.mostRecentDeauthTime = 0;
  335. for(std::unordered_map< uint64_t,std::vector<uint8_t> >::const_iterator m(n->second.members.begin());m!=n->second.members.end();++m) {
  336. try {
  337. nlohmann::json member(nlohmann::json::from_msgpack(m->second));
  338. if (OSUtils::jsonBool(member["authorized"],false)) {
  339. ++ns.authorizedMemberCount;
  340. try {
  341. const nlohmann::json &mlog = member["recentLog"];
  342. if ((mlog.is_array())&&(mlog.size() > 0)) {
  343. const nlohmann::json &mlog1 = mlog[0];
  344. if (mlog1.is_object()) {
  345. if ((now - OSUtils::jsonInt(mlog1["ts"],0ULL)) < (ZT_NETWORK_AUTOCONF_DELAY * 2))
  346. ++ns.activeMemberCount;
  347. }
  348. }
  349. } catch ( ... ) {}
  350. try {
  351. if (OSUtils::jsonBool(member["activeBridge"],false))
  352. ns.activeBridges.push_back(Address(m->first));
  353. } catch ( ... ) {}
  354. try {
  355. const nlohmann::json &mips = member["ipAssignments"];
  356. if (mips.is_array()) {
  357. for(unsigned long i=0;i<mips.size();++i) {
  358. InetAddress mip(OSUtils::jsonString(mips[i],"").c_str());
  359. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  360. ns.allocatedIps.push_back(mip);
  361. }
  362. }
  363. } catch ( ... ) {}
  364. } else {
  365. try {
  366. ns.mostRecentDeauthTime = std::max(ns.mostRecentDeauthTime,OSUtils::jsonInt(member["lastDeauthorizedTime"],0ULL));
  367. } catch ( ... ) {}
  368. }
  369. ++ns.totalMemberCount;
  370. } catch ( ... ) {}
  371. }
  372. std::sort(ns.activeBridges.begin(),ns.activeBridges.end());
  373. std::sort(ns.allocatedIps.begin(),ns.allocatedIps.end());
  374. n->second.summaryInfoLastComputed = now;
  375. }
  376. }
  377. todo.clear();
  378. }
  379. #ifndef __WINDOWS__
  380. delete [] readbuf;
  381. #endif
  382. }
  383. bool JSONDB::_add(const nlohmann::json &j)
  384. {
  385. try {
  386. if (j.is_object()) {
  387. std::string id(OSUtils::jsonString(j["id"],"0"));
  388. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  389. if ((id.length() == 16)&&(objtype == "network")) {
  390. const uint64_t nwid = Utils::hexStrToU64(id.c_str());
  391. if (nwid) {
  392. Mutex::Lock _l(_networks_m);
  393. _networks[nwid].config = nlohmann::json::to_msgpack(j);
  394. return true;
  395. }
  396. } else if ((id.length() == 10)&&(objtype == "member")) {
  397. const uint64_t mid = Utils::hexStrToU64(id.c_str());
  398. const uint64_t nwid = Utils::hexStrToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  399. if ((mid)&&(nwid)) {
  400. Mutex::Lock _l(_networks_m);
  401. _networks[nwid].members[mid] = nlohmann::json::to_msgpack(j);
  402. _members[mid].insert(nwid);
  403. return true;
  404. }
  405. }
  406. }
  407. } catch ( ... ) {}
  408. return false;
  409. }
  410. bool JSONDB::_load(const std::string &p)
  411. {
  412. // This is not used in stdin/stdout mode. Instead data is populated by
  413. // sending it all to stdin.
  414. if (_httpAddr) {
  415. // In HTTP harnessed mode we download our entire working data set on startup.
  416. std::string body;
  417. std::map<std::string,std::string> headers;
  418. 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);
  419. if (sc == 200) {
  420. try {
  421. nlohmann::json dbImg(OSUtils::jsonParse(body));
  422. std::string tmp;
  423. if (dbImg.is_object()) {
  424. Mutex::Lock _l(_networks_m);
  425. for(nlohmann::json::iterator i(dbImg.begin());i!=dbImg.end();++i) {
  426. try {
  427. _add(i.value());
  428. } catch ( ... ) {}
  429. }
  430. return true;
  431. }
  432. } catch ( ... ) {} // invalid JSON, so maybe incomplete request
  433. }
  434. return false;
  435. } else {
  436. // In regular mode we recursively read it from controller.d/ on disk
  437. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  438. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  439. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  440. std::string buf;
  441. if (OSUtils::readFile((p + ZT_PATH_SEPARATOR_S + *di).c_str(),buf)) {
  442. try {
  443. _add(OSUtils::jsonParse(buf));
  444. } catch ( ... ) {}
  445. }
  446. } else {
  447. this->_load((p + ZT_PATH_SEPARATOR_S + *di));
  448. }
  449. }
  450. return true;
  451. }
  452. }
  453. void JSONDB::_recomputeSummaryInfo(const uint64_t networkId)
  454. {
  455. Mutex::Lock _l(_summaryThread_m);
  456. if (std::find(_summaryThreadToDo.begin(),_summaryThreadToDo.end(),networkId) == _summaryThreadToDo.end())
  457. _summaryThreadToDo.push_back(networkId);
  458. if (!_summaryThread)
  459. _summaryThread = Thread::start(this);
  460. }
  461. std::string JSONDB::_genPath(const std::string &n,bool create)
  462. {
  463. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  464. if (pt.size() == 0)
  465. return std::string();
  466. char sep;
  467. if (_httpAddr) {
  468. sep = '/';
  469. create = false;
  470. } else {
  471. sep = ZT_PATH_SEPARATOR;
  472. }
  473. std::string p(_basePath);
  474. if (create) OSUtils::mkdir(p.c_str());
  475. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  476. p.push_back(sep);
  477. p.append(pt[i]);
  478. if (create) OSUtils::mkdir(p.c_str());
  479. }
  480. p.push_back(sep);
  481. p.append(pt[pt.size()-1]);
  482. p.append(".json");
  483. return p;
  484. }
  485. } // namespace ZeroTier