DB.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 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 &member,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. json &config = old["config"];
  217. if (config.is_object()) {
  218. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  219. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  220. if ((memberId)&&(networkId)) {
  221. {
  222. std::lock_guard<std::mutex> l(_networks_l);
  223. auto nw2 = _networks.find(networkId);
  224. if (nw2 != _networks.end())
  225. nw = nw2->second;
  226. }
  227. if (nw) {
  228. std::lock_guard<std::mutex> l(nw->lock);
  229. if (OSUtils::jsonBool(config["activeBridge"],false))
  230. nw->activeBridgeMembers.erase(memberId);
  231. wasAuth = OSUtils::jsonBool(config["authorized"],false);
  232. if (wasAuth)
  233. nw->authorizedMembers.erase(memberId);
  234. json &ips = config["ipAssignments"];
  235. if (ips.is_array()) {
  236. for(unsigned long i=0;i<ips.size();++i) {
  237. json &ipj = ips[i];
  238. if (ipj.is_string()) {
  239. const std::string ips = ipj;
  240. InetAddress ipa(ips.c_str());
  241. ipa.setPort(0);
  242. nw->allocatedIps.erase(ipa);
  243. }
  244. }
  245. }
  246. }
  247. }
  248. }
  249. }
  250. if (member.is_object()) {
  251. json &config = member["config"];
  252. if (config.is_object()) {
  253. if (!nw) {
  254. memberId = OSUtils::jsonIntHex(config["id"],0ULL);
  255. networkId = OSUtils::jsonIntHex(config["nwid"],0ULL);
  256. if ((!memberId)||(!networkId))
  257. return;
  258. std::lock_guard<std::mutex> l(_networks_l);
  259. std::shared_ptr<_Network> &nw2 = _networks[networkId];
  260. if (!nw2)
  261. nw2.reset(new _Network);
  262. nw = nw2;
  263. }
  264. {
  265. std::lock_guard<std::mutex> l(nw->lock);
  266. nw->members[memberId] = config;
  267. if (OSUtils::jsonBool(config["activeBridge"],false))
  268. nw->activeBridgeMembers.insert(memberId);
  269. isAuth = OSUtils::jsonBool(config["authorized"],false);
  270. if (isAuth)
  271. nw->authorizedMembers.insert(memberId);
  272. json &ips = config["ipAssignments"];
  273. if (ips.is_array()) {
  274. for(unsigned long i=0;i<ips.size();++i) {
  275. json &ipj = ips[i];
  276. if (ipj.is_string()) {
  277. const std::string ips = ipj;
  278. InetAddress ipa(ips.c_str());
  279. ipa.setPort(0);
  280. nw->allocatedIps.insert(ipa);
  281. }
  282. }
  283. }
  284. if (!isAuth) {
  285. const int64_t ldt = (int64_t)OSUtils::jsonInt(config["lastDeauthorizedTime"],0ULL);
  286. if (ldt > nw->mostRecentDeauthTime)
  287. nw->mostRecentDeauthTime = ldt;
  288. }
  289. }
  290. if (push)
  291. _controller->onNetworkMemberUpdate(networkId,memberId);
  292. }
  293. } else if (memberId) {
  294. if (nw) {
  295. std::lock_guard<std::mutex> l(nw->lock);
  296. nw->members.erase(memberId);
  297. }
  298. if (networkId) {
  299. std::lock_guard<std::mutex> l(_networks_l);
  300. auto er = _networkByMember.equal_range(memberId);
  301. for(auto i=er.first;i!=er.second;++i) {
  302. if (i->second == networkId) {
  303. _networkByMember.erase(i);
  304. break;
  305. }
  306. }
  307. }
  308. }
  309. if ((push)&&((wasAuth)&&(!isAuth)&&(networkId)&&(memberId)))
  310. _controller->onNetworkMemberDeauthorize(networkId,memberId);
  311. }
  312. void DB::_networkChanged(nlohmann::json &old,nlohmann::json &network,bool push)
  313. {
  314. if (network.is_object()) {
  315. json &config = network["config"];
  316. if (config.is_object()) {
  317. const std::string ids = config["id"];
  318. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  319. if (id) {
  320. std::shared_ptr<_Network> nw;
  321. {
  322. std::lock_guard<std::mutex> l(_networks_l);
  323. std::shared_ptr<_Network> &nw2 = _networks[id];
  324. if (!nw2)
  325. nw2.reset(new _Network);
  326. nw = nw2;
  327. }
  328. {
  329. std::lock_guard<std::mutex> l2(nw->lock);
  330. nw->config = config;
  331. }
  332. if (push)
  333. _controller->onNetworkUpdate(id);
  334. }
  335. }
  336. } else if (old.is_object()) {
  337. const std::string ids = old["id"];
  338. const uint64_t id = Utils::hexStrToU64(ids.c_str());
  339. if (id) {
  340. std::lock_guard<std::mutex> l(_networks_l);
  341. _networks.erase(id);
  342. }
  343. }
  344. }
  345. void DB::_fillSummaryInfo(const std::shared_ptr<_Network> &nw,NetworkSummaryInfo &info)
  346. {
  347. for(auto ab=nw->activeBridgeMembers.begin();ab!=nw->activeBridgeMembers.end();++ab)
  348. info.activeBridges.push_back(Address(*ab));
  349. for(auto ip=nw->allocatedIps.begin();ip!=nw->allocatedIps.end();++ip)
  350. info.allocatedIps.push_back(*ip);
  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