LFDB.cpp 15 KB

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