JSONDB.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. bool update;
  153. {
  154. Mutex::Lock _l(_networks_m);
  155. _NW &nw = _networks[networkId];
  156. update = !nw.config.empty();
  157. nw.config = nlohmann::json::to_msgpack(networkConfig);
  158. }
  159. if (update)
  160. _parent->onNetworkUpdate(networkId);
  161. _recomputeSummaryInfo(networkId);
  162. }
  163. void JSONDB::saveNetworkMember(const uint64_t networkId,const uint64_t nodeId,const nlohmann::json &memberConfig)
  164. {
  165. char n[256];
  166. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  167. writeRaw(n,OSUtils::jsonDump(memberConfig,-1));
  168. bool update;
  169. {
  170. Mutex::Lock _l(_networks_m);
  171. std::vector<uint8_t> &m = _networks[networkId].members[nodeId];
  172. update = !m.empty();
  173. m = nlohmann::json::to_msgpack(memberConfig);
  174. _members[nodeId].insert(networkId);
  175. }
  176. if (update)
  177. _parent->onNetworkMemberUpdate(networkId,nodeId);
  178. _recomputeSummaryInfo(networkId);
  179. }
  180. nlohmann::json JSONDB::eraseNetwork(const uint64_t networkId)
  181. {
  182. if (_rawOutput >= 0) {
  183. // In harnessed mode, DB deletes occur in the Central database and we do
  184. // not need to erase files.
  185. } else {
  186. std::vector<uint64_t> memberIds;
  187. {
  188. Mutex::Lock _l(_networks_m);
  189. const std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  190. if (i == _networks.end())
  191. return _EMPTY_JSON;
  192. for(std::unordered_map< uint64_t,std::vector<uint8_t> >::iterator m(i->second.members.begin());m!=i->second.members.end();++m)
  193. memberIds.push_back(m->first);
  194. }
  195. for(std::vector<uint64_t>::iterator m(memberIds.begin());m!=memberIds.end();++m)
  196. eraseNetworkMember(networkId,*m,false);
  197. char n[256];
  198. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx",(unsigned long long)networkId);
  199. const std::string path(_genPath(n,false));
  200. if (path.length())
  201. OSUtils::rm(path.c_str());
  202. }
  203. // This also erases all members from the memory cache
  204. {
  205. Mutex::Lock _l(_networks_m);
  206. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  207. if (i == _networks.end())
  208. return _EMPTY_JSON; // sanity check, shouldn't happen
  209. nlohmann::json tmp(nlohmann::json::from_msgpack(i->second.config));
  210. _networks.erase(i);
  211. return tmp;
  212. }
  213. }
  214. nlohmann::json JSONDB::eraseNetworkMember(const uint64_t networkId,const uint64_t nodeId,bool recomputeSummaryInfo)
  215. {
  216. if (_rawOutput >= 0) {
  217. // In harnessed mode, DB deletes occur in Central and we do not remove files.
  218. } else {
  219. char n[256];
  220. OSUtils::ztsnprintf(n,sizeof(n),"network/%.16llx/member/%.10llx",(unsigned long long)networkId,(unsigned long long)nodeId);
  221. const std::string path(_genPath(n,false));
  222. if (path.length())
  223. OSUtils::rm(path.c_str());
  224. }
  225. {
  226. Mutex::Lock _l(_networks_m);
  227. _members[nodeId].erase(networkId);
  228. std::unordered_map<uint64_t,_NW>::iterator i(_networks.find(networkId));
  229. if (i == _networks.end())
  230. return _EMPTY_JSON;
  231. std::unordered_map< uint64_t,std::vector<uint8_t> >::iterator j(i->second.members.find(nodeId));
  232. if (j == i->second.members.end())
  233. return _EMPTY_JSON;
  234. nlohmann::json tmp(j->second);
  235. i->second.members.erase(j);
  236. if (recomputeSummaryInfo)
  237. _recomputeSummaryInfo(networkId);
  238. return tmp;
  239. }
  240. }
  241. void JSONDB::threadMain()
  242. throw()
  243. {
  244. #ifndef __WINDOWS__
  245. fd_set readfds,nullfds;
  246. char *const readbuf = (_rawInput >= 0) ? (new char[1048576]) : (char *)0;
  247. std::string rawInputBuf;
  248. FD_ZERO(&readfds);
  249. FD_ZERO(&nullfds);
  250. struct timeval tv;
  251. #endif
  252. std::vector<uint64_t> todo;
  253. while (_summaryThreadRun) {
  254. #ifndef __WINDOWS__
  255. if (_rawInput < 0) {
  256. Thread::sleep(25);
  257. } else {
  258. // In IPC mode we wait but also select() on STDIN to read database updates
  259. FD_SET(_rawInput,&readfds);
  260. tv.tv_sec = 0;
  261. tv.tv_usec = 25000;
  262. select(_rawInput+1,&readfds,&nullfds,&nullfds,&tv);
  263. if (FD_ISSET(_rawInput,&readfds)) {
  264. const long rn = (long)read(_rawInput,readbuf,1048576);
  265. bool gotMessage = false;
  266. for(long i=0;i<rn;++i) {
  267. if ((readbuf[i] != '\n')&&(readbuf[i] != '\r')&&(readbuf[i] != 0)) { // compatible with nodeJS IPC
  268. rawInputBuf.push_back(readbuf[i]);
  269. } else if (rawInputBuf.length() > 0) {
  270. try {
  271. const nlohmann::json obj(OSUtils::jsonParse(rawInputBuf));
  272. gotMessage = true;
  273. if (!_dataReady) {
  274. _dataReady = true;
  275. _networks_m.unlock();
  276. }
  277. if (obj.is_array()) {
  278. for(unsigned long i=0;i<obj.size();++i)
  279. _add(obj[i]);
  280. } else if (obj.is_object()) {
  281. _add(obj);
  282. }
  283. } catch ( ... ) {} // ignore malformed JSON
  284. rawInputBuf.clear();
  285. }
  286. }
  287. if (!gotMessage) // select() again immediately until we get at least one full message
  288. continue;
  289. }
  290. }
  291. #else
  292. Thread::sleep(25);
  293. #endif
  294. {
  295. Mutex::Lock _l(_summaryThread_m);
  296. if (_summaryThreadToDo.empty())
  297. continue;
  298. else _summaryThreadToDo.swap(todo);
  299. }
  300. if (!_dataReady) { // sanity check
  301. _dataReady = true;
  302. _networks_m.unlock();
  303. }
  304. const uint64_t now = OSUtils::now();
  305. try {
  306. Mutex::Lock _l(_networks_m);
  307. for(std::vector<uint64_t>::iterator ii(todo.begin());ii!=todo.end();++ii) {
  308. const uint64_t networkId = *ii;
  309. std::unordered_map<uint64_t,_NW>::iterator n(_networks.find(networkId));
  310. if (n != _networks.end()) {
  311. NetworkSummaryInfo &ns = n->second.summaryInfo;
  312. ns.activeBridges.clear();
  313. ns.allocatedIps.clear();
  314. ns.authorizedMemberCount = 0;
  315. ns.activeMemberCount = 0;
  316. ns.totalMemberCount = 0;
  317. ns.mostRecentDeauthTime = 0;
  318. for(std::unordered_map< uint64_t,std::vector<uint8_t> >::const_iterator m(n->second.members.begin());m!=n->second.members.end();++m) {
  319. try {
  320. nlohmann::json member(nlohmann::json::from_msgpack(m->second));
  321. if (OSUtils::jsonBool(member["authorized"],false)) {
  322. ++ns.authorizedMemberCount;
  323. try {
  324. const nlohmann::json &mlog = member["recentLog"];
  325. if ((mlog.is_array())&&(mlog.size() > 0)) {
  326. const nlohmann::json &mlog1 = mlog[0];
  327. if (mlog1.is_object()) {
  328. if ((now - OSUtils::jsonInt(mlog1["ts"],0ULL)) < (ZT_NETWORK_AUTOCONF_DELAY * 2))
  329. ++ns.activeMemberCount;
  330. }
  331. }
  332. } catch ( ... ) {}
  333. try {
  334. if (OSUtils::jsonBool(member["activeBridge"],false))
  335. ns.activeBridges.push_back(Address(m->first));
  336. } catch ( ... ) {}
  337. try {
  338. const nlohmann::json &mips = member["ipAssignments"];
  339. if (mips.is_array()) {
  340. for(unsigned long i=0;i<mips.size();++i) {
  341. InetAddress mip(OSUtils::jsonString(mips[i],"").c_str());
  342. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  343. ns.allocatedIps.push_back(mip);
  344. }
  345. }
  346. } catch ( ... ) {}
  347. } else {
  348. try {
  349. ns.mostRecentDeauthTime = std::max(ns.mostRecentDeauthTime,OSUtils::jsonInt(member["lastDeauthorizedTime"],0ULL));
  350. } catch ( ... ) {}
  351. }
  352. ++ns.totalMemberCount;
  353. } catch ( ... ) {}
  354. }
  355. std::sort(ns.activeBridges.begin(),ns.activeBridges.end());
  356. std::sort(ns.allocatedIps.begin(),ns.allocatedIps.end());
  357. n->second.summaryInfoLastComputed = now;
  358. }
  359. }
  360. } catch ( ... ) {}
  361. todo.clear();
  362. }
  363. if (!_dataReady) // sanity check
  364. _networks_m.unlock();
  365. #ifndef __WINDOWS__
  366. delete [] readbuf;
  367. #endif
  368. }
  369. bool JSONDB::_add(const nlohmann::json &j)
  370. {
  371. try {
  372. if (j.is_object()) {
  373. std::string id(OSUtils::jsonString(j["id"],"0"));
  374. std::string objtype(OSUtils::jsonString(j["objtype"],""));
  375. if ((id.length() == 16)&&(objtype == "network")) {
  376. const uint64_t nwid = Utils::hexStrToU64(id.c_str());
  377. if (nwid) {
  378. bool update;
  379. {
  380. Mutex::Lock _l(_networks_m);
  381. _NW &nw = _networks[nwid];
  382. update = !nw.config.empty();
  383. nw.config = nlohmann::json::to_msgpack(j);
  384. }
  385. if (update)
  386. _parent->onNetworkUpdate(nwid);
  387. _recomputeSummaryInfo(nwid);
  388. return true;
  389. }
  390. } else if ((id.length() == 10)&&(objtype == "member")) {
  391. const uint64_t mid = Utils::hexStrToU64(id.c_str());
  392. const uint64_t nwid = Utils::hexStrToU64(OSUtils::jsonString(j["nwid"],"0").c_str());
  393. if ((mid)&&(nwid)) {
  394. bool update;
  395. {
  396. Mutex::Lock _l(_networks_m);
  397. std::vector<uint8_t> &m = _networks[nwid].members[mid];
  398. update = !m.empty();
  399. m = nlohmann::json::to_msgpack(j);
  400. _members[mid].insert(nwid);
  401. }
  402. if (update)
  403. _parent->onNetworkMemberUpdate(nwid,mid);
  404. _recomputeSummaryInfo(nwid);
  405. return true;
  406. }
  407. }
  408. }
  409. } catch ( ... ) {}
  410. return false;
  411. }
  412. bool JSONDB::_load(const std::string &p)
  413. {
  414. // This is not used in stdin/stdout mode. Instead data is populated by
  415. // sending it all to stdin.
  416. std::vector<std::string> dl(OSUtils::listDirectory(p.c_str(),true));
  417. for(std::vector<std::string>::const_iterator di(dl.begin());di!=dl.end();++di) {
  418. if ((di->length() > 5)&&(di->substr(di->length() - 5) == ".json")) {
  419. std::string buf;
  420. if (OSUtils::readFile((p + ZT_PATH_SEPARATOR_S + *di).c_str(),buf)) {
  421. try {
  422. _add(OSUtils::jsonParse(buf));
  423. } catch ( ... ) {}
  424. }
  425. } else {
  426. this->_load((p + ZT_PATH_SEPARATOR_S + *di));
  427. }
  428. }
  429. return true;
  430. }
  431. void JSONDB::_recomputeSummaryInfo(const uint64_t networkId)
  432. {
  433. Mutex::Lock _l(_summaryThread_m);
  434. if (std::find(_summaryThreadToDo.begin(),_summaryThreadToDo.end(),networkId) == _summaryThreadToDo.end())
  435. _summaryThreadToDo.push_back(networkId);
  436. if (!_summaryThread)
  437. _summaryThread = Thread::start(this);
  438. }
  439. std::string JSONDB::_genPath(const std::string &n,bool create)
  440. {
  441. std::vector<std::string> pt(OSUtils::split(n.c_str(),"/","",""));
  442. if (pt.size() == 0)
  443. return std::string();
  444. std::string p(_basePath);
  445. if (create) OSUtils::mkdir(p.c_str());
  446. for(unsigned long i=0,j=(unsigned long)(pt.size()-1);i<j;++i) {
  447. p.push_back(ZT_PATH_SEPARATOR);
  448. p.append(pt[i]);
  449. if (create) OSUtils::mkdir(p.c_str());
  450. }
  451. p.push_back(ZT_PATH_SEPARATOR);
  452. p.append(pt[pt.size()-1]);
  453. p.append(".json");
  454. return p;
  455. }
  456. } // namespace ZeroTier