DB.cpp 11 KB

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