LFDB.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include "LFDB.hpp"
  27. #include <thread>
  28. #include <iostream>
  29. #include <sstream>
  30. #include "../osdep/OSUtils.hpp"
  31. #include "../ext/cpp-httplib/httplib.h"
  32. namespace ZeroTier
  33. {
  34. LFDB::LFDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState) :
  35. DB(nc,myId,path),
  36. _nc(nc),
  37. _myId(myId),
  38. _lfOwnerPrivate(lfOwnerPrivate),
  39. _lfOwnerPublic(lfOwnerPublic),
  40. _lfNodeHost(lfNodeHost),
  41. _lfNodePort(lfNodePort),
  42. _running(true),
  43. _ready(false),
  44. _storeOnlineState(storeOnlineState)
  45. {
  46. _syncThread = std::thread([this]() {
  47. char controllerAddress[24];
  48. _myId.address().toString(controllerAddress);
  49. httplib::Client htcli(_lfNodeHost.c_str(),_lfNodePort,600);
  50. while (_running) {
  51. std::ostringstream query;
  52. query
  53. << '{'
  54. << "\"Ranges\":[{"
  55. << "\"Name\": \"com.zerotier.controller.lfdb:" << controllerAddress << "\""
  56. << "}],"
  57. << "\"MaskingKey\":\"" << controllerAddress << "\","
  58. << "\"Owners\":[\"" << _lfOwnerPublic << "\"],"
  59. << "\"Open\":true"
  60. << '}';
  61. auto resp = htcli.Post("/query",query.str(),"application/json");
  62. if (resp->status == 200) {
  63. fprintf(stderr,"%d %s\n",resp->status,resp->body.c_str());
  64. } else {
  65. fprintf(stderr,"ERROR: LFDB: %d from node: %s" ZT_EOL_S,resp->status,resp->body.c_str());
  66. }
  67. _ready = true;
  68. for(int k=0;k<10;++k) {
  69. if (!_running)
  70. return;
  71. usleep(100000);
  72. }
  73. }
  74. });
  75. }
  76. LFDB::~LFDB()
  77. {
  78. _running = false;
  79. _syncThread.join();
  80. }
  81. bool LFDB::waitForReady()
  82. {
  83. while (!_ready)
  84. usleep(10000);
  85. }
  86. bool LFDB::isReady()
  87. {
  88. return (_ready);
  89. }
  90. void LFDB::save(nlohmann::json *orig,nlohmann::json &record)
  91. {
  92. if (orig) {
  93. if (*orig != record) {
  94. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  95. }
  96. } else {
  97. record["revision"] = 1;
  98. }
  99. const std::string objtype = record["objtype"];
  100. if (objtype == "network") {
  101. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  102. if (nwid) {
  103. nlohmann::json old;
  104. get(nwid,old);
  105. if ((!old.is_object())||(old != record)) {
  106. }
  107. }
  108. } else if (objtype == "member") {
  109. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  110. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  111. if ((id)&&(nwid)) {
  112. nlohmann::json network,old;
  113. get(nwid,network,id,old);
  114. if ((!old.is_object())||(old != record)) {
  115. }
  116. }
  117. }
  118. }
  119. void LFDB::eraseNetwork(const uint64_t networkId)
  120. {
  121. // TODO
  122. }
  123. void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  124. {
  125. // TODO
  126. }
  127. void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  128. {
  129. std::lock_guard<std::mutex> l(_state_l);
  130. auto nw = _state.find(networkId);
  131. if (nw != _state.end()) {
  132. auto m = nw->second.members.find(memberId);
  133. if (m != nw->second.members.end()) {
  134. m->second.lastOnlineTime = OSUtils::now();
  135. if (physicalAddress)
  136. m->second.lastOnlineAddress = physicalAddress;
  137. m->second.lastOnlineDirty = true;
  138. }
  139. }
  140. }
  141. #if 0
  142. FileDB::FileDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path) :
  143. DB(nc,myId,path),
  144. _networksPath(_path + ZT_PATH_SEPARATOR_S + "network"),
  145. _tracePath(_path + ZT_PATH_SEPARATOR_S + "trace"),
  146. _onlineChanged(false),
  147. _running(true)
  148. {
  149. OSUtils::mkdir(_path.c_str());
  150. OSUtils::lockDownFile(_path.c_str(),true);
  151. OSUtils::mkdir(_networksPath.c_str());
  152. OSUtils::mkdir(_tracePath.c_str());
  153. std::vector<std::string> networks(OSUtils::listDirectory(_networksPath.c_str(),false));
  154. std::string buf;
  155. for(auto n=networks.begin();n!=networks.end();++n) {
  156. buf.clear();
  157. if ((n->length() == 21)&&(OSUtils::readFile((_networksPath + ZT_PATH_SEPARATOR_S + *n).c_str(),buf))) {
  158. try {
  159. nlohmann::json network(OSUtils::jsonParse(buf));
  160. const std::string nwids = network["id"];
  161. if (nwids.length() == 16) {
  162. nlohmann::json nullJson;
  163. _networkChanged(nullJson,network,false);
  164. std::string membersPath(_networksPath + ZT_PATH_SEPARATOR_S + nwids + ZT_PATH_SEPARATOR_S "member");
  165. std::vector<std::string> members(OSUtils::listDirectory(membersPath.c_str(),false));
  166. for(auto m=members.begin();m!=members.end();++m) {
  167. buf.clear();
  168. if ((m->length() == 15)&&(OSUtils::readFile((membersPath + ZT_PATH_SEPARATOR_S + *m).c_str(),buf))) {
  169. try {
  170. nlohmann::json member(OSUtils::jsonParse(buf));
  171. const std::string addrs = member["id"];
  172. if (addrs.length() == 10) {
  173. nlohmann::json nullJson2;
  174. _memberChanged(nullJson2,member,false);
  175. }
  176. } catch ( ... ) {}
  177. }
  178. }
  179. }
  180. } catch ( ... ) {}
  181. }
  182. }
  183. _onlineUpdateThread = std::thread([this]() {
  184. unsigned int cnt = 0;
  185. while (this->_running) {
  186. std::this_thread::sleep_for(std::chrono::microseconds(100));
  187. if ((++cnt % 20) == 0) { // 5 seconds
  188. std::lock_guard<std::mutex> l(this->_online_l);
  189. if (!this->_running) return;
  190. if (this->_onlineChanged) {
  191. char p[4096],atmp[64];
  192. for(auto nw=this->_online.begin();nw!=this->_online.end();++nw) {
  193. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx-online.json",_networksPath.c_str(),(unsigned long long)nw->first);
  194. FILE *f = fopen(p,"wb");
  195. if (f) {
  196. fprintf(f,"{");
  197. const char *memberPrefix = "";
  198. for(auto m=nw->second.begin();m!=nw->second.end();++m) {
  199. fprintf(f,"%s\"%.10llx\":{" ZT_EOL_S,memberPrefix,(unsigned long long)m->first);
  200. memberPrefix = ",";
  201. InetAddress lastAddr;
  202. const char *timestampPrefix = " ";
  203. int cnt = 0;
  204. for(auto ts=m->second.rbegin();ts!=m->second.rend();) {
  205. if (cnt < 25) {
  206. if (lastAddr != ts->second) {
  207. lastAddr = ts->second;
  208. fprintf(f,"%s\"%lld\":\"%s\"" ZT_EOL_S,timestampPrefix,(long long)ts->first,ts->second.toString(atmp));
  209. timestampPrefix = ",";
  210. ++cnt;
  211. ++ts;
  212. } else {
  213. ts = std::map<int64_t,InetAddress>::reverse_iterator(m->second.erase(std::next(ts).base()));
  214. }
  215. } else {
  216. ts = std::map<int64_t,InetAddress>::reverse_iterator(m->second.erase(std::next(ts).base()));
  217. }
  218. }
  219. fprintf(f,"}");
  220. }
  221. fprintf(f,"}" ZT_EOL_S);
  222. fclose(f);
  223. }
  224. }
  225. this->_onlineChanged = false;
  226. }
  227. }
  228. }
  229. });
  230. }
  231. FileDB::~FileDB()
  232. {
  233. try {
  234. _online_l.lock();
  235. _running = false;
  236. _online_l.unlock();
  237. _onlineUpdateThread.join();
  238. } catch ( ... ) {}
  239. }
  240. bool FileDB::waitForReady() { return true; }
  241. bool FileDB::isReady() { return true; }
  242. void FileDB::save(nlohmann::json *orig,nlohmann::json &record)
  243. {
  244. char p1[4096],p2[4096],pb[4096];
  245. try {
  246. if (orig) {
  247. if (*orig != record) {
  248. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  249. }
  250. } else {
  251. record["revision"] = 1;
  252. }
  253. const std::string objtype = record["objtype"];
  254. if (objtype == "network") {
  255. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  256. if (nwid) {
  257. nlohmann::json old;
  258. get(nwid,old);
  259. if ((!old.is_object())||(old != record)) {
  260. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),nwid);
  261. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
  262. fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
  263. _networkChanged(old,record,true);
  264. }
  265. }
  266. } else if (objtype == "member") {
  267. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  268. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  269. if ((id)&&(nwid)) {
  270. nlohmann::json network,old;
  271. get(nwid,network,id,old);
  272. if ((!old.is_object())||(old != record)) {
  273. OSUtils::ztsnprintf(pb,sizeof(pb),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)nwid);
  274. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%.10llx.json",pb,(unsigned long long)id);
  275. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1))) {
  276. OSUtils::ztsnprintf(p2,sizeof(p2),"%s" ZT_PATH_SEPARATOR_S "%.16llx",_networksPath.c_str(),(unsigned long long)nwid);
  277. OSUtils::mkdir(p2);
  278. OSUtils::mkdir(pb);
  279. if (!OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1)))
  280. fprintf(stderr,"WARNING: controller unable to write to path: %s" ZT_EOL_S,p1);
  281. }
  282. _memberChanged(old,record,true);
  283. }
  284. }
  285. } else if (objtype == "trace") {
  286. const std::string id = record["id"];
  287. if (id.length() > 0) {
  288. OSUtils::ztsnprintf(p1,sizeof(p1),"%s" ZT_PATH_SEPARATOR_S "%s.json",_tracePath.c_str(),id.c_str());
  289. OSUtils::writeFile(p1,OSUtils::jsonDump(record,-1));
  290. }
  291. }
  292. } catch ( ... ) {} // drop invalid records missing fields
  293. }
  294. void FileDB::eraseNetwork(const uint64_t networkId)
  295. {
  296. nlohmann::json network,nullJson;
  297. get(networkId,network);
  298. char p[16384];
  299. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx.json",_networksPath.c_str(),networkId);
  300. OSUtils::rm(p);
  301. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx-online.json",_networksPath.c_str(),networkId);
  302. OSUtils::rm(p);
  303. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member",_networksPath.c_str(),(unsigned long long)networkId);
  304. OSUtils::rmDashRf(p);
  305. _networkChanged(network,nullJson,true);
  306. std::lock_guard<std::mutex> l(this->_online_l);
  307. this->_online.erase(networkId);
  308. this->_onlineChanged = true;
  309. }
  310. void FileDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  311. {
  312. nlohmann::json network,member,nullJson;
  313. get(networkId,network);
  314. get(memberId,member);
  315. char p[4096];
  316. OSUtils::ztsnprintf(p,sizeof(p),"%s" ZT_PATH_SEPARATOR_S "%.16llx" ZT_PATH_SEPARATOR_S "member" ZT_PATH_SEPARATOR_S "%.10llx.json",_networksPath.c_str(),networkId,memberId);
  317. OSUtils::rm(p);
  318. _memberChanged(member,nullJson,true);
  319. std::lock_guard<std::mutex> l(this->_online_l);
  320. this->_online[networkId].erase(memberId);
  321. this->_onlineChanged = true;
  322. }
  323. void FileDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  324. {
  325. char mid[32],atmp[64];
  326. OSUtils::ztsnprintf(mid,sizeof(mid),"%.10llx",(unsigned long long)memberId);
  327. physicalAddress.toString(atmp);
  328. std::lock_guard<std::mutex> l(this->_online_l);
  329. this->_online[networkId][memberId][OSUtils::now()] = physicalAddress;
  330. this->_onlineChanged = true;
  331. }
  332. #endif
  333. } // namespace ZeroTier