2
0

LFDB.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "LFDB.hpp"
  14. #include <thread>
  15. #include <chrono>
  16. #include <iostream>
  17. #include <sstream>
  18. #include "../osdep/OSUtils.hpp"
  19. #include "../ext/cpp-httplib/httplib.h"
  20. namespace ZeroTier
  21. {
  22. LFDB::LFDB(const Identity &myId,const char *path,const char *lfOwnerPrivate,const char *lfOwnerPublic,const char *lfNodeHost,int lfNodePort,bool storeOnlineState) :
  23. DB(),
  24. _myId(myId),
  25. _lfOwnerPrivate((lfOwnerPrivate) ? lfOwnerPrivate : ""),
  26. _lfOwnerPublic((lfOwnerPublic) ? lfOwnerPublic : ""),
  27. _lfNodeHost((lfNodeHost) ? lfNodeHost : "127.0.0.1"),
  28. _lfNodePort(((lfNodePort > 0)&&(lfNodePort < 65536)) ? lfNodePort : 9980),
  29. _running(true),
  30. _ready(false),
  31. _storeOnlineState(storeOnlineState)
  32. {
  33. _syncThread = std::thread([this]() {
  34. char controllerAddress[24];
  35. const uint64_t controllerAddressInt = _myId.address().toInt();
  36. _myId.address().toString(controllerAddress);
  37. std::string networksSelectorName("com.zerotier.controller.lfdb:"); networksSelectorName.append(controllerAddress); networksSelectorName.append("/network");
  38. // LF record masking key is the first 32 bytes of SHA512(controller private key) in hex,
  39. // hiding record values from anything but the controller or someone who has its key.
  40. uint8_t sha512pk[64];
  41. _myId.sha512PrivateKey(sha512pk);
  42. char maskingKey [128];
  43. Utils::hex(sha512pk,32,maskingKey);
  44. httplib::Client htcli(_lfNodeHost.c_str(),_lfNodePort);
  45. int64_t timeRangeStart = 0;
  46. while (_running.load()) {
  47. {
  48. std::lock_guard<std::mutex> sl(_state_l);
  49. for(auto ns=_state.begin();ns!=_state.end();++ns) {
  50. if (ns->second.dirty) {
  51. nlohmann::json network;
  52. if (get(ns->first,network)) {
  53. nlohmann::json newrec,selector0;
  54. selector0["Name"] = networksSelectorName;
  55. selector0["Ordinal"] = ns->first;
  56. newrec["Selectors"].push_back(selector0);
  57. newrec["Value"] = network.dump();
  58. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  59. newrec["MaskingKey"] = maskingKey;
  60. newrec["PulseIfUnchanged"] = true;
  61. try {
  62. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  63. if (resp) {
  64. if (resp->status == 200) {
  65. ns->second.dirty = false;
  66. //printf("SET network %.16llx %s\n",ns->first,resp->body.c_str());
  67. } else {
  68. fprintf(stderr,"ERROR: LFDB: %d from node (create/update network): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  69. }
  70. } else {
  71. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  72. }
  73. } catch (std::exception &e) {
  74. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update network): %s" ZT_EOL_S,e.what());
  75. } catch ( ... ) {
  76. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update network): unknown exception" ZT_EOL_S);
  77. }
  78. }
  79. }
  80. for(auto ms=ns->second.members.begin();ms!=ns->second.members.end();++ms) {
  81. if ((_storeOnlineState)&&(ms->second.lastOnlineDirty)&&(ms->second.lastOnlineAddress)) {
  82. nlohmann::json newrec,selector0,selector1,selectors,ip;
  83. char tmp[1024],tmp2[128];
  84. OSUtils::ztsnprintf(tmp,sizeof(tmp),"com.zerotier.controller.lfdb:%s/network/%.16llx/online",controllerAddress,(unsigned long long)ns->first);
  85. ms->second.lastOnlineAddress.toIpString(tmp2);
  86. selector0["Name"] = tmp;
  87. selector0["Ordinal"] = ms->first;
  88. selector1["Name"] = tmp2;
  89. selector1["Ordinal"] = 0;
  90. selectors.push_back(selector0);
  91. selectors.push_back(selector1);
  92. newrec["Selectors"] = selectors;
  93. const uint8_t *const rawip = (const uint8_t *)ms->second.lastOnlineAddress.rawIpData();
  94. switch(ms->second.lastOnlineAddress.ss_family) {
  95. case AF_INET:
  96. for(int j=0;j<4;++j)
  97. ip.push_back((unsigned int)rawip[j]);
  98. break;
  99. case AF_INET6:
  100. for(int j=0;j<16;++j)
  101. ip.push_back((unsigned int)rawip[j]);
  102. break;
  103. default:
  104. ip = tmp2; // should never happen since only IP transport is currently supported
  105. break;
  106. }
  107. newrec["Value"] = ip;
  108. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  109. newrec["MaskingKey"] = maskingKey;
  110. newrec["Timestamp"] = ms->second.lastOnlineTime;
  111. newrec["PulseIfUnchanged"] = true;
  112. try {
  113. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  114. if (resp) {
  115. if (resp->status == 200) {
  116. ms->second.lastOnlineDirty = false;
  117. //printf("SET member online %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
  118. } else {
  119. fprintf(stderr,"ERROR: LFDB: %d from node (create/update member online status): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  120. }
  121. } else {
  122. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  123. }
  124. } catch (std::exception &e) {
  125. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member online status): %s" ZT_EOL_S,e.what());
  126. } catch ( ... ) {
  127. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member online status): unknown exception" ZT_EOL_S);
  128. }
  129. }
  130. if (ms->second.dirty) {
  131. nlohmann::json network,member;
  132. if (get(ns->first,network,ms->first,member)) {
  133. nlohmann::json newrec,selector0,selector1,selectors;
  134. selector0["Name"] = networksSelectorName;
  135. selector0["Ordinal"] = ns->first;
  136. selector1["Name"] = "member";
  137. selector1["Ordinal"] = ms->first;
  138. selectors.push_back(selector0);
  139. selectors.push_back(selector1);
  140. newrec["Selectors"] = selectors;
  141. newrec["Value"] = member.dump();
  142. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  143. newrec["MaskingKey"] = maskingKey;
  144. newrec["PulseIfUnchanged"] = true;
  145. try {
  146. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  147. if (resp) {
  148. if (resp->status == 200) {
  149. ms->second.dirty = false;
  150. //printf("SET member %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
  151. } else {
  152. fprintf(stderr,"ERROR: LFDB: %d from node (create/update member): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  153. }
  154. } else {
  155. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  156. }
  157. } catch (std::exception &e) {
  158. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member): %s" ZT_EOL_S,e.what());
  159. } catch ( ... ) {
  160. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (create/update member): unknown exception" ZT_EOL_S);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. try {
  168. std::ostringstream query;
  169. query <<
  170. "{"
  171. "\"Ranges\":[{"
  172. "\"Name\":\"" << networksSelectorName << "\","
  173. "\"Range\":[0,18446744073709551615]"
  174. "}],"
  175. "\"TimeRange\":[" << timeRangeStart << ",9223372036854775807],"
  176. "\"MaskingKey\":\"" << maskingKey << "\","
  177. "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  178. "}";
  179. auto resp = htcli.Post("/query",query.str(),"application/json");
  180. if (resp) {
  181. if (resp->status == 200) {
  182. nlohmann::json results(OSUtils::jsonParse(resp->body));
  183. if ((results.is_array())&&(!results.empty())) {
  184. for(std::size_t ri=0;ri<results.size();++ri) {
  185. nlohmann::json &rset = results[ri];
  186. if ((rset.is_array())&&(!rset.empty())) {
  187. nlohmann::json &result = rset[0];
  188. if (result.is_object()) {
  189. nlohmann::json &record = result["Record"];
  190. if (record.is_object()) {
  191. const std::string recordValue = result["Value"];
  192. //printf("GET network %s\n",recordValue.c_str());
  193. nlohmann::json network(OSUtils::jsonParse(recordValue));
  194. if (network.is_object()) {
  195. const std::string idstr = network["id"];
  196. const uint64_t id = Utils::hexStrToU64(idstr.c_str());
  197. if ((id >> 24) == controllerAddressInt) { // sanity check
  198. nlohmann::json oldNetwork;
  199. if ((timeRangeStart > 0)&&(get(id,oldNetwork))) {
  200. const uint64_t revision = network["revision"];
  201. const uint64_t prevRevision = oldNetwork["revision"];
  202. if (prevRevision < revision) {
  203. _networkChanged(oldNetwork,network,timeRangeStart > 0);
  204. }
  205. } else {
  206. nlohmann::json nullJson;
  207. _networkChanged(nullJson,network,timeRangeStart > 0);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. }
  215. }
  216. } else {
  217. fprintf(stderr,"ERROR: LFDB: %d from node (check for network updates): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  218. }
  219. } else {
  220. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  221. }
  222. } catch (std::exception &e) {
  223. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for network updates): %s" ZT_EOL_S,e.what());
  224. } catch ( ... ) {
  225. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for network updates): unknown exception" ZT_EOL_S);
  226. }
  227. try {
  228. std::ostringstream query;
  229. query <<
  230. "{"
  231. "\"Ranges\":[{"
  232. "\"Name\":\"" << networksSelectorName << "\","
  233. "\"Range\":[0,18446744073709551615]"
  234. "},{"
  235. "\"Name\":\"member\","
  236. "\"Range\":[0,18446744073709551615]"
  237. "}],"
  238. "\"TimeRange\":[" << timeRangeStart << ",9223372036854775807],"
  239. "\"MaskingKey\":\"" << maskingKey << "\","
  240. "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  241. "}";
  242. auto resp = htcli.Post("/query",query.str(),"application/json");
  243. if (resp) {
  244. if (resp->status == 200) {
  245. nlohmann::json results(OSUtils::jsonParse(resp->body));
  246. if ((results.is_array())&&(!results.empty())) {
  247. for(std::size_t ri=0;ri<results.size();++ri) {
  248. nlohmann::json &rset = results[ri];
  249. if ((rset.is_array())&&(!rset.empty())) {
  250. nlohmann::json &result = rset[0];
  251. if (result.is_object()) {
  252. nlohmann::json &record = result["Record"];
  253. if (record.is_object()) {
  254. const std::string recordValue = result["Value"];
  255. //printf("GET member %s\n",recordValue.c_str());
  256. nlohmann::json member(OSUtils::jsonParse(recordValue));
  257. if (member.is_object()) {
  258. const std::string nwidstr = member["nwid"];
  259. const std::string idstr = member["id"];
  260. const uint64_t nwid = Utils::hexStrToU64(nwidstr.c_str());
  261. const uint64_t id = Utils::hexStrToU64(idstr.c_str());
  262. if ((id)&&((nwid >> 24) == controllerAddressInt)) { // sanity check
  263. nlohmann::json network,oldMember;
  264. if ((timeRangeStart > 0)&&(get(nwid,network,id,oldMember))) {
  265. const uint64_t revision = member["revision"];
  266. const uint64_t prevRevision = oldMember["revision"];
  267. if (prevRevision < revision)
  268. _memberChanged(oldMember,member,timeRangeStart > 0);
  269. } else if (hasNetwork(nwid)) {
  270. nlohmann::json nullJson;
  271. _memberChanged(nullJson,member,timeRangeStart > 0);
  272. }
  273. }
  274. }
  275. }
  276. }
  277. }
  278. }
  279. }
  280. } else {
  281. fprintf(stderr,"ERROR: LFDB: %d from node (check for member updates): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  282. }
  283. } else {
  284. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  285. }
  286. } catch (std::exception &e) {
  287. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for member updates): %s" ZT_EOL_S,e.what());
  288. } catch ( ... ) {
  289. fprintf(stderr,"ERROR: LFDB: unexpected exception querying node (check for member updates): unknown exception" ZT_EOL_S);
  290. }
  291. timeRangeStart = time(nullptr) - 120; // start next query 2m before now to avoid losing updates
  292. _ready.store(true);
  293. for(int k=0;k<4;++k) { // 2s delay between queries for remotely modified networks or members
  294. if (!_running.load())
  295. return;
  296. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  297. }
  298. }
  299. });
  300. }
  301. LFDB::~LFDB()
  302. {
  303. _running.store(false);
  304. _syncThread.join();
  305. }
  306. bool LFDB::waitForReady()
  307. {
  308. while (!_ready.load()) {
  309. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  310. }
  311. return true;
  312. }
  313. bool LFDB::isReady()
  314. {
  315. return (_ready.load());
  316. }
  317. bool LFDB::save(nlohmann::json &record,bool notifyListeners)
  318. {
  319. bool modified = false;
  320. const std::string objtype = record["objtype"];
  321. if (objtype == "network") {
  322. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  323. if (nwid) {
  324. nlohmann::json old;
  325. get(nwid,old);
  326. if ((!old.is_object())||(!_compareRecords(old,record))) {
  327. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  328. _networkChanged(old,record,notifyListeners);
  329. {
  330. std::lock_guard<std::mutex> l(_state_l);
  331. _state[nwid].dirty = true;
  332. }
  333. modified = true;
  334. }
  335. }
  336. } else if (objtype == "member") {
  337. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  338. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  339. if ((id)&&(nwid)) {
  340. nlohmann::json network,old;
  341. get(nwid,network,id,old);
  342. if ((!old.is_object())||(!_compareRecords(old,record))) {
  343. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  344. _memberChanged(old,record,notifyListeners);
  345. {
  346. std::lock_guard<std::mutex> l(_state_l);
  347. _state[nwid].members[id].dirty = true;
  348. }
  349. modified = true;
  350. }
  351. }
  352. }
  353. return modified;
  354. }
  355. void LFDB::eraseNetwork(const uint64_t networkId)
  356. {
  357. // TODO
  358. }
  359. void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  360. {
  361. // TODO
  362. }
  363. void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  364. {
  365. std::lock_guard<std::mutex> l(_state_l);
  366. auto nw = _state.find(networkId);
  367. if (nw != _state.end()) {
  368. auto m = nw->second.members.find(memberId);
  369. if (m != nw->second.members.end()) {
  370. m->second.lastOnlineTime = OSUtils::now();
  371. if (physicalAddress)
  372. m->second.lastOnlineAddress = physicalAddress;
  373. m->second.lastOnlineDirty = true;
  374. }
  375. }
  376. }
  377. } // namespace ZeroTier