LFDB.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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(myId,path),
  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) {
  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. 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. }
  87. }
  88. for(auto ms=ns->second.members.begin();ms!=ns->second.members.end();++ms) {
  89. if ((_storeOnlineState)&&(ms->second.lastOnlineDirty)&&(ms->second.lastOnlineAddress)) {
  90. nlohmann::json newrec,selector0,selector1,selectors,ip;
  91. char tmp[1024],tmp2[128];
  92. OSUtils::ztsnprintf(tmp,sizeof(tmp),"com.zerotier.controller.lfdb:%s/network/%.16llx/online",controllerAddress,(unsigned long long)ns->first);
  93. ms->second.lastOnlineAddress.toIpString(tmp2);
  94. selector0["Name"] = tmp;
  95. selector0["Ordinal"] = ms->first;
  96. selector1["Name"] = tmp2;
  97. selector1["Ordinal"] = 0;
  98. selectors.push_back(selector0);
  99. selectors.push_back(selector1);
  100. newrec["Selectors"] = selectors;
  101. const uint8_t *const rawip = (const uint8_t *)ms->second.lastOnlineAddress.rawIpData();
  102. switch(ms->second.lastOnlineAddress) {
  103. case AF_INET:
  104. for(int j=0;j<4;++j)
  105. ip.push_back((unsigned int)rawip[j]);
  106. break;
  107. case AF_INET6:
  108. for(int j=0;j<16;++j)
  109. ip.push_back((unsigned int)rawip[j]);
  110. break;
  111. default:
  112. ip = tmp2; // should never happen since only IP transport is currently supported
  113. break;
  114. }
  115. newrec["Value"] = ip;
  116. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  117. newrec["MaskingKey"] = maskingKey;
  118. newrec["Timestamp"] = ms->second.lastOnlineTime;
  119. newrec["PulseIfUnchanged"] = true;
  120. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  121. if (resp) {
  122. if (resp->status == 200) {
  123. ms->second.lastOnlineDirty = false;
  124. printf("SET member online %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
  125. } else {
  126. fprintf(stderr,"ERROR: LFDB: %d from node (create/update member online status): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  127. }
  128. } else {
  129. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  130. }
  131. }
  132. if (ms->second.dirty) {
  133. nlohmann::json network,member;
  134. if (get(ns->first,network,ms->first,member)) {
  135. nlohmann::json newrec,selector0,selector1,selectors;
  136. selector0["Name"] = networksSelectorName;
  137. selector0["Ordinal"] = ns->first;
  138. selector1["Name"] = membersSelectorName;
  139. selector1["Ordinal"] = ms->first;
  140. selectors.push_back(selector0);
  141. selectors.push_back(selector1);
  142. newrec["Selectors"] = selectors;
  143. newrec["Value"] = member.dump();
  144. newrec["OwnerPrivate"] = _lfOwnerPrivate;
  145. newrec["MaskingKey"] = maskingKey;
  146. newrec["PulseIfUnchanged"] = true;
  147. auto resp = htcli.Post("/makerecord",newrec.dump(),"application/json");
  148. if (resp) {
  149. if (resp->status == 200) {
  150. ms->second.dirty = false;
  151. printf("SET member %.16llx %.10llx %s\n",ns->first,ms->first,resp->body.c_str());
  152. } else {
  153. fprintf(stderr,"ERROR: LFDB: %d from node (create/update member): %s" ZT_EOL_S,resp->status,resp->body.c_str());
  154. }
  155. } else {
  156. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. }
  163. {
  164. std::ostringstream query;
  165. query
  166. << '{'
  167. << "\"Ranges\":[{"
  168. << "\"Name\":\"" << networksSelectorName << "\","
  169. << "\"Range\":[0,18446744073709551615]"
  170. << "}],"
  171. << "\"TimeRange\":[" << timeRangeStart << ",18446744073709551615],"
  172. << "\"MaskingKey\":\"" << maskingKey << "\","
  173. << "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  174. << '}';
  175. auto resp = htcli.Post("/query",query.str(),"application/json");
  176. if (resp) {
  177. if (resp->status == 200) {
  178. nlohmann::json results(OSUtils::jsonParse(resp->body));
  179. if ((results.is_array())&&(results.size() > 0)) {
  180. for(std::size_t ri=0;ri<results.size();++ri) {
  181. nlohmann::json &rset = results[ri];
  182. if ((rset.is_array())&&(rset.size() > 0)) {
  183. nlohmann::json &result = rset[0];
  184. if (result.is_object()) {
  185. nlohmann::json &record = result["Record"];
  186. if (record.is_object()) {
  187. const std::string recordValue = result["Value"];
  188. printf("GET network %s\n",recordValue.c_str());
  189. nlohmann::json network(OSUtils::jsonParse(recordValue));
  190. if (network.is_object()) {
  191. const std::string idstr = network["id"];
  192. const uint64_t id = Utils::hexStrToU64(idstr.c_str());
  193. if ((id >> 24) == controllerAddressInt) {
  194. std::lock_guard<std::mutex> sl(_state_l);
  195. _NetworkState &ns = _state[id];
  196. if (!ns.dirty) {
  197. nlohmann::json nullJson;
  198. _networkChanged(nullJson,network,false);
  199. }
  200. }
  201. }
  202. }
  203. }
  204. }
  205. }
  206. }
  207. } else {
  208. fprintf(stderr,"ERROR: LFDB: %d from node: %s" ZT_EOL_S,resp->status,resp->body.c_str());
  209. }
  210. } else {
  211. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  212. }
  213. }
  214. {
  215. std::ostringstream query;
  216. query
  217. << '{'
  218. << "\"Ranges\":[{"
  219. << "\"Name\":\"" << networksSelectorName << "\","
  220. << "\"Range\":[0,18446744073709551615]"
  221. << "},{"
  222. << "\"Name\":\"" << membersSelectorName << "\","
  223. << "\"Range\":[0,18446744073709551615]"
  224. << "}],"
  225. << "\"TimeRange\":[" << timeRangeStart << ",18446744073709551615],"
  226. << "\"MaskingKey\":\"" << maskingKey << "\","
  227. << "\"Owners\":[\"" << _lfOwnerPublic << "\"]"
  228. << '}';
  229. auto resp = htcli.Post("/query",query.str(),"application/json");
  230. if (resp) {
  231. if (resp->status == 200) {
  232. nlohmann::json results(OSUtils::jsonParse(resp->body));
  233. if ((results.is_array())&&(results.size() > 0)) {
  234. for(std::size_t ri=0;ri<results.size();++ri) {
  235. nlohmann::json &rset = results[ri];
  236. if ((rset.is_array())&&(rset.size() > 0)) {
  237. nlohmann::json &result = rset[0];
  238. if (result.is_object()) {
  239. nlohmann::json &record = result["Record"];
  240. if (record.is_object()) {
  241. const std::string recordValue = result["Value"];
  242. printf("GET member %s\n",recordValue.c_str());
  243. nlohmann::json member(OSUtils::jsonParse(recordValue));
  244. if (member.is_object()) {
  245. const std::string nwidstr = member["nwid"];
  246. const std::string idstr = member["id"];
  247. const uint64_t nwid = Utils::hexStrToU64(nwidstr.c_str());
  248. const uint64_t id = Utils::hexStrToU64(idstr.c_str());
  249. if ((id)&&((nwid >> 24) == controllerAddressInt)) {
  250. std::lock_guard<std::mutex> sl(_state_l);
  251. auto ns = _state.find(nwid);
  252. if (ns != _state.end()) {
  253. _MemberState &ms = ns->second.members[id];
  254. if (!ms.dirty) {
  255. nlohmann::json nullJson;
  256. _memberChanged(nullJson,member,false);
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. }
  264. }
  265. }
  266. } else {
  267. fprintf(stderr,"ERROR: LFDB: %d from node: %s" ZT_EOL_S,resp->status,resp->body.c_str());
  268. }
  269. } else {
  270. fprintf(stderr,"ERROR: LFDB: node is offline" ZT_EOL_S);
  271. }
  272. }
  273. timeRangeStart = time(nullptr) - 120; // start next query 2m before now to avoid losing updates
  274. _ready = true;
  275. for(int k=0;k<20;++k) { // 2s delay between queries for remotely modified networks or members
  276. if (!_running)
  277. return;
  278. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  279. }
  280. }
  281. });
  282. }
  283. LFDB::~LFDB()
  284. {
  285. _running = false;
  286. _syncThread.join();
  287. }
  288. bool LFDB::waitForReady()
  289. {
  290. while (!_ready) {
  291. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  292. }
  293. return true;
  294. }
  295. bool LFDB::isReady()
  296. {
  297. return (_ready);
  298. }
  299. void LFDB::save(nlohmann::json *orig,nlohmann::json &record)
  300. {
  301. if (orig) {
  302. if (*orig != record) {
  303. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1;
  304. }
  305. } else {
  306. record["revision"] = 1;
  307. }
  308. const std::string objtype = record["objtype"];
  309. if (objtype == "network") {
  310. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  311. if (nwid) {
  312. nlohmann::json old;
  313. get(nwid,old);
  314. if ((!old.is_object())||(old != record)) {
  315. _networkChanged(old,record,true);
  316. {
  317. std::lock_guard<std::mutex> l(_state_l);
  318. _state[nwid].dirty = true;
  319. }
  320. }
  321. }
  322. } else if (objtype == "member") {
  323. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  324. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  325. if ((id)&&(nwid)) {
  326. nlohmann::json network,old;
  327. get(nwid,network,id,old);
  328. if ((!old.is_object())||(old != record)) {
  329. _memberChanged(old,record,true);
  330. {
  331. std::lock_guard<std::mutex> l(_state_l);
  332. _state[nwid].members[id].dirty = true;
  333. }
  334. }
  335. }
  336. }
  337. }
  338. void LFDB::eraseNetwork(const uint64_t networkId)
  339. {
  340. // TODO
  341. }
  342. void LFDB::eraseMember(const uint64_t networkId,const uint64_t memberId)
  343. {
  344. // TODO
  345. }
  346. void LFDB::nodeIsOnline(const uint64_t networkId,const uint64_t memberId,const InetAddress &physicalAddress)
  347. {
  348. std::lock_guard<std::mutex> l(_state_l);
  349. auto nw = _state.find(networkId);
  350. if (nw != _state.end()) {
  351. auto m = nw->second.members.find(memberId);
  352. if (m != nw->second.members.end()) {
  353. m->second.lastOnlineTime = OSUtils::now();
  354. if (physicalAddress)
  355. m->second.lastOnlineAddress = physicalAddress;
  356. m->second.lastOnlineDirty = true;
  357. }
  358. }
  359. }
  360. } // namespace ZeroTier