DB.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc.
  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. #include "DB.hpp"
  19. #include "EmbeddedNetworkController.hpp"
  20. #include <chrono>
  21. #include <algorithm>
  22. #include <stdexcept>
  23. using json = nlohmann::json;
  24. namespace ZeroTier {
  25. void DB::initNetwork(nlohmann::json &network)
  26. {
  27. if (!network.count("private")) network["private"] = true;
  28. if (!network.count("creationTime")) network["creationTime"] = OSUtils::now();
  29. if (!network.count("name")) network["name"] = "";
  30. if (!network.count("multicastLimit")) network["multicastLimit"] = (uint64_t)32;
  31. if (!network.count("enableBroadcast")) network["enableBroadcast"] = true;
  32. if (!network.count("v4AssignMode")) network["v4AssignMode"] = {{"zt",false}};
  33. if (!network.count("v6AssignMode")) network["v6AssignMode"] = {{"rfc4193",false},{"zt",false},{"6plane",false}};
  34. if (!network.count("authTokens")) network["authTokens"] = {{}};
  35. if (!network.count("capabilities")) network["capabilities"] = nlohmann::json::array();
  36. if (!network.count("tags")) network["tags"] = nlohmann::json::array();
  37. if (!network.count("routes")) network["routes"] = nlohmann::json::array();
  38. if (!network.count("ipAssignmentPools")) network["ipAssignmentPools"] = nlohmann::json::array();
  39. //if (!network.count("anchors")) network["anchors"] = nlohmann::json::array();
  40. if (!network.count("mtu")) network["mtu"] = ZT_DEFAULT_MTU;
  41. if (!network.count("remoteTraceTarget")) network["remoteTraceTarget"] = nlohmann::json();
  42. if (!network.count("removeTraceLevel")) network["remoteTraceLevel"] = 0;
  43. if (!network.count("rules")) {
  44. // If unspecified, rules are set to allow anything and behave like a flat L2 segment
  45. network["rules"] = {{
  46. { "not",false },
  47. { "or", false },
  48. { "type","ACTION_ACCEPT" }
  49. }};
  50. }
  51. network["objtype"] = "network";
  52. }
  53. void DB::initMember(nlohmann::json &member)
  54. {
  55. if (!member.count("authorized")) member["authorized"] = false;
  56. if (!member.count("ipAssignments")) member["ipAssignments"] = nlohmann::json::array();
  57. if (!member.count("activeBridge")) member["activeBridge"] = false;
  58. if (!member.count("tags")) member["tags"] = nlohmann::json::array();
  59. if (!member.count("capabilities")) member["capabilities"] = nlohmann::json::array();
  60. if (!member.count("creationTime")) member["creationTime"] = OSUtils::now();
  61. if (!member.count("noAutoAssignIps")) member["noAutoAssignIps"] = false;
  62. if (!member.count("revision")) member["revision"] = 0ULL;
  63. if (!member.count("lastDeauthorizedTime")) member["lastDeauthorizedTime"] = 0ULL;
  64. if (!member.count("lastAuthorizedTime")) member["lastAuthorizedTime"] = 0ULL;
  65. if (!member.count("lastAuthorizedCredentialType")) member["lastAuthorizedCredentialType"] = nlohmann::json();
  66. if (!member.count("lastAuthorizedCredential")) member["lastAuthorizedCredential"] = nlohmann::json();
  67. if (!member.count("vMajor")) member["vMajor"] = -1;
  68. if (!member.count("vMinor")) member["vMinor"] = -1;
  69. if (!member.count("vRev")) member["vRev"] = -1;
  70. if (!member.count("vProto")) member["vProto"] = -1;
  71. if (!member.count("remoteTraceTarget")) member["remoteTraceTarget"] = nlohmann::json();
  72. if (!member.count("removeTraceLevel")) member["remoteTraceLevel"] = 0;
  73. member["objtype"] = "member";
  74. }
  75. void DB::cleanNetwork(nlohmann::json &network)
  76. {
  77. network.erase("clock");
  78. network.erase("authorizedMemberCount");
  79. network.erase("activeMemberCount");
  80. network.erase("totalMemberCount");
  81. network.erase("lastModified");
  82. }
  83. void DB::cleanMember(nlohmann::json &member)
  84. {
  85. member.erase("clock");
  86. member.erase("physicalAddr");
  87. member.erase("recentLog");
  88. member.erase("lastModified");
  89. member.erase("lastRequestMetaData");
  90. }
  91. DB::DB(EmbeddedNetworkController *const nc,const Identity &myId,const char *path) :
  92. _controller(nc),
  93. _myId(myId),
  94. _myAddress(myId.address()),
  95. _path((path) ? path : "")
  96. {
  97. char tmp[32];
  98. _myAddress.toString(tmp);
  99. _myAddressStr = tmp;
  100. }
  101. DB::~DB()
  102. {
  103. }
  104. bool DB::get(const uint64_t networkId,nlohmann::json &network)
  105. {
  106. waitForReady();
  107. std::shared_ptr<_Network> nw;
  108. {
  109. std::lock_guard<std::mutex> l(_networks_l);
  110. auto nwi = _networks.find(networkId);
  111. if (nwi == _networks.end())
  112. return false;
  113. nw = nwi->second;
  114. }
  115. {
  116. std::lock_guard<std::mutex> l2(nw->lock);
  117. network = nw->config;
  118. }
  119. return true;
  120. }
  121. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member)
  122. {
  123. waitForReady();
  124. std::shared_ptr<_Network> nw;
  125. {
  126. std::lock_guard<std::mutex> l(_networks_l);
  127. auto nwi = _networks.find(networkId);
  128. if (nwi == _networks.end())
  129. return false;
  130. nw = nwi->second;
  131. }
  132. {
  133. std::lock_guard<std::mutex> l2(nw->lock);
  134. network = nw->config;
  135. auto m = nw->members.find(memberId);
  136. if (m == nw->members.end())
  137. return false;
  138. member = m->second;
  139. }
  140. return true;
  141. }
  142. bool DB::get(const uint64_t networkId,nlohmann::json &network,const uint64_t memberId,nlohmann::json &member,NetworkSummaryInfo &info)
  143. {
  144. waitForReady();
  145. std::shared_ptr<_Network> nw;
  146. {
  147. std::lock_guard<std::mutex> l(_networks_l);
  148. auto nwi = _networks.find(networkId);
  149. if (nwi == _networks.end())
  150. return false;
  151. nw = nwi->second;
  152. }
  153. {
  154. std::lock_guard<std::mutex> l2(nw->lock);
  155. network = nw->config;
  156. _fillSummaryInfo(nw,info);
  157. auto m = nw->members.find(memberId);
  158. if (m == nw->members.end())
  159. return false;
  160. member = m->second;
  161. }
  162. return true;
  163. }
  164. bool DB::get(const uint64_t networkId,nlohmann::json &network,std::vector<nlohmann::json> &members)
  165. {
  166. waitForReady();
  167. std::shared_ptr<_Network> nw;
  168. {
  169. std::lock_guard<std::mutex> l(_networks_l);
  170. auto nwi = _networks.find(networkId);
  171. if (nwi == _networks.end())
  172. return false;
  173. nw = nwi->second;
  174. }
  175. {
  176. std::lock_guard<std::mutex> l2(nw->lock);
  177. network = nw->config;
  178. for(auto m=nw->members.begin();m!=nw->members.end();++m)
  179. members.push_back(m->second);
  180. }
  181. return true;
  182. }
  183. bool DB::summary(const uint64_t networkId,NetworkSummaryInfo &info)
  184. {
  185. waitForReady();
  186. std::shared_ptr<_Network> nw;
  187. {
  188. std::lock_guard<std::mutex> l(_networks_l);
  189. auto nwi = _networks.find(networkId);
  190. if (nwi == _networks.end())
  191. return false;
  192. nw = nwi->second;
  193. }
  194. {
  195. std::lock_guard<std::mutex> l2(nw->lock);
  196. _fillSummaryInfo(nw,info);
  197. }
  198. return true;
  199. }
  200. void DB::networks(std::vector<uint64_t> &networks)
  201. {
  202. waitForReady();
  203. std::lock_guard<std::mutex> l(_networks_l);
  204. networks.reserve(_networks.size() + 1);
  205. for(auto n=_networks.begin();n!=_networks.end();++n)
  206. networks.push_back(n->first);
  207. }
  208. void DB::_memberChanged(nlohmann::json &old,nlohmann::json &memberConfig,bool push)
  209. {
  210. uint64_t memberId = 0;
  211. uint64_t networkId = 0;
  212. bool isAuth = false;
  213. bool wasAuth = false;
  214. std::shared_ptr<_Network> nw;
  215. if (old.is_object()) {
  216. memberId = OSUtils::jsonIntHex(old["id"],0ULL);
  217. networkId = OSUtils::jsonIntHex(old["nwid"],0ULL);
  218. if ((memberId)&&(networkId)) {
  219. {
  220. std::lock_guard<std::mutex> l(_networks_l);
  221. auto nw2 = _networks.find(networkId);
  222. if (nw2 != _networks.end())
  223. nw = nw2->second;
  224. }
  225. if (nw) {
  226. std::lock_guard<std::mutex> l(nw->lock);
  227. if (OSUtils::jsonBool(old["activeBridge"],false))
  228. nw->activeBridgeMembers.erase(memberId);
  229. wasAuth = OSUtils::jsonBool(old["authorized"],false);
  230. if (wasAuth)
  231. nw->authorizedMembers.erase(memberId);
  232. json &ips = old["ipAssignments"];
  233. if (ips.is_array()) {
  234. for(unsigned long i=0;i<ips.size();++i) {
  235. json &ipj = ips[i];
  236. if (ipj.is_string()) {
  237. const std::string ips = ipj;
  238. InetAddress ipa(ips.c_str());
  239. ipa.setPort(0);
  240. nw->allocatedIps.erase(ipa);
  241. }
  242. }
  243. }
  244. }
  245. }
  246. }
  247. if (memberConfig.is_object()) {
  248. if (!nw) {
  249. memberId = OSUtils::jsonIntHex(memberConfig["id"],0ULL);
  250. networkId = OSUtils::jsonIntHex(memberConfig["nwid"],0ULL);
  251. if ((!memberId)||(!networkId))
  252. return;
  253. std::lock_guard<std::mutex> l(_networks_l);
  254. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  255. if (!nw2)
  256. nw2.reset(new _Network);
  257. nw = nw2;
  258. }
  259. {
  260. std::lock_guard<std::mutex> l(nw->lock);
  261. nw->members[memberId] = memberConfig;
  262. if (OSUtils::jsonBool(memberConfig["activeBridge"],false))
  263. nw->activeBridgeMembers.insert(memberId);
  264. isAuth = OSUtils::jsonBool(memberConfig["authorized"],false);
  265. if (isAuth)
  266. nw->authorizedMembers.insert(memberId);
  267. json &ips = memberConfig["ipAssignments"];
  268. if (ips.is_array()) {
  269. for(unsigned long i=0;i<ips.size();++i) {
  270. json &ipj = ips[i];
  271. if (ipj.is_string()) {
  272. const std::string ips = ipj;
  273. InetAddress ipa(ips.c_str());
  274. ipa.setPort(0);
  275. nw->allocatedIps.insert(ipa);
  276. }
  277. }
  278. }
  279. if (!isAuth) {
  280. const int64_t ldt = (int64_t)OSUtils::jsonInt(memberConfig["lastDeauthorizedTime"],0ULL);
  281. if (ldt > nw->mostRecentDeauthTime)
  282. nw->mostRecentDeauthTime = ldt;
  283. }
  284. }
  285. if (push)
  286. _controller->onNetworkMemberUpdate(networkId,memberId);
  287. } else if (memberId) {
  288. if (nw) {
  289. std::lock_guard<std::mutex> l(nw->lock);
  290. nw->members.erase(memberId);
  291. }
  292. if (networkId) {
  293. std::lock_guard<std::mutex> l(_networks_l);
  294. auto er = _networkByMember.equal_range(memberId);
  295. for(auto i=er.first;i!=er.second;++i) {
  296. if (i->second == networkId) {
  297. _networkByMember.erase(i);
  298. break;
  299. }
  300. }
  301. }
  302. }
  303. /*
  304. if (old.is_object()) {
  305. json &config = old["config"];
  306. if (config.is_object()) {
  307. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  308. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  309. if ((memberId)&&(networkId)) {
  310. {
  311. std::lock_guard<std::mutex> l(_networks_l);
  312. auto nw2 = _networks.find(networkId);
  313. if (nw2 != _networks.end())
  314. nw = nw2->second;
  315. }
  316. if (nw) {
  317. std::lock_guard<std::mutex> l(nw->lock);
  318. if (OSUtils::jsonBool(config["activeBridge"],false))
  319. nw->activeBridgeMembers.erase(memberId);
  320. wasAuth = OSUtils::jsonBool(config["authorized"],false);
  321. if (wasAuth)
  322. nw->authorizedMembers.erase(memberId);
  323. json &ips = config["ipAssignments"];
  324. if (ips.is_array()) {
  325. for(unsigned long i=0;i<ips.size();++i) {
  326. json &ipj = ips[i];
  327. if (ipj.is_string()) {
  328. const std::string ips = ipj;
  329. InetAddress ipa(ips.c_str());
  330. ipa.setPort(0);
  331. nw->allocatedIps.erase(ipa);
  332. }
  333. }
  334. }
  335. }
  336. }
  337. }
  338. }
  339. if (member.is_object()) {
  340. json &config = member["config"];
  341. if (config.is_object()) {
  342. if (!nw) {
  343. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  344. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  345. if ((!memberId)||(!networkId))
  346. return;
  347. std::lock_guard<std::mutex> l(_networks_l);
  348. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  349. if (!nw2)
  350. nw2.reset(new _Network);
  351. nw = nw2;
  352. }
  353. {
  354. std::lock_guard<std::mutex> l(nw->lock);
  355. nw->members[memberId] = config;
  356. if (OSUtils::jsonBool(config["activeBridge"],false))
  357. nw->activeBridgeMembers.insert(memberId);
  358. isAuth = OSUtils::jsonBool(config["authorized"],false);
  359. if (isAuth)
  360. nw->authorizedMembers.insert(memberId);
  361. json &ips = config["ipAssignments"];
  362. if (ips.is_array()) {
  363. for(unsigned long i=0;i<ips.size();++i) {
  364. json &ipj = ips[i];
  365. if (ipj.is_string()) {
  366. const std::string ips = ipj;
  367. InetAddress ipa(ips.c_str());
  368. ipa.setPort(0);
  369. nw->allocatedIps.insert(ipa);
  370. }
  371. }
  372. }
  373. if (!isAuth) {
  374. const int64_t ldt = (int64_t)OSUtils::jsonInt(config["lastDeauthorizedTime"],0ULL);
  375. if (ldt > nw->mostRecentDeauthTime)
  376. nw->mostRecentDeauthTime = ldt;
  377. }
  378. }
  379. if (push)
  380. _controller->onNetworkMemberUpdate(networkId,memberId);
  381. }
  382. } else if (memberId) {
  383. if (nw) {
  384. std::lock_guard<std::mutex> l(nw->lock);
  385. nw->members.erase(memberId);
  386. }
  387. if (networkId) {
  388. std::lock_guard<std::mutex> l(_networks_l);
  389. auto er = _networkByMember.equal_range(memberId);
  390. for(auto i=er.first;i!=er.second;++i) {
  391. if (i->second == networkId) {
  392. _networkByMember.erase(i);
  393. break;
  394. }
  395. }
  396. }
  397. }
  398. */
  399. if ((push)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId)))
  400. _controller->onNetworkMemberDeauthorize(networkId,memberId);
  401. }
  402. void DB::_networkChanged(nlohmann::json &old,nlohmann::json &networkConfig,bool push)
  403. {
  404. if (networkConfig.is_object()) {
  405. const std::string ids = networkConfig["id"];
  406. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  407. if (id) {
  408. std::shared_ptr<_Network> nw;
  409. {
  410. std::lock_guard<std::mutex> l(_networks_l);
  411. std::shared_ptr<_Network> &nw2 = _networks[id];
  412. if (!nw2)
  413. nw2.reset(new _Network);
  414. nw = nw2;
  415. }
  416. {
  417. std::lock_guard<std::mutex> l2(nw->lock);
  418. nw->config = networkConfig;
  419. }
  420. if (push)
  421. _controller->onNetworkUpdate(id);
  422. }
  423. } else if (old.is_object()) {
  424. const std::string ids = old["id"];
  425. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  426. if (id) {
  427. std::lock_guard<std::mutex> l(_networks_l);
  428. _networks.erase(id);
  429. }
  430. }
  431. /*
  432. if (network.is_object()) {
  433. json &config = network["config"];
  434. if (networkConfig.is_object()) {
  435. const std::string ids = config["id"];
  436. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  437. if (id) {
  438. std::shared_ptr<_Network> nw;
  439. {
  440. std::lock_guard<std::mutex> l(_networks_l);
  441. std::shared_ptr<_Network> &nw2 = _networks[id];
  442. if (!nw2)
  443. nw2.reset(new _Network);
  444. nw = nw2;
  445. }
  446. {
  447. std::lock_guard<std::mutex> l2(nw->lock);
  448. nw->config = config;
  449. }
  450. if (push)
  451. _controller->onNetworkUpdate(id);
  452. }
  453. }
  454. } else if (old.is_object()) {
  455. const std::string ids = old["id"];
  456. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  457. if (id) {
  458. std::lock_guard<std::mutex> l(_networks_l);
  459. _networks.erase(id);
  460. }
  461. }
  462. */
  463. }
  464. void DB::_fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info)
  465. {
  466. for(auto ab=nw->activeBridgeMembers.begin();ab!=nw->activeBridgeMembers.end();++ab)
  467. info.activeBridges.push_back(Address(*ab));
  468. std::sort(info.activeBridges.begin(),info.activeBridges.end());
  469. for(auto ip=nw->allocatedIps.begin();ip!=nw->allocatedIps.end();++ip)
  470. info.allocatedIps.push_back(*ip);
  471. std::sort(info.allocatedIps.begin(),info.allocatedIps.end());
  472. info.authorizedMemberCount = (unsigned long)nw->authorizedMembers.size();
  473. info.totalMemberCount = (unsigned long)nw->members.size();
  474. info.mostRecentDeauthTime = nw->mostRecentDeauthTime;
  475. }
  476. } // namespace ZeroTier