DB.cpp 12 KB

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