LFDB.cpp 15 KB

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