DB.cpp 11 KB

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