LFDB.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 <chrono>
  29. #include <iostream>
  30. #include <sstream>
  31. #include "../osdep/OSUtils.hpp"
  32. #include "../ext/cpp-httplib/httplib.h"
  33. namespace ZeroTier
  34. {
  35. LFDB::LFDB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState) :
  36. DB(nc,myId,path),
  37. _nc(nc),
  38. _myId(myId),
  39. _lfOwnerPrivate((lfOwnerPrivate) ? lfOwnerPrivate : ""),
  40. _lfOwnerPublic((lfOwnerPublic) ? lfOwnerPublic : ""),
  41. _lfNodeHost((lfNodeHost) ? lfNodeHost : "127.0.0.1"),
  42. _lfNodePort(((lfNodePort > 0)&&(lfNodePort < 65536)) ? lfNodePort : 9980),
  43. _running(true),
  44. _ready(false),
  45. _storeOnlineState(storeOnlineState)
  46. {
  47. _syncThread = std::thread([this]() {
  48. char controllerAddress[24];
  49. const uint64_t controllerAddressInt = _myId.address().toInt();
  50. _myId.address().toString(controllerAddress);
  51. std::string networksSelectorName("com.zerotier.controller.lfdb:"); networksSelectorName.append(controllerAddress); networksSelectorName.append("/network");
  52. std::string membersSelectorName("com.zerotier.controller.lfdb:"); membersSelectorName.append(controllerAddress); membersSelectorName.append("/network/member");
  53. httplib::Client htcli(_lfNodeHost.c_str(),_lfNodePort,600);
  54. int64_t timeRangeStart = 0;
  55. while (_running) {
  56. {
  57. std::lock_guard<std::mutex> sl(_state_l);
  58. for(auto ns=_state.begin();ns!=_state.end();++ns) {
  59. if (ns->second.dirty) {
  60. nlohmann::json network;
  61. if (get(ns->first,network)) {
  62. nlohmann::json newrec,selector0;
  63. selector0["Name"] = networksSelectorName;
  64. selector0["Ordinal"] = ns->first;
  65. newrec["Selectors"].push_back(selector0);
  66. newrec["Value"] = network.dump();
  67. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  68. newrec["MaskingKey"] = controllerAddress;
  69. newrec["PulseIfUnchanged"] = true;
  70. printf("%s\n",newrec.dump().c_str());
  71. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  72. if (resp) {
  73. if (resp->status == 200) {
  74. ns->second.dirty = false;
  75. printf("SET network %.16llx %s\n",ns->first,resp->body.c_str());
  76. } else {
  77. fprintf(stderr,"ERROR: LFDB: %d from node (create/update network): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  78. }
  79. } else {
  80. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  81. }
  82. }
  83. }
  84. for(auto ms=ns->second.members.begin();ms!=ns->second.members.end();++ms) {
  85. if ((_storeOnlineState)&&(ms->second.lastOnlineDirty)&&(ms->second.lastOnlineAddress)) {
  86. char tmp[1024],tmp2[128];
  87. OSUtils::ztsnprintf(tmp,sizeof(tmp),"com.zerotier.controller.lfdb:%s/network/%.16llx/online",controllerAddress,(unsigned long long)ns->first);
  88. ms->second.lastOnlineAddress.toIpString(tmp2);
  89. nlohmann::json newrec,selector0,selector1,selectors;
  90. selector0["Name"] = tmp;
  91. selector0["Ordinal"] = ms->first;
  92. selector1["Name"] = tmp2;
  93. selector1["Ordinal"] = 0;
  94. selectors.push_back(selector0);
  95. selectors.push_back(selector1);
  96. newrec["Selectors"] = selectors;
  97. newrec["Value"] = tmp2;
  98. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  99. newrec["MaskingKey"] = controllerAddress;
  100. newrec["Timestamp"] = ms->second.lastOnlineTime;
  101. newrec["PulseIfUnchanged"] = true;
  102. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  103. if (resp) {
  104. if (resp->status == 200) {
  105. ms->second.lastOnlineDirty = false;
  106. printf("SET member online %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
  107. } else {
  108. fprintf(stderr,"ERROR: LFDB: %d from node (create/update member): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  109. }
  110. } else {
  111. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  112. }
  113. }
  114. if (ms->second.dirty) {
  115. nlohmann::json network,member;
  116. if (get(ns->first,network,ms->first,member)) {
  117. nlohmann::json newrec,selector0,selector1,selectors;
  118. selector0["Name"] = networksSelectorName;
  119. selector0["Ordinal"] = ns->first;
  120. selector1["Name"] = membersSelectorName;
  121. selector1["Ordinal"] = ms->first;
  122. selectors.push_back(selector0);
  123. selectors.push_back(selector1);
  124. newrec["Selectors"] = selectors;
  125. newrec["Value"] = member.dump();
  126. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  127. newrec["MaskingKey"] = controllerAddress;
  128. newrec["PulseIfUnchanged"] = true;
  129. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  130. if (resp) {
  131. if (resp->status == 200) {
  132. ms->second.dirty = false;
  133. printf("SET member %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
  134. } else {
  135. fprintf(stderr,"ERROR: LFDB: %d from node (create/update member): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  136. }
  137. } else {
  138. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  139. }
  140. }
  141. }
  142. }
  143. }
  144. }
  145. {
  146. std::ostringstream query;
  147. query
  148. << '{'
  149. << "\"Ranges\":[{"
  150. << "\"Name\":\"" << networksSelectorName << "\","
  151. << "\"Range\":[0,18446744073709551615]"
  152. << "}],"
  153. << "\"TimeRange\":[" << timeRangeStart << ",18446744073709551615],"
  154. << "\"MaskingKey\":\"" << controllerAddress << "\","
  155. << "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  156. << '}';
  157. auto resp = htcli.Post("/query",query.str(),"application/json");
  158. if (resp) {
  159. if (resp->status == 200) {
  160. nlohmann::json results(OSUtils::jsonParse(resp->body));
  161. if ((results.is_array())&&(results.size() > 0)) {
  162. for(std::size_t ri=0;ri<results.size();++ri) {
  163. nlohmann::json &rset = results[ri];
  164. if ((rset.is_array())&&(rset.size() > 0)) {
  165. nlohmann::json &result = rset[0];
  166. if (result.is_object()) {
  167. nlohmann::json &record = result["Record"];
  168. if (record.is_object()) {
  169. const std::string recordValue = result["Value"];
  170. printf("GET network %s\n",recordValue.c_str());
  171. nlohmann::json network(OSUtils::jsonParse(recordValue));
  172. if (network.is_object()) {
  173. const std::string idstr = network["id"];
  174. const uint64_t id = Utils::hexStrToU64(idstr.c_str());
  175. if ((id >> 24) == controllerAddressInt) {
  176. std::lock_guard<std::mutex> sl(_state_l);
  177. _NetworkState &ns = _state[id];
  178. if (!ns.dirty) {
  179. nlohmann::json nullJson;
  180. _networkChanged(nullJson,network,false);
  181. }
  182. }
  183. }
  184. }
  185. }
  186. }
  187. }
  188. }
  189. } else {
  190. fprintf(stderr,"ERROR: LFDB: %d from node: %s" ZT_EOL_S,resp->status,resp->body.c_str());
  191. }
  192. } else {
  193. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  194. }
  195. }
  196. {
  197. std::ostringstream query;
  198. query
  199. << '{'
  200. << "\"Ranges\":[{"
  201. << "\"Name\":\"" << networksSelectorName << "\","
  202. << "\"Range\":[0,18446744073709551615]"
  203. << "},{"
  204. << "\"Name\":\"" << membersSelectorName << "\","
  205. << "\"Range\":[0,18446744073709551615]"
  206. << "}],"
  207. << "\"TimeRange\":[" << timeRangeStart << ",18446744073709551615],"
  208. << "\"MaskingKey\":\"" << controllerAddress << "\","
  209. << "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  210. << '}';
  211. auto resp = htcli.Post("/query",query.str(),"application/json");
  212. if (resp) {
  213. if (resp->status == 200) {
  214. nlohmann::json results(OSUtils::jsonParse(resp->body));
  215. if ((results.is_array())&&(results.size() > 0)) {
  216. for(std::size_t ri=0;ri<results.size();++ri) {
  217. nlohmann::json &rset = results[ri];
  218. if ((rset.is_array())&&(rset.size() > 0)) {
  219. nlohmann::json &result = rset[0];
  220. if (result.is_object()) {
  221. nlohmann::json &record = result["Record"];
  222. if (record.is_object()) {
  223. const std::string recordValue = result["Value"];
  224. printf("GET member %s\n",recordValue.c_str());
  225. nlohmann::json member(OSUtils::jsonParse(recordValue));
  226. if (member.is_object()) {
  227. const std::string nwidstr = member["nwid"];
  228. const std::string idstr = member["id"];
  229. const uint64_t nwid = Utils::hexStrToU64(nwidstr.c_str());
  230. const uint64_t id = Utils::hexStrToU64(idstr.c_str());
  231. if ((id)&&((nwid >> 24) == controllerAddressInt)) {
  232. std::lock_guard<std::mutex> sl(_state_l);
  233. auto ns = _state.find(nwid);
  234. if (ns != _state.end()) {
  235. _MemberState &ms = ns->second.members[id];
  236. if (!ms.dirty) {
  237. nlohmann::json nullJson;
  238. _memberChanged(nullJson,member,false);
  239. }
  240. }
  241. }
  242. }
  243. }
  244. }
  245. }
  246. }
  247. }
  248. } else {
  249. fprintf(stderr,"ERROR: LFDB: %d from node: %s" ZT_EOL_S,resp->status,resp->body.c_str());
  250. }
  251. } else {
  252. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  253. }
  254. }
  255. timeRangeStart = time(nullptr) - 120; // start next query 2m before now to avoid losing updates
  256. _ready = true;
  257. for(int k=0;k<20;++k) { // 2s delay between queries for remotely modified networks or members
  258. if (!_running)
  259. return;
  260. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  261. }
  262. }
  263. });
  264. }
  265. LFDB::~LFDB()
  266. {
  267. _running = false;
  268. _syncThread.join();
  269. }
  270. bool LFDB::waitForReady()
  271. {
  272. while (!_ready) {
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. }
  275. return true;
  276. }
  277. bool LFDB::isReady()
  278. {
  279. return (_ready);
  280. }
  281. void LFDB::save(nlohmann::json *orig,nlohmann::json &record)
  282. {
  283. if (orig) {
  284. if (*orig != record) {
  285. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  286. }
  287. } else {
  288. record["revision"] = 1;
  289. }
  290. const std::string objtype = record["objtype"];
  291. if (objtype == "network") {
  292. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  293. if (nwid) {
  294. nlohmann::json old;
  295. get(nwid,old);
  296. if ((!old.is_object())||(old != record)) {
  297. _networkChanged(old,record,true);
  298. {
  299. std::lock_guard<std::mutex> l(_state_l);
  300. _state[nwid].dirty = true;
  301. }
  302. }
  303. }
  304. } else if (objtype == "member") {
  305. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  306. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  307. if ((id)&&(nwid)) {
  308. nlohmann::json network,old;
  309. get(nwid,network,id,old);
  310. if ((!old.is_object())||(old != record)) {
  311. _memberChanged(old,record,true);
  312. {
  313. std::lock_guard<std::mutex> l(_state_l);
  314. _state[nwid].members[id].dirty = true;
  315. }
  316. }
  317. }
  318. }
  319. }
  320. void LFDB::eraseNetwork(const uint64_t networkId)
  321. {
  322. // TODO
  323. }
  324. void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  325. {
  326. // TODO
  327. }
  328. void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  329. {
  330. std::lock_guard<std::mutex> l(_state_l);
  331. auto nw = _state.find(networkId);
  332. if (nw != _state.end()) {
  333. auto m = nw->second.members.find(memberId);
  334. if (m != nw->second.members.end()) {
  335. m->second.lastOnlineTime = OSUtils::now();
  336. if (physicalAddress)
  337. m->second.lastOnlineAddress = physicalAddress;
  338. m->second.lastOnlineDirty = true;
  339. }
  340. }
  341. }
  342. } // namespace ZeroTier