DB.cpp 11 KB

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