DB.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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: 2025-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 "DB.hpp"
  14. #include "EmbeddedNetworkController.hpp"
  15. #include <chrono>
  16. #include <algorithm>
  17. #include <stdexcept>
  18. using json = nlohmann::json;
  19. namespace ZeroTier {
  20. void DB::initNetwork(nlohmann::json &network)
  21. {
  22. if (!network.count("private")) network["private"] = true;
  23. if (!network.count("creationTime")) network["creationTime"] = OSUtils::now();
  24. if (!network.count("name")) network["name"] = "";
  25. if (!network.count("multicastLimit")) network["multicastLimit"] = (uint64_t)32;
  26. if (!network.count("enableBroadcast")) network["enableBroadcast"] = true;
  27. if (!network.count("v4AssignMode")) network["v4AssignMode"] = {{"zt",false}};
  28. if (!network.count("v6AssignMode")) network["v6AssignMode"] = {{"rfc4193",false},{"zt",false},{"6plane",false}};
  29. if (!network.count("authTokens")) network["authTokens"] = {{}};
  30. if (!network.count("capabilities")) network["capabilities"] = nlohmann::json::array();
  31. if (!network.count("tags")) network["tags"] = nlohmann::json::array();
  32. if (!network.count("routes")) network["routes"] = nlohmann::json::array();
  33. if (!network.count("ipAssignmentPools")) network["ipAssignmentPools"] = nlohmann::json::array();
  34. if (!network.count("mtu")) network["mtu"] = ZT_DEFAULT_MTU;
  35. if (!network.count("remoteTraceTarget")) network["remoteTraceTarget"] = nlohmann::json();
  36. if (!network.count("removeTraceLevel")) network["remoteTraceLevel"] = 0;
  37. if (!network.count("rulesSource")) network["rulesSource"] = "";
  38. if (!network.count("rules")) {
  39. // If unspecified, rules are set to allow anything and behave like a flat L2 segment
  40. network["rules"] = {{
  41. { "not",false },
  42. { "or", false },
  43. { "type","ACTION_ACCEPT" }
  44. }};
  45. }
  46. if (!network.count("dns")) network["dns"] = nlohmann::json::array();
  47. network["objtype"] = "network";
  48. }
  49. void DB::initMember(nlohmann::json &member)
  50. {
  51. if (!member.count("authorized")) member["authorized"] = false;
  52. if (!member.count("ipAssignments")) member["ipAssignments"] = nlohmann::json::array();
  53. if (!member.count("activeBridge")) member["activeBridge"] = false;
  54. if (!member.count("tags")) member["tags"] = nlohmann::json::array();
  55. if (!member.count("capabilities")) member["capabilities"] = nlohmann::json::array();
  56. if (!member.count("creationTime")) member["creationTime"] = OSUtils::now();
  57. if (!member.count("noAutoAssignIps")) member["noAutoAssignIps"] = false;
  58. if (!member.count("revision")) member["revision"] = 0ULL;
  59. if (!member.count("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
  60. if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
  61. if (!member.count("lastAuthorizedCredentialType")) member["lastAuthorizedCredentialType"] = nlohmann::json();
  62. if (!member.count("lastAuthorizedCredential")) member["lastAuthorizedCredential"] = nlohmann::json();
  63. if (!member.count("authenticationExpiryTime")) member["authenticationExpiryTime"] = -1LL;
  64. if (!member.count("vMajor")) member["vMajor"] = -1;
  65. if (!member.count("vMinor")) member["vMinor"] = -1;
  66. if (!member.count("vRev")) member["vRev"] = -1;
  67. if (!member.count("vProto")) member["vProto"] = -1;
  68. if (!member.count("remoteTraceTarget")) member["remoteTraceTarget"] = nlohmann::json();
  69. if (!member.count("removeTraceLevel")) member["remoteTraceLevel"] = 0;
  70. member["objtype"] = "member";
  71. }
  72. void DB::cleanNetwork(nlohmann::json &network)
  73. {
  74. network.erase("clock");
  75. network.erase("authorizedMemberCount");
  76. network.erase("activeMemberCount");
  77. network.erase("totalMemberCount");
  78. network.erase("lastModified");
  79. }
  80. void DB::cleanMember(nlohmann::json &member)
  81. {
  82. member.erase("clock");
  83. member.erase("physicalAddr");
  84. member.erase("recentLog");
  85. member.erase("lastModified");
  86. member.erase("lastRequestMetaData");
  87. member.erase("authenticationURL"); // computed
  88. member.erase("authenticationClientID"); // computed
  89. }
  90. DB::DB() {}
  91. DB::~DB() {}
  92. bool DB::get(const uint64_t networkId,nlohmann::json &network)
  93. {
  94. waitForReady();
  95. std::shared_ptr<_Network> nw;
  96. {
  97. std::lock_guard<std::mutex> l(_networks_l);
  98. auto nwi = _networks.find(networkId);
  99. if (nwi == _networks.end())
  100. return false;
  101. nw = nwi->second;
  102. }
  103. {
  104. std::lock_guard<std::mutex> l2(nw->lock);
  105. network = nw->config;
  106. }
  107. return true;
  108. }
  109. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
  110. {
  111. waitForReady();
  112. std::shared_ptr<_Network> nw;
  113. {
  114. std::lock_guard<std::mutex> l(_networks_l);
  115. auto nwi = _networks.find(networkId);
  116. if (nwi == _networks.end())
  117. return false;
  118. nw = nwi->second;
  119. }
  120. {
  121. std::lock_guard<std::mutex> l2(nw->lock);
  122. network = nw->config;
  123. auto m = nw->members.find(memberId);
  124. if (m == nw->members.end())
  125. return false;
  126. member = m->second;
  127. updateMemberOnLoad(networkId, memberId, member);
  128. }
  129. return true;
  130. }
  131. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
  132. {
  133. waitForReady();
  134. std::shared_ptr<_Network> nw;
  135. {
  136. std::lock_guard<std::mutex> l(_networks_l);
  137. auto nwi = _networks.find(networkId);
  138. if (nwi == _networks.end())
  139. return false;
  140. nw = nwi->second;
  141. }
  142. {
  143. std::lock_guard<std::mutex> l2(nw->lock);
  144. network = nw->config;
  145. _fillSummaryInfo(nw,info);
  146. auto m = nw->members.find(memberId);
  147. if (m == nw->members.end())
  148. return false;
  149. member = m->second;
  150. updateMemberOnLoad(networkId, memberId, member);
  151. }
  152. return true;
  153. }
  154. bool DB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
  155. {
  156. waitForReady();
  157. std::shared_ptr<_Network> nw;
  158. {
  159. std::lock_guard<std::mutex> l(_networks_l);
  160. auto nwi = _networks.find(networkId);
  161. if (nwi == _networks.end())
  162. return false;
  163. nw = nwi->second;
  164. }
  165. {
  166. std::lock_guard<std::mutex> l2(nw->lock);
  167. network = nw->config;
  168. for(auto m=nw->members.begin();m!=nw->members.end();++m) {
  169. members.push_back(m->second);
  170. updateMemberOnLoad(networkId, m->first, members.back());
  171. }
  172. }
  173. return true;
  174. }
  175. void DB::networks(std::set<uint64_t> &networks)
  176. {
  177. waitForReady();
  178. std::lock_guard<std::mutex> l(_networks_l);
  179. for(auto n=_networks.begin();n!=_networks.end();++n)
  180. networks.insert(n->first);
  181. }
  182. void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners)
  183. {
  184. fprintf(stderr, "DB::_memberChanged\n");
  185. uint64_t memberId = 0;
  186. uint64_t networkId = 0;
  187. bool isAuth = false;
  188. bool wasAuth = false;
  189. std::shared_ptr<_Network> nw;
  190. if (old.is_object()) {
  191. memberId = OSUtils::jsonIntHex(old["id"],0ULL);
  192. networkId = OSUtils::jsonIntHex(old["nwid"],0ULL);
  193. if ((memberId)&&(networkId)) {
  194. {
  195. std::lock_guard<std::mutex> l(_networks_l);
  196. auto nw2 = _networks.find(networkId);
  197. if (nw2 != _networks.end())
  198. nw = nw2->second;
  199. }
  200. if (nw) {
  201. std::lock_guard<std::mutex> l(nw->lock);
  202. if (OSUtils::jsonBool(old["activeBridge"],false))
  203. nw->activeBridgeMembers.erase(memberId);
  204. wasAuth = OSUtils::jsonBool(old["authorized"],false);
  205. if (wasAuth)
  206. nw->authorizedMembers.erase(memberId);
  207. json &ips = old["ipAssignments"];
  208. if (ips.is_array()) {
  209. for(unsigned long i=0;i<ips.size();++i) {
  210. json &ipj = ips[i];
  211. if (ipj.is_string()) {
  212. const std::string ips = ipj;
  213. InetAddress ipa(ips.c_str());
  214. ipa.setPort(0);
  215. nw->allocatedIps.erase(ipa);
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. if (memberConfig.is_object()) {
  223. if (!nw) {
  224. memberId = OSUtils::jsonIntHex(memberConfig["id"],0ULL);
  225. networkId = OSUtils::jsonIntHex(memberConfig["nwid"],0ULL);
  226. if ((!memberId)||(!networkId))
  227. return;
  228. std::lock_guard<std::mutex> l(_networks_l);
  229. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  230. if (!nw2)
  231. nw2.reset(new _Network);
  232. nw = nw2;
  233. }
  234. {
  235. std::lock_guard<std::mutex> l(nw->lock);
  236. nw->members[memberId] = memberConfig;
  237. if (OSUtils::jsonBool(memberConfig["activeBridge"],false))
  238. nw->activeBridgeMembers.insert(memberId);
  239. isAuth = OSUtils::jsonBool(memberConfig["authorized"],false);
  240. if (isAuth)
  241. nw->authorizedMembers.insert(memberId);
  242. json &ips = memberConfig["ipAssignments"];
  243. if (ips.is_array()) {
  244. for(unsigned long i=0;i<ips.size();++i) {
  245. json &ipj = ips[i];
  246. if (ipj.is_string()) {
  247. const std::string ips = ipj;
  248. InetAddress ipa(ips.c_str());
  249. ipa.setPort(0);
  250. nw->allocatedIps.insert(ipa);
  251. }
  252. }
  253. }
  254. if (!isAuth) {
  255. const int64_t ldt = (int64_t)OSUtils::jsonInt(memberConfig["lastDeauthorizedTime"],0ULL);
  256. if (ldt > nw->mostRecentDeauthTime)
  257. nw->mostRecentDeauthTime = ldt;
  258. }
  259. }
  260. if (notifyListeners) {
  261. std::lock_guard<std::mutex> ll(_changeListeners_l);
  262. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  263. (*i)->onNetworkMemberUpdate(this,networkId,memberId,memberConfig);
  264. }
  265. }
  266. } else if (memberId) {
  267. if (nw) {
  268. std::lock_guard<std::mutex> l(nw->lock);
  269. nw->members.erase(memberId);
  270. }
  271. if (networkId) {
  272. std::lock_guard<std::mutex> l(_networks_l);
  273. auto er = _networkByMember.equal_range(memberId);
  274. for(auto i=er.first;i!=er.second;++i) {
  275. if (i->second == networkId) {
  276. _networkByMember.erase(i);
  277. break;
  278. }
  279. }
  280. }
  281. }
  282. if ((notifyListeners)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))) {
  283. std::lock_guard<std::mutex> ll(_changeListeners_l);
  284. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  285. (*i)->onNetworkMemberDeauthorize(this,networkId,memberId);
  286. }
  287. }
  288. }
  289. void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool notifyListeners)
  290. {
  291. fprintf(stderr, "DB::_networkChanged\n");
  292. if (networkConfig.is_object()) {
  293. const std::string ids = networkConfig["id"];
  294. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  295. if (networkId) {
  296. std::shared_ptr<_Network> nw;
  297. {
  298. std::lock_guard<std::mutex> l(_networks_l);
  299. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  300. if (!nw2)
  301. nw2.reset(new _Network);
  302. nw = nw2;
  303. }
  304. {
  305. std::lock_guard<std::mutex> l2(nw->lock);
  306. nw->config = networkConfig;
  307. }
  308. if (notifyListeners) {
  309. std::lock_guard<std::mutex> ll(_changeListeners_l);
  310. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  311. (*i)->onNetworkUpdate(this,networkId,networkConfig);
  312. }
  313. }
  314. }
  315. } else if (old.is_object()) {
  316. const std::string ids = old["id"];
  317. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  318. if (networkId) {
  319. std::lock_guard<std::mutex> l(_networks_l);
  320. _networks.erase(networkId);
  321. }
  322. }
  323. }
  324. void DB::_fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info)
  325. {
  326. for(auto ab=nw->activeBridgeMembers.begin();ab!=nw->activeBridgeMembers.end();++ab)
  327. info.activeBridges.push_back(Address(*ab));
  328. std::sort(info.activeBridges.begin(),info.activeBridges.end());
  329. for(auto ip=nw->allocatedIps.begin();ip!=nw->allocatedIps.end();++ip)
  330. info.allocatedIps.push_back(*ip);
  331. std::sort(info.allocatedIps.begin(),info.allocatedIps.end());
  332. info.authorizedMemberCount = (unsigned long)nw->authorizedMembers.size();
  333. info.totalMemberCount = (unsigned long)nw->members.size();
  334. info.mostRecentDeauthTime = nw->mostRecentDeauthTime;
  335. }
  336. } // namespace ZeroTier