DB.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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("ssoExempt")) member["ssoExempt"] = false;
  56. if (!member.count("ipAssignments")) member["ipAssignments"] = nlohmann::json::array();
  57. if (!member.count("activeBridge")) member["activeBridge"] = false;
  58. if (!member.count("tags")) member["tags"] = nlohmann::json::array();
  59. if (!member.count("capabilities")) member["capabilities"] = nlohmann::json::array();
  60. if (!member.count("creationTime")) member["creationTime"] = OSUtils::now();
  61. if (!member.count("noAutoAssignIps")) member["noAutoAssignIps"] = false;
  62. if (!member.count("revision")) member["revision"] = 0ULL;
  63. if (!member.count("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
  64. if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
  65. if (!member.count("lastAuthorizedCredentialType")) member["lastAuthorizedCredentialType"] = nlohmann::json();
  66. if (!member.count("lastAuthorizedCredential")) member["lastAuthorizedCredential"] = nlohmann::json();
  67. if (!member.count("authenticationExpiryTime")) member["authenticationExpiryTime"] = 0LL;
  68. if (!member.count("vMajor")) member["vMajor"] = -1;
  69. if (!member.count("vMinor")) member["vMinor"] = -1;
  70. if (!member.count("vRev")) member["vRev"] = -1;
  71. if (!member.count("vProto")) member["vProto"] = -1;
  72. if (!member.count("remoteTraceTarget")) member["remoteTraceTarget"] = nlohmann::json();
  73. if (!member.count("removeTraceLevel")) member["remoteTraceLevel"] = 0;
  74. member["objtype"] = "member";
  75. }
  76. void DB::cleanNetwork(nlohmann::json &network)
  77. {
  78. network.erase("clock");
  79. network.erase("authorizedMemberCount");
  80. network.erase("activeMemberCount");
  81. network.erase("totalMemberCount");
  82. network.erase("lastModified");
  83. }
  84. void DB::cleanMember(nlohmann::json &member)
  85. {
  86. member.erase("clock");
  87. member.erase("physicalAddr");
  88. member.erase("recentLog");
  89. member.erase("lastModified");
  90. member.erase("lastRequestMetaData");
  91. member.erase("authenticationURL"); // computed
  92. member.erase("authenticationClientID"); // computed
  93. }
  94. DB::DB() {}
  95. DB::~DB() {}
  96. bool DB::get(const uint64_t networkId,nlohmann::json &network)
  97. {
  98. waitForReady();
  99. std::shared_ptr<_Network> nw;
  100. {
  101. std::lock_guard<std::mutex> l(_networks_l);
  102. auto nwi = _networks.find(networkId);
  103. if (nwi == _networks.end())
  104. return false;
  105. nw = nwi->second;
  106. }
  107. {
  108. std::lock_guard<std::mutex> l2(nw->lock);
  109. network = nw->config;
  110. }
  111. return true;
  112. }
  113. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
  114. {
  115. waitForReady();
  116. std::shared_ptr<_Network> nw;
  117. {
  118. std::lock_guard<std::mutex> l(_networks_l);
  119. auto nwi = _networks.find(networkId);
  120. if (nwi == _networks.end())
  121. return false;
  122. nw = nwi->second;
  123. }
  124. {
  125. std::lock_guard<std::mutex> l2(nw->lock);
  126. network = nw->config;
  127. auto m = nw->members.find(memberId);
  128. if (m == nw->members.end())
  129. return false;
  130. member = m->second;
  131. }
  132. return true;
  133. }
  134. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
  135. {
  136. waitForReady();
  137. std::shared_ptr<_Network> nw;
  138. {
  139. std::lock_guard<std::mutex> l(_networks_l);
  140. auto nwi = _networks.find(networkId);
  141. if (nwi == _networks.end())
  142. return false;
  143. nw = nwi->second;
  144. }
  145. {
  146. std::lock_guard<std::mutex> l2(nw->lock);
  147. network = nw->config;
  148. _fillSummaryInfo(nw,info);
  149. auto m = nw->members.find(memberId);
  150. if (m == nw->members.end())
  151. return false;
  152. member = m->second;
  153. }
  154. return true;
  155. }
  156. bool DB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
  157. {
  158. waitForReady();
  159. std::shared_ptr<_Network> nw;
  160. {
  161. std::lock_guard<std::mutex> l(_networks_l);
  162. auto nwi = _networks.find(networkId);
  163. if (nwi == _networks.end())
  164. return false;
  165. nw = nwi->second;
  166. }
  167. {
  168. std::lock_guard<std::mutex> l2(nw->lock);
  169. network = nw->config;
  170. for(auto m=nw->members.begin();m!=nw->members.end();++m) {
  171. members.push_back(m->second);
  172. }
  173. }
  174. return true;
  175. }
  176. void DB::networks(std::set<uint64_t> &networks)
  177. {
  178. waitForReady();
  179. std::lock_guard<std::mutex> l(_networks_l);
  180. for(auto n=_networks.begin();n!=_networks.end();++n)
  181. networks.insert(n->first);
  182. }
  183. void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool notifyListeners)
  184. {
  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. if (networkConfig.is_object()) {
  292. const std::string ids = networkConfig["id"];
  293. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  294. if (networkId) {
  295. std::shared_ptr<_Network> nw;
  296. {
  297. std::lock_guard<std::mutex> l(_networks_l);
  298. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  299. if (!nw2)
  300. nw2.reset(new _Network);
  301. nw = nw2;
  302. }
  303. {
  304. std::lock_guard<std::mutex> l2(nw->lock);
  305. nw->config = networkConfig;
  306. }
  307. if (notifyListeners) {
  308. std::lock_guard<std::mutex> ll(_changeListeners_l);
  309. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  310. (*i)->onNetworkUpdate(this,networkId,networkConfig);
  311. }
  312. }
  313. }
  314. } else if (old.is_object()) {
  315. const std::string ids = old["id"];
  316. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  317. if (networkId) {
  318. std::lock_guard<std::mutex> l(_networks_l);
  319. _networks.erase(networkId);
  320. }
  321. }
  322. }
  323. void DB::_fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info)
  324. {
  325. for(auto ab=nw->activeBridgeMembers.begin();ab!=nw->activeBridgeMembers.end();++ab)
  326. info.activeBridges.push_back(Address(*ab));
  327. std::sort(info.activeBridges.begin(),info.activeBridges.end());
  328. for(auto ip=nw->allocatedIps.begin();ip!=nw->allocatedIps.end();++ip)
  329. info.allocatedIps.push_back(*ip);
  330. std::sort(info.allocatedIps.begin(),info.allocatedIps.end());
  331. info.authorizedMemberCount = (unsigned long)nw->authorizedMembers.size();
  332. info.totalMemberCount = (unsigned long)nw->members.size();
  333. info.mostRecentDeauthTime = nw->mostRecentDeauthTime;
  334. }
  335. } // namespace ZeroTier