LFDB.cpp 16 KB

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