JSONDB.cpp 16 KB

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