DB.cpp 11 KB

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