DB.cpp 11 KB

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