LFDB.cpp 15 KB

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