2
0

DB.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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(const Identity &myId,const char *path) :
  99. _myId(myId),
  100. _myAddress(myId.address()),
  101. _path((path) ? path : "")
  102. {
  103. char tmp[32];
  104. _myAddress.toString(tmp);
  105. _myAddressStr = tmp;
  106. }
  107. DB::~DB() {}
  108. bool DB::get(const uint64_t networkId,nlohmann::json &network)
  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. }
  123. return true;
  124. }
  125. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
  126. {
  127. waitForReady();
  128. std::shared_ptr<_Network> nw;
  129. {
  130. std::lock_guard<std::mutex> l(_networks_l);
  131. auto nwi = _networks.find(networkId);
  132. if (nwi == _networks.end())
  133. return false;
  134. nw = nwi->second;
  135. }
  136. {
  137. std::lock_guard<std::mutex> l2(nw->lock);
  138. network = nw->config;
  139. auto m = nw->members.find(memberId);
  140. if (m == nw->members.end())
  141. return false;
  142. member = m->second;
  143. }
  144. return true;
  145. }
  146. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
  147. {
  148. waitForReady();
  149. std::shared_ptr<_Network> nw;
  150. {
  151. std::lock_guard<std::mutex> l(_networks_l);
  152. auto nwi = _networks.find(networkId);
  153. if (nwi == _networks.end())
  154. return false;
  155. nw = nwi->second;
  156. }
  157. {
  158. std::lock_guard<std::mutex> l2(nw->lock);
  159. network = nw->config;
  160. _fillSummaryInfo(nw,info);
  161. auto m = nw->members.find(memberId);
  162. if (m == nw->members.end())
  163. return false;
  164. member = m->second;
  165. }
  166. return true;
  167. }
  168. bool DB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
  169. {
  170. waitForReady();
  171. std::shared_ptr<_Network> nw;
  172. {
  173. std::lock_guard<std::mutex> l(_networks_l);
  174. auto nwi = _networks.find(networkId);
  175. if (nwi == _networks.end())
  176. return false;
  177. nw = nwi->second;
  178. }
  179. {
  180. std::lock_guard<std::mutex> l2(nw->lock);
  181. network = nw->config;
  182. for(auto m=nw->members.begin();m!=nw->members.end();++m)
  183. members.push_back(m->second);
  184. }
  185. return true;
  186. }
  187. bool DB::summary(const uint64_t networkId,NetworkSummaryInfo &info)
  188. {
  189. waitForReady();
  190. std::shared_ptr<_Network> nw;
  191. {
  192. std::lock_guard<std::mutex> l(_networks_l);
  193. auto nwi = _networks.find(networkId);
  194. if (nwi == _networks.end())
  195. return false;
  196. nw = nwi->second;
  197. }
  198. {
  199. std::lock_guard<std::mutex> l2(nw->lock);
  200. _fillSummaryInfo(nw,info);
  201. }
  202. return true;
  203. }
  204. void DB::networks(std::vector<uint64_t> &networks)
  205. {
  206. waitForReady();
  207. std::lock_guard<std::mutex> l(_networks_l);
  208. networks.reserve(_networks.size() + 1);
  209. for(auto n=_networks.begin();n!=_networks.end();++n)
  210. networks.push_back(n->first);
  211. }
  212. void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool initialized)
  213. {
  214. uint64_t memberId = 0;
  215. uint64_t networkId = 0;
  216. bool isAuth = false;
  217. bool wasAuth = false;
  218. std::shared_ptr<_Network> nw;
  219. if (old.is_object()) {
  220. memberId = OSUtils::jsonIntHex(old["id"],0ULL);
  221. networkId = OSUtils::jsonIntHex(old["nwid"],0ULL);
  222. if ((memberId)&&(networkId)) {
  223. {
  224. std::lock_guard<std::mutex> l(_networks_l);
  225. auto nw2 = _networks.find(networkId);
  226. if (nw2 != _networks.end())
  227. nw = nw2->second;
  228. }
  229. if (nw) {
  230. std::lock_guard<std::mutex> l(nw->lock);
  231. if (OSUtils::jsonBool(old["activeBridge"],false))
  232. nw->activeBridgeMembers.erase(memberId);
  233. wasAuth = OSUtils::jsonBool(old["authorized"],false);
  234. if (wasAuth)
  235. nw->authorizedMembers.erase(memberId);
  236. json &ips = old["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.erase(ipa);
  245. }
  246. }
  247. }
  248. }
  249. }
  250. }
  251. if (memberConfig.is_object()) {
  252. if (!nw) {
  253. memberId = OSUtils::jsonIntHex(memberConfig["id"],0ULL);
  254. networkId = OSUtils::jsonIntHex(memberConfig["nwid"],0ULL);
  255. if ((!memberId)||(!networkId))
  256. return;
  257. std::lock_guard<std::mutex> l(_networks_l);
  258. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  259. if (!nw2)
  260. nw2.reset(new _Network);
  261. nw = nw2;
  262. }
  263. {
  264. std::lock_guard<std::mutex> l(nw->lock);
  265. nw->members[memberId] = memberConfig;
  266. if (OSUtils::jsonBool(memberConfig["activeBridge"],false))
  267. nw->activeBridgeMembers.insert(memberId);
  268. isAuth = OSUtils::jsonBool(memberConfig["authorized"],false);
  269. if (isAuth)
  270. nw->authorizedMembers.insert(memberId);
  271. json &ips = memberConfig["ipAssignments"];
  272. if (ips.is_array()) {
  273. for(unsigned long i=0;i<ips.size();++i) {
  274. json &ipj = ips[i];
  275. if (ipj.is_string()) {
  276. const std::string ips = ipj;
  277. InetAddress ipa(ips.c_str());
  278. ipa.setPort(0);
  279. nw->allocatedIps.insert(ipa);
  280. }
  281. }
  282. }
  283. if (!isAuth) {
  284. const int64_t ldt = (int64_t)OSUtils::jsonInt(memberConfig["lastDeauthorizedTime"],0ULL);
  285. if (ldt > nw->mostRecentDeauthTime)
  286. nw->mostRecentDeauthTime = ldt;
  287. }
  288. }
  289. if (initialized) {
  290. std::lock_guard<std::mutex> ll(_changeListeners_l);
  291. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  292. (*i)->onNetworkMemberUpdate(networkId,memberId,memberConfig);
  293. }
  294. }
  295. } else if (memberId) {
  296. if (nw) {
  297. std::lock_guard<std::mutex> l(nw->lock);
  298. nw->members.erase(memberId);
  299. }
  300. if (networkId) {
  301. std::lock_guard<std::mutex> l(_networks_l);
  302. auto er = _networkByMember.equal_range(memberId);
  303. for(auto i=er.first;i!=er.second;++i) {
  304. if (i->second == networkId) {
  305. _networkByMember.erase(i);
  306. break;
  307. }
  308. }
  309. }
  310. }
  311. if ((initialized)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId))) {
  312. std::lock_guard<std::mutex> ll(_changeListeners_l);
  313. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  314. (*i)->onNetworkMemberDeauthorize(networkId,memberId);
  315. }
  316. }
  317. }
  318. void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool initialized)
  319. {
  320. if (networkConfig.is_object()) {
  321. const std::string ids = networkConfig["id"];
  322. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  323. if (networkId) {
  324. std::shared_ptr<_Network> nw;
  325. {
  326. std::lock_guard<std::mutex> l(_networks_l);
  327. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  328. if (!nw2)
  329. nw2.reset(new _Network);
  330. nw = nw2;
  331. }
  332. {
  333. std::lock_guard<std::mutex> l2(nw->lock);
  334. nw->config = networkConfig;
  335. }
  336. if (initialized) {
  337. std::lock_guard<std::mutex> ll(_changeListeners_l);
  338. for(auto i=_changeListeners.begin();i!=_changeListeners.end();++i) {
  339. (*i)->onNetworkUpdate(networkId,networkConfig);
  340. }
  341. }
  342. }
  343. } else if (old.is_object()) {
  344. const std::string ids = old["id"];
  345. const uint64_t networkId = Utils::hexStrToU64(ids.c_str());
  346. if (networkId) {
  347. std::lock_guard<std::mutex> l(_networks_l);
  348. _networks.erase(networkId);
  349. }
  350. }
  351. }
  352. void DB::_fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info)
  353. {
  354. for(auto ab=nw->activeBridgeMembers.begin();ab!=nw->activeBridgeMembers.end();++ab)
  355. info.activeBridges.push_back(Address(*ab));
  356. std::sort(info.activeBridges.begin(),info.activeBridges.end());
  357. for(auto ip=nw->allocatedIps.begin();ip!=nw->allocatedIps.end();++ip)
  358. info.allocatedIps.push_back(*ip);
  359. std::sort(info.allocatedIps.begin(),info.allocatedIps.end());
  360. info.authorizedMemberCount = (unsigned long)nw->authorizedMembers.size();
  361. info.totalMemberCount = (unsigned long)nw->members.size();
  362. info.mostRecentDeauthTime = nw->mostRecentDeauthTime;
  363. }
  364. } // namespace ZeroTier