CV2.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*
  2. * Copyright (c)2025 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2026-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include "CV2.hpp"
  14. #ifdef ZT_CONTROLLER_USE_LIBPQ
  15. #include "../node/Constants.hpp"
  16. #include "../node/SHA512.hpp"
  17. #include "EmbeddedNetworkController.hpp"
  18. #include "../version.h"
  19. #include "CtlUtil.hpp"
  20. #include <libpq-fe.h>
  21. #include <sstream>
  22. #include <iomanip>
  23. #include <climits>
  24. #include <chrono>
  25. using json = nlohmann::json;
  26. namespace {
  27. }
  28. using namespace ZeroTier;
  29. CV2::CV2(const Identity &myId, const char *path, int listenPort)
  30. : DB()
  31. , _pool()
  32. , _myId(myId)
  33. , _myAddress(myId.address())
  34. , _ready(0)
  35. , _connected(1)
  36. , _run(1)
  37. , _waitNoticePrinted(false)
  38. , _listenPort(listenPort)
  39. {
  40. fprintf(stderr, "CV2::CV2\n");
  41. char myAddress[64];
  42. _myAddressStr = myId.address().toString(myAddress);
  43. _connString = std::string(path);
  44. auto f = std::make_shared<PostgresConnFactory>(_connString);
  45. _pool = std::make_shared<ConnectionPool<PostgresConnection> >(
  46. 15, 5, std::static_pointer_cast<ConnectionFactory>(f));
  47. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  48. char *const ssoPskHex = getenv("ZT_SSO_PSK");
  49. #ifdef ZT_TRACE
  50. fprintf(stderr, "ZT_SSO_PSK: %s\n", ssoPskHex);
  51. #endif
  52. if (ssoPskHex) {
  53. // SECURITY: note that ssoPskHex will always be null-terminated if libc actually
  54. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  55. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  56. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  57. }
  58. _readyLock.lock();
  59. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  60. _waitNoticePrinted = true;
  61. initializeNetworks();
  62. initializeMembers();
  63. _heartbeatThread = std::thread(&CV2::heartbeat, this);
  64. _membersDbWatcher = std::thread(&CV2::membersDbWatcher, this);
  65. _networksDbWatcher = std::thread(&CV2::networksDbWatcher, this);
  66. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  67. _commitThread[i] = std::thread(&CV2::commitThread, this);
  68. }
  69. _onlineNotificationThread = std::thread(&CV2::onlineNotificationThread, this);
  70. }
  71. CV2::~CV2()
  72. {
  73. _run = 0;
  74. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  75. _heartbeatThread.join();
  76. _membersDbWatcher.join();
  77. _networksDbWatcher.join();
  78. _commitQueue.stop();
  79. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  80. _commitThread[i].join();
  81. }
  82. _onlineNotificationThread.join();
  83. }
  84. bool CV2::waitForReady()
  85. {
  86. while (_ready < 2) {
  87. _readyLock.lock();
  88. _readyLock.unlock();
  89. }
  90. return true;
  91. }
  92. bool CV2::isReady()
  93. {
  94. return (_ready == 2) && _connected;
  95. }
  96. bool CV2::save(nlohmann::json &record,bool notifyListeners)
  97. {
  98. bool modified = false;
  99. try {
  100. if (!record.is_object()) {
  101. fprintf(stderr, "record is not an object?!?\n");
  102. return false;
  103. }
  104. const std::string objtype = record["objtype"];
  105. if (objtype == "network") {
  106. //fprintf(stderr, "network save\n");
  107. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  108. if (nwid) {
  109. nlohmann::json old;
  110. get(nwid,old);
  111. if ((!old.is_object())||(!_compareRecords(old,record))) {
  112. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  113. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  114. modified = true;
  115. }
  116. }
  117. } else if (objtype == "member") {
  118. std::string networkId = record["nwid"];
  119. std::string memberId = record["id"];
  120. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  121. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  122. //fprintf(stderr, "member save %s-%s\n", networkId.c_str(), memberId.c_str());
  123. if ((id)&&(nwid)) {
  124. nlohmann::json network,old;
  125. get(nwid,network,id,old);
  126. if ((!old.is_object())||(!_compareRecords(old,record))) {
  127. //fprintf(stderr, "commit queue post\n");
  128. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  129. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  130. modified = true;
  131. } else {
  132. //fprintf(stderr, "no change\n");
  133. }
  134. }
  135. } else {
  136. fprintf(stderr, "uhh waaat\n");
  137. }
  138. } catch (std::exception &e) {
  139. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  140. } catch (...) {
  141. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  142. }
  143. return modified;
  144. }
  145. void CV2::eraseNetwork(const uint64_t networkId)
  146. {
  147. fprintf(stderr, "PostgreSQL::eraseNetwork\n");
  148. char tmp2[24];
  149. waitForReady();
  150. Utils::hex(networkId, tmp2);
  151. std::pair<nlohmann::json,bool> tmp;
  152. tmp.first["id"] = tmp2;
  153. tmp.first["objtype"] = "_delete_network";
  154. tmp.second = true;
  155. _commitQueue.post(tmp);
  156. nlohmann::json nullJson;
  157. _networkChanged(tmp.first, nullJson, true);
  158. }
  159. void CV2::eraseMember(const uint64_t networkId, const uint64_t memberId)
  160. {
  161. fprintf(stderr, "PostgreSQL::eraseMember\n");
  162. char tmp2[24];
  163. waitForReady();
  164. std::pair<nlohmann::json,bool> tmp, nw;
  165. Utils::hex(networkId, tmp2);
  166. tmp.first["nwid"] = tmp2;
  167. Utils::hex(memberId, tmp2);
  168. tmp.first["id"] = tmp2;
  169. tmp.first["objtype"] = "_delete_member";
  170. tmp.second = true;
  171. _commitQueue.post(tmp);
  172. nlohmann::json nullJson;
  173. _memberChanged(tmp.first, nullJson, true);
  174. }
  175. void CV2::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  176. {
  177. std::lock_guard<std::mutex> l(_lastOnline_l);
  178. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  179. i.first = OSUtils::now();
  180. if (physicalAddress) {
  181. i.second = physicalAddress;
  182. }
  183. }
  184. AuthInfo CV2::getSSOAuthInfo(const nlohmann::json &member, const std::string &redirectURL)
  185. {
  186. // TODO: Redo this for CV2
  187. Metrics::db_get_sso_info++;
  188. // NONCE is just a random character string. no semantic meaning
  189. // state = HMAC SHA384 of Nonce based on shared sso key
  190. //
  191. // need nonce timeout in database? make sure it's used within X time
  192. // X is 5 minutes for now. Make configurable later?
  193. //
  194. // how do we tell when a nonce is used? if auth_expiration_time is set
  195. std::string networkId = member["nwid"];
  196. std::string memberId = member["id"];
  197. char authenticationURL[4096] = {0};
  198. AuthInfo info;
  199. info.enabled = true;
  200. //if (memberId == "a10dccea52" && networkId == "8056c2e21c24673d") {
  201. // fprintf(stderr, "invalid authinfo for grant's machine\n");
  202. // info.version=1;
  203. // return info;
  204. //}
  205. // fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  206. std::shared_ptr<PostgresConnection> c;
  207. try {
  208. // c = _pool->borrow();
  209. // pqxx::work w(*c->c);
  210. // char nonceBytes[16] = {0};
  211. // std::string nonce = "";
  212. // // check if the member exists first.
  213. // pqxx::row count = w.exec_params1("SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2 AND deleted = false", memberId, networkId);
  214. // if (count[0].as<int>() == 1) {
  215. // // get active nonce, if exists.
  216. // pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  217. // "WHERE network_id = $1 AND member_id = $2 "
  218. // "AND ((NOW() AT TIME ZONE 'UTC') <= authentication_expiry_time) AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  219. // networkId, memberId);
  220. // if (r.size() == 0) {
  221. // // no active nonce.
  222. // // find an unused nonce, if one exists.
  223. // pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  224. // "WHERE network_id = $1 AND member_id = $2 "
  225. // "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  226. // networkId, memberId);
  227. // if (r.size() == 1) {
  228. // // we have an existing nonce. Use it
  229. // nonce = r.at(0)[0].as<std::string>();
  230. // Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  231. // } else if (r.empty()) {
  232. // // create a nonce
  233. // Utils::getSecureRandom(nonceBytes, 16);
  234. // char nonceBuf[64] = {0};
  235. // Utils::hex(nonceBytes, sizeof(nonceBytes), nonceBuf);
  236. // nonce = std::string(nonceBuf);
  237. // pqxx::result ir = w.exec_params0("INSERT INTO ztc_sso_expiry "
  238. // "(nonce, nonce_expiration, network_id, member_id) VALUES "
  239. // "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  240. // nonce, OSUtils::now() + 300000, networkId, memberId);
  241. // w.commit();
  242. // } else {
  243. // // > 1 ?!? Thats an error!
  244. // fprintf(stderr, "> 1 unused nonce!\n");
  245. // exit(6);
  246. // }
  247. // } else if (r.size() == 1) {
  248. // nonce = r.at(0)[0].as<std::string>();
  249. // Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  250. // } else {
  251. // // more than 1 nonce in use? Uhhh...
  252. // fprintf(stderr, "> 1 nonce in use for network member?!?\n");
  253. // exit(7);
  254. // }
  255. // r = w.exec_params(
  256. // "SELECT oc.client_id, oc.authorization_endpoint, oc.issuer, oc.provider, oc.sso_impl_version "
  257. // "FROM ztc_network AS n "
  258. // "INNER JOIN ztc_org o "
  259. // " ON o.owner_id = n.owner_id "
  260. // "LEFT OUTER JOIN ztc_network_oidc_config noc "
  261. // " ON noc.network_id = n.id "
  262. // "LEFT OUTER JOIN ztc_oidc_config oc "
  263. // " ON noc.client_id = oc.client_id AND oc.org_id = o.org_id "
  264. // "WHERE n.id = $1 AND n.sso_enabled = true", networkId);
  265. // std::string client_id = "";
  266. // std::string authorization_endpoint = "";
  267. // std::string issuer = "";
  268. // std::string provider = "";
  269. // uint64_t sso_version = 0;
  270. // if (r.size() == 1) {
  271. // client_id = r.at(0)[0].as<std::optional<std::string>>().value_or("");
  272. // authorization_endpoint = r.at(0)[1].as<std::optional<std::string>>().value_or("");
  273. // issuer = r.at(0)[2].as<std::optional<std::string>>().value_or("");
  274. // provider = r.at(0)[3].as<std::optional<std::string>>().value_or("");
  275. // sso_version = r.at(0)[4].as<std::optional<uint64_t>>().value_or(1);
  276. // } else if (r.size() > 1) {
  277. // fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  278. // } else {
  279. // fprintf(stderr, "No client or auth endpoint?!?\n");
  280. // }
  281. // info.version = sso_version;
  282. // // no catch all else because we don't actually care if no records exist here. just continue as normal.
  283. // if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  284. // uint8_t state[48];
  285. // HMACSHA384(_ssoPsk, nonceBytes, sizeof(nonceBytes), state);
  286. // char state_hex[256];
  287. // Utils::hex(state, 48, state_hex);
  288. // if (info.version == 0) {
  289. // char url[2048] = {0};
  290. // OSUtils::ztsnprintf(url, sizeof(authenticationURL),
  291. // "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redirect_uri=%s&nonce=%s&state=%s&client_id=%s",
  292. // authorization_endpoint.c_str(),
  293. // url_encode(redirectURL).c_str(),
  294. // nonce.c_str(),
  295. // state_hex,
  296. // client_id.c_str());
  297. // info.authenticationURL = std::string(url);
  298. // } else if (info.version == 1) {
  299. // info.ssoClientID = client_id;
  300. // info.issuerURL = issuer;
  301. // info.ssoProvider = provider;
  302. // info.ssoNonce = nonce;
  303. // info.ssoState = std::string(state_hex) + "_" +networkId;
  304. // info.centralAuthURL = redirectURL;
  305. // #ifdef ZT_DEBUG
  306. // fprintf(
  307. // stderr,
  308. // "ssoClientID: %s\nissuerURL: %s\nssoNonce: %s\nssoState: %s\ncentralAuthURL: %s\nprovider: %s\n",
  309. // info.ssoClientID.c_str(),
  310. // info.issuerURL.c_str(),
  311. // info.ssoNonce.c_str(),
  312. // info.ssoState.c_str(),
  313. // info.centralAuthURL.c_str(),
  314. // provider.c_str());
  315. // #endif
  316. // }
  317. // } else {
  318. // fprintf(stderr, "client_id: %s\nauthorization_endpoint: %s\n", client_id.c_str(), authorization_endpoint.c_str());
  319. // }
  320. // }
  321. // _pool->unborrow(c);
  322. } catch (std::exception &e) {
  323. fprintf(stderr, "ERROR: Error updating member on load for network %s: %s\n", networkId.c_str(), e.what());
  324. }
  325. return info; //std::string(authenticationURL);
  326. }
  327. void CV2::initializeNetworks()
  328. { fprintf(stderr, "Initializing networks...\n");
  329. try {
  330. char qbuf[2048];
  331. sprintf(qbuf, "SELECT id, name, configuration , creation_time, last_modified, revision FROM networks_ctl WHERE controller_id = '%s'", _myAddressStr.c_str());
  332. auto c = _pool->borrow();
  333. pqxx::work w(*c->c);
  334. fprintf(stderr, "Load networks from psql...\n");
  335. auto stream = pqxx::stream_from::query(w, qbuf);
  336. std::tuple<
  337. std::string // network ID
  338. , std::optional<std::string> // name
  339. , std::string // configuration
  340. , std::optional<uint64_t> // created_at
  341. , std::optional<uint64_t> // last_modified
  342. , std::optional<uint64_t> // revision
  343. > row;
  344. uint64_t count = 0;
  345. uint64_t total = 0;
  346. while (stream >> row) {
  347. auto start = std::chrono::high_resolution_clock::now();
  348. json empty;
  349. json config;
  350. initNetwork(config);
  351. std::string nwid = std::get<0>(row);
  352. std::string name = std::get<1>(row).value_or("");
  353. json cfgtmp = json::parse(std::get<2>(row));
  354. std::optional<uint64_t> created_at = std::get<3>(row);
  355. std::optional<uint64_t> last_modified = std::get<4>(row);
  356. std::optional<uint64_t> revision = std::get<5>(row);
  357. config["id"] = nwid;
  358. config["name"] = name;
  359. config["creationTime"] = created_at.value_or(0);
  360. config["lastModified"] = last_modified.value_or(0);
  361. config["revision"] = revision.value_or(0);
  362. config["capabilities"] = cfgtmp["capabilities"].is_array() ? cfgtmp["capabilities"] : json::array();
  363. config["enableBroadcast"] = cfgtmp["enableBroadcast"].is_boolean() ? cfgtmp["enableBroadcast"].get<bool>() : false;
  364. config["mtu"] = cfgtmp["mtu"].is_number() ? cfgtmp["mtu"].get<int32_t>() : 2800;
  365. config["multicastLimit"] = cfgtmp["multicastLimit"].is_number() ? cfgtmp["multicastLimit"].get<int32_t>() : 64;
  366. config["private"] = cfgtmp["private"].is_boolean() ? cfgtmp["private"].get<bool>() : true;
  367. config["remoteTraceLevel"] = cfgtmp["remoteTraceLevel"].is_number() ? cfgtmp["remoteTraceLevel"].get<int32_t>() : 0;
  368. config["remoteTraceTarget"] = cfgtmp["remoteTraceTarget"].is_string() ? cfgtmp["remoteTraceTarget"].get<std::string>() : nullptr;
  369. config["revision"] = revision.value_or(0);
  370. config["rules"] = cfgtmp["rules"].is_array() ? cfgtmp["rules"] : json::array();
  371. config["tags"] = cfgtmp["tags"].is_array() ? cfgtmp["tags"] : json::array();
  372. if (cfgtmp["v4AssignMode"].is_object()) {
  373. config["v4AssignMode"] = cfgtmp["v4AssignMode"];
  374. } else {
  375. config["v4AssignMode"] = json::object();
  376. config["v4AssignMode"]["zt"] = true;
  377. }
  378. if (cfgtmp["v6AssignMode"].is_object()) {
  379. config["v6AssignMode"] = cfgtmp["v6AssignMode"];
  380. } else {
  381. config["v6AssignMode"] = json::object();
  382. config["v6AssignMode"]["zt"] = true;
  383. config["v6AssignMode"]["6plane"] = true;
  384. config["v6AssignMode"]["rfc4193"] = false;
  385. }
  386. config["ssoEnabled"] = cfgtmp["ssoEnabled"].is_boolean() ? cfgtmp["ssoEnabled"].get<bool>() : false;
  387. config["objtype"] = "network";
  388. config["routes"] = cfgtmp["routes"].is_array() ? cfgtmp["routes"] : json::array();
  389. config["clientId"] = cfgtmp["clientId"].is_string() ? cfgtmp["clientId"].get<std::string>() : nullptr;
  390. config["authorizationEndpoint"] = cfgtmp["authorizationEndpoint"].is_string() ? cfgtmp["authorizationEndpoint"].get<std::string>() : nullptr;
  391. config["provider"] = cfgtmp["ssoProvider"].is_string() ? cfgtmp["ssoProvider"].get<std::string>() : nullptr;
  392. if (!cfgtmp["dns"].is_object()) {
  393. cfgtmp["dns"] = json::object();
  394. cfgtmp["dns"]["domain"] = "";
  395. cfgtmp["dns"]["servers"] = json::array();
  396. } else {
  397. config["dns"] = cfgtmp["dns"];
  398. }
  399. config["ipAssignmentPools"] = cfgtmp["assignmentPools"].is_array() ? cfgtmp["assignmentPools"] : json::array();
  400. Metrics::network_count++;
  401. _networkChanged(empty, config, false);
  402. auto end = std::chrono::high_resolution_clock::now();
  403. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);;
  404. total += dur.count();
  405. ++count;
  406. if (count > 0 && count % 10000 == 0) {
  407. fprintf(stderr, "Averaging %lu us per network\n", (total/count));
  408. }
  409. }
  410. w.commit();
  411. _pool->unborrow(c);
  412. fprintf(stderr, "done.\n");
  413. if (++this->_ready == 2) {
  414. if (_waitNoticePrinted) {
  415. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  416. }
  417. _readyLock.unlock();
  418. }
  419. fprintf(stderr, "network init done\n");
  420. } catch (std::exception &e) {
  421. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  422. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  423. exit(-1);
  424. }
  425. }
  426. void CV2::initializeMembers()
  427. {
  428. std::string memberId;
  429. std::string networkId;
  430. try {
  431. char qbuf[2048];
  432. sprintf(qbuf,
  433. "SELECT nm.device_id, nm.network_id, nm.authorized, nm.active_bridge, nm.ip_assignments, nm.no_auto_assign_ips, "
  434. "nm.sso_exempt, authentication_expiry_time, nm.creation_time, nm.identity, nm.last_authorized_credential, "
  435. "nm.last_authorized_time, nm.last_deauthorized_time, nm.remote_trace_level, nm.remote_trace_target, "
  436. "nm.revision, nm.capabilities, nm.tags "
  437. "FROM network_memberships_ctl nm "
  438. "INNER JOIN networks n "
  439. " ON nm.network_id = n.id "
  440. "WHERE n.controller_id = '%s'", _myAddressStr.c_str());
  441. auto c = _pool->borrow();
  442. pqxx::work w(*c->c);
  443. fprintf(stderr, "Load members from psql...\n");
  444. auto stream = pqxx::stream_from::query(w, qbuf);
  445. std::tuple<
  446. std::string // device ID
  447. , std::string // network ID
  448. , bool // authorized
  449. , std::optional<bool> // active_bridge
  450. , std::optional<std::string> // ip_assignments
  451. , std::optional<bool> // no_auto_assign_ips
  452. , std::optional<bool> // sso_exempt
  453. , std::optional<uint64_t> // authentication_expiry_time
  454. , std::optional<uint64_t> // creation_time
  455. , std::string // identity
  456. , std::optional<std::string> // last_authorized_credential
  457. , std::optional<uint64_t> // last_authorized_time
  458. , std::optional<uint64_t> // last_deauthorized_time
  459. , std::optional<int32_t> // remote_trace_level
  460. , std::optional<std::string> // remote_trace_target
  461. , std::optional<uint64_t> // revision
  462. , std::optional<std::string> // capabilities
  463. , std::optional<std::string> // tags
  464. > row;
  465. uint64_t count = 0;
  466. uint64_t total = 0;
  467. while (stream >> row) {
  468. auto start = std::chrono::high_resolution_clock::now();
  469. json empty;
  470. json config;
  471. initMember(config);
  472. memberId = std::get<0>(row);
  473. networkId = std::get<1>(row);
  474. bool authorized = std::get<2>(row);
  475. std::optional<bool> active_bridge = std::get<3>(row);
  476. std::string ip_assignments = std::get<4>(row).value_or("");
  477. std::optional<bool> no_auto_assign_ips = std::get<5>(row);
  478. std::optional<bool> sso_exempt = std::get<6>(row);
  479. std::optional<uint64_t> authentication_expiry_time = std::get<7>(row);
  480. std::optional<uint64_t> creation_time = std::get<8>(row);
  481. std::string identity = std::get<9>(row);
  482. std::optional<std::string> last_authorized_credential = std::get<10>(row);
  483. std::optional<uint64_t> last_authorized_time = std::get<11>(row);
  484. std::optional<uint64_t> last_deauthorized_time = std::get<12>(row);
  485. std::optional<int32_t> remote_trace_level = std::get<13>(row);
  486. std::optional<std::string> remote_trace_target = std::get<14>(row);
  487. std::optional<uint64_t> revision = std::get<15>(row);
  488. std::optional<std::string> capabilities = std::get<16>(row);
  489. std::optional<std::string> tags = std::get<17>(row);
  490. config["objtype"] = "member";
  491. config["id"] = memberId;
  492. config["address"] = identity;
  493. config["nwid"] = networkId;
  494. config["authorized"] = authorized;
  495. config["activeBridge"] = active_bridge.value_or(false);
  496. config["ipAssignments"] = json::array();
  497. if (ip_assignments != "{}") {
  498. std::string tmp = ip_assignments.substr(1, ip_assignments.length() - 2);
  499. std::vector<std::string> addrs = split(tmp, ',');
  500. for (auto it = addrs.begin(); it != addrs.end(); ++it) {
  501. config["ipAssignments"].push_back(*it);
  502. }
  503. }
  504. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  505. config["creationTime"] = creation_time.value_or(0);
  506. config["lastAuthorizedCredential"] = last_authorized_credential.value_or("");
  507. config["lastAuthorizedTime"] = last_authorized_time.value_or(0);
  508. config["lastDeauthorizedTime"] = last_deauthorized_time.value_or(0);
  509. config["noAutoAssignIPs"] = no_auto_assign_ips.value_or(false);
  510. config["remoteTraceLevel"] = remote_trace_level.value_or(0);
  511. config["remoteTraceTarget"] = remote_trace_target.value_or(nullptr);
  512. config["revision"] = revision.value_or(0);
  513. config["ssoExempt"] = sso_exempt.value_or(false);
  514. config["authenticationExpiryTime"] = authentication_expiry_time.value_or(0);
  515. config["tags"] = json::parse(tags.value_or("[]"));
  516. Metrics::member_count++;
  517. _memberChanged(empty, config, false);
  518. memberId = "";
  519. networkId = "";
  520. auto end = std::chrono::high_resolution_clock::now();
  521. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  522. total += dur.count();
  523. ++count;
  524. if (count > 0 && count % 10000 == 0) {
  525. fprintf(stderr, "Averaging %lu us per member\n", (total/count));
  526. }
  527. }
  528. if (count > 0) {
  529. fprintf(stderr, "Took %lu us per member to load\n", (total/count));
  530. }
  531. stream.complete();
  532. w.commit();
  533. _pool->unborrow(c);
  534. fprintf(stderr, "done.\n");
  535. if (++this->_ready == 2) {
  536. if (_waitNoticePrinted) {
  537. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  538. }
  539. _readyLock.unlock();
  540. }
  541. fprintf(stderr, "member init done\n");
  542. } catch (std::exception &e) {
  543. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  544. exit(-1);
  545. }
  546. }
  547. void CV2::heartbeat()
  548. {
  549. char publicId[1024];
  550. char hostnameTmp[1024];
  551. _myId.toString(false,publicId);
  552. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  553. hostnameTmp[0] = (char)0;
  554. } else {
  555. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  556. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  557. hostnameTmp[i] = (char)0;
  558. break;
  559. }
  560. }
  561. }
  562. const char *controllerId = _myAddressStr.c_str();
  563. const char *publicIdentity = publicId;
  564. const char *hostname = hostnameTmp;
  565. while (_run == 1) {
  566. auto c = _pool->borrow();
  567. int64_t ts = OSUtils::now();
  568. if (c->c) {
  569. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  570. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  571. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  572. std::string version = major + "." + minor + "." + rev;
  573. std::string versionStr = "v" + version;
  574. try {
  575. pqxx::work w{*c->c};
  576. w.exec_params0("INSERT INTO controllers_ctl (id, hostname, last_heartbeat, public_identity, version) VALUES "
  577. "($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5) "
  578. "ON CONFLICT (id) DO UPDATE SET hostname = EXCLUDED.hostname, last_heartbeat = EXCLUDED.last_heartbeat, "
  579. "public_identity = EXCLUDED.public_identity, version = EXCLUDED.version",
  580. controllerId, hostname, ts, publicIdentity, versionStr);
  581. w.commit();
  582. } catch (std::exception &e) {
  583. fprintf(stderr, "ERROR: Error in heartbeat: %s\n", e.what());
  584. continue;
  585. } catch (...) {
  586. fprintf(stderr, "ERROR: Unknown error in heartbeat\n");
  587. continue;
  588. }
  589. }
  590. _pool->unborrow(c);
  591. std::this_thread::sleep_for(std::chrono::seconds(1));
  592. }
  593. fprintf(stderr, "Exited heartbeat thread\n");
  594. }
  595. void CV2::membersDbWatcher() {
  596. auto c = _pool->borrow();
  597. std::string stream = "member_" + _myAddressStr;
  598. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  599. MemberNotificationReceiver m(this, *c->c, stream);
  600. while(_run == 1) {
  601. c->c->await_notification(5, 0);
  602. }
  603. _pool->unborrow(c);
  604. fprintf(stderr, "Exited membersDbWatcher\n");
  605. }
  606. void CV2::networksDbWatcher()
  607. {
  608. std::string stream = "network_" + _myAddressStr;
  609. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  610. auto c = _pool->borrow();
  611. NetworkNotificationReceiver n(this, *c->c, stream);
  612. while(_run == 1) {
  613. c->c->await_notification(5,0);
  614. }
  615. _pool->unborrow(c);
  616. fprintf(stderr, "Exited networksDbWatcher\n");
  617. }
  618. void CV2::commitThread()
  619. {
  620. fprintf(stderr, "%s: commitThread start\n", _myAddressStr.c_str());
  621. std::pair<nlohmann::json,bool> qitem;
  622. while(_commitQueue.get(qitem)&&(_run == 1)) {
  623. //fprintf(stderr, "commitThread tick\n");
  624. if (!qitem.first.is_object()) {
  625. fprintf(stderr, "not an object\n");
  626. continue;
  627. }
  628. std::shared_ptr<PostgresConnection> c;
  629. try {
  630. c = _pool->borrow();
  631. } catch (std::exception &e) {
  632. fprintf(stderr, "ERROR: %s\n", e.what());
  633. continue;
  634. }
  635. if (!c) {
  636. fprintf(stderr, "Error getting database connection\n");
  637. continue;
  638. }
  639. Metrics::pgsql_commit_ticks++;
  640. try {
  641. nlohmann::json &config = (qitem.first);
  642. const std::string objtype = config["objtype"];
  643. if (objtype == "member") {
  644. // fprintf(stderr, "%s: commitThread: member\n", _myAddressStr.c_str());
  645. std::string memberId;
  646. std::string networkId;
  647. try {
  648. pqxx::work w(*c->c);
  649. memberId = config["id"];
  650. networkId = config["nwid"];
  651. std::string target = "NULL";
  652. if (!config["remoteTraceTarget"].is_null()) {
  653. target = config["remoteTraceTarget"];
  654. }
  655. pqxx::row nwrow = w.exec_params1("SELECT COUNT(id) FROM networks WHERE id = $1", networkId);
  656. int nwcount = nwrow[0].as<int>();
  657. if (nwcount != 1) {
  658. fprintf(stderr, "network %s does not exist. skipping member upsert\n", networkId.c_str());
  659. w.abort();
  660. _pool->unborrow(c);
  661. continue;
  662. }
  663. // only needed for hooks, and no hooks for now
  664. // pqxx::row mrow = w.exec_params1("SELECT COUNT(id) FROM device_networks WHERE device_id = $1 AND network_id = $2", memberId, networkId);
  665. // int membercount = mrow[0].as<int>();
  666. // bool isNewMember = (membercount == 0);
  667. pqxx::result res = w.exec_params0(
  668. "INSERT INTO network_memberships_ctl (device_id, network_id, authorized, active_bridge, ip_assignments, "
  669. "no_auto_assign_ips, sso_exempt, authentication_expiry_time, capabilities, creation_time, "
  670. "identity, last_authorized_credential, last_authorized_time, last_deauthorized_time, "
  671. "remote_trace_level, remote_trace_target, revision, tags, version_major, version_minor, "
  672. "version_revision, version_protocol) "
  673. "VALUES ($1, $2, $3, $4, $5, $6, $7, TO_TIMESTAMP($8::double precision/1000), $9, "
  674. "TO_TIMESTAMP($10::double precision/1000), $11, 12, TO_TIMESTAMP($13::double precision/1000), "
  675. "TO_TIMESTAMP($14::double precision/1000), $15, $16, $17, $18, $19, $20, $21, $22) "
  676. "ON CONFLICT (device_id, network_id) DO UPDATE SET "
  677. "authorized = EXCLUDED.authorized, active_bridge = EXCLUDED.active_bridge, "
  678. "ip_assignments = EXCLUDED.ip_assignments, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  679. "sso_exempt = EXCLUDED.sso_exempt, authentication_expiry_time = EXCLUDED.authentication_expiry_time, "
  680. "capabilities = EXCLUDED.capabilities, creation_time = EXCLUDED.creation_time, "
  681. "identity = EXCLUDED.identity, last_authorized_credential = EXCLUDED.last_authorized_credential, "
  682. "last_authorized_time = EXCLUDED.last_authorized_time, last_deauthorized_time = EXCLUDED.last_deauthorized_time, "
  683. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  684. "revision = EXCLUDED.revision, tags = EXCLUDED.tags, version_major = EXCLUDED.version_major, "
  685. "version_minor = EXCLUDED.version_minor, version_revision = EXCLUDED.version_revision, "
  686. "version_protocol = EXCLUDED.version_protocol",
  687. memberId,
  688. networkId,
  689. (bool)config["authorized"],
  690. (bool)config["activeBridge"],
  691. config["ipAssignments"].get<std::vector<std::string>>(),
  692. (bool)config["noAutoAssignIps"],
  693. (bool)config["ssoExempt"],
  694. (uint64_t)config["authenticationExpiryTime"],
  695. OSUtils::jsonDump(config["capabilities"], -1),
  696. (uint64_t)config["creationTime"],
  697. OSUtils::jsonString(config["identity"], ""),
  698. OSUtils::jsonString(config["lastAuthorizedCredential"], ""),
  699. (uint64_t)config["lastAuthorizedTime"],
  700. (uint64_t)config["lastDeauthorizedTime"],
  701. (int)config["remoteTraceLevel"],
  702. target,
  703. (uint64_t)config["revision"],
  704. OSUtils::jsonDump(config["tags"], -1),
  705. (int)config["vMajor"],
  706. (int)config["vMinor"],
  707. (int)config["vRev"],
  708. (int)config["vProto"]);
  709. w.commit();
  710. // No hooks for now
  711. // if (_smee != NULL && isNewMember) {
  712. // pqxx::row row = w.exec_params1(
  713. // "SELECT "
  714. // " count(h.hook_id) "
  715. // "FROM "
  716. // " ztc_hook h "
  717. // " INNER JOIN ztc_org o ON o.org_id = h.org_id "
  718. // " INNER JOIN ztc_network n ON n.owner_id = o.owner_id "
  719. // " WHERE "
  720. // "n.id = $1 ",
  721. // networkId
  722. // );
  723. // int64_t hookCount = row[0].as<int64_t>();
  724. // if (hookCount > 0) {
  725. // notifyNewMember(networkId, memberId);
  726. // }
  727. // }
  728. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  729. const uint64_t memberidInt = OSUtils::jsonIntHex(config["id"], 0ULL);
  730. if (nwidInt && memberidInt) {
  731. nlohmann::json nwOrig;
  732. nlohmann::json memOrig;
  733. nlohmann::json memNew(config);
  734. get(nwidInt, nwOrig, memberidInt, memOrig);
  735. _memberChanged(memOrig, memNew, qitem.second);
  736. } else {
  737. fprintf(stderr, "%s: Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  738. }
  739. } catch (std::exception &e) {
  740. fprintf(stderr, "%s ERROR: Error updating member %s-%s: %s\n", _myAddressStr.c_str(), networkId.c_str(), memberId.c_str(), e.what());
  741. }
  742. } else if (objtype == "network") {
  743. try {
  744. // fprintf(stderr, "%s: commitThread: network\n", _myAddressStr.c_str());
  745. pqxx::work w(*c->c);
  746. std::string id = config["id"];
  747. // network must already exist
  748. pqxx::result res = w.exec_params0(
  749. "INSERT INTO networks_ctl (id, name, configuration, controller_id, revision) "
  750. "VALUES ($1, $2, $3, $4, $5) "
  751. "ON CONFLICT (id) DO UPDATE SET "
  752. "name = EXCLUDED.name, configuration = EXCLUDED.configuration, revision = EXCLUDED.revision+1",
  753. id,
  754. OSUtils::jsonString(config["name"], ""),
  755. OSUtils::jsonDump(config, -1),
  756. _myAddressStr,
  757. ((uint64_t)config["revision"])
  758. );
  759. w.commit();
  760. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  761. if (nwidInt) {
  762. nlohmann::json nwOrig;
  763. nlohmann::json nwNew(config);
  764. get(nwidInt, nwOrig);
  765. _networkChanged(nwOrig, nwNew, qitem.second);
  766. } else {
  767. fprintf(stderr, "%s: Can't notify network changed: %llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt);
  768. }
  769. } catch (std::exception &e) {
  770. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  771. }
  772. } else if (objtype == "_delete_network") {
  773. // fprintf(stderr, "%s: commitThread: delete network\n", _myAddressStr.c_str());
  774. try {
  775. // don't think we need this. Deletion handled by CV2 API
  776. pqxx::work w(*c->c);
  777. std::string networkId = config["id"];
  778. w.exec_params0("DELETE FROM network_memberships_ctl WHERE network_id = $1", networkId);
  779. w.exec_params0("DELETE FROM networks_ctl WHERE id = $1", networkId);
  780. w.commit();
  781. } catch (std::exception &e) {
  782. fprintf(stderr, "%s ERROR: Error deleting network: %s\n", _myAddressStr.c_str(), e.what());
  783. }
  784. } else if (objtype == "_delete_member") {
  785. // fprintf(stderr, "%s commitThread: delete member\n", _myAddressStr.c_str());
  786. try {
  787. pqxx::work w(*c->c);
  788. std::string memberId = config["id"];
  789. std::string networkId = config["nwid"];
  790. pqxx::result res = w.exec_params0(
  791. "DELETE FROM network_memberships_ctl WHERE device_id = $1 AND network_id = $2",
  792. memberId, networkId);
  793. w.commit();
  794. } catch (std::exception &e) {
  795. fprintf(stderr, "%s ERROR: Error deleting member: %s\n", _myAddressStr.c_str(), e.what());
  796. }
  797. } else {
  798. fprintf(stderr, "%s ERROR: unknown objtype\n", _myAddressStr.c_str());
  799. }
  800. } catch (std::exception &e) {
  801. fprintf(stderr, "%s ERROR: Error getting objtype: %s\n", _myAddressStr.c_str(), e.what());
  802. }
  803. _pool->unborrow(c);
  804. c.reset();
  805. }
  806. fprintf(stderr, "%s commitThread finished\n", _myAddressStr.c_str());
  807. }
  808. void CV2::onlineNotificationThread() {
  809. waitForReady();
  810. _connected = 1;
  811. nlohmann::json jtmp1, jtmp2;
  812. while (_run == 1) {
  813. auto c = _pool->borrow();
  814. auto c2 = _pool->borrow();
  815. try {
  816. fprintf(stderr, "%s onlineNotificationThread\n", _myAddressStr.c_str());
  817. std::unordered_map<std::pair<uint64_t, uint64_t>, std::pair<int64_t, InetAddress>,_PairHasher> lastOnline;
  818. {
  819. std::lock_guard<std::mutex> l(_lastOnline_l);
  820. lastOnline.swap(_lastOnline);
  821. }
  822. pqxx::work w(*c->c);
  823. pqxx::work w2(*c2->c);
  824. bool firstRun = true;
  825. bool memberAdded = false;
  826. uint64_t updateCount = 0;
  827. pqxx::pipeline pipe(w);
  828. for (auto i = lastOnline.begin(); i != lastOnline.end(); ++i) {
  829. updateCount++;
  830. uint64_t nwid_i = i->first.first;
  831. char nwidTmp[64];
  832. char memTmp[64];
  833. char ipTmp[64];
  834. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  835. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  836. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  837. continue; // skip non existent networks/members
  838. }
  839. std::string networkId(nwidTmp);
  840. std::string memberId(memTmp);
  841. try {
  842. pqxx::row r = w2.exec_params1("SELECT device_id, network_id FROM network_memberships_ctl WHERE network_id = $1 AND device_id = $2",
  843. networkId, memberId);
  844. } catch (pqxx::unexpected_rows &e) {
  845. continue;
  846. }
  847. int64_t ts = i->second.first;
  848. std::string ipAddr = i->second.second.toIpString(ipTmp);
  849. std::string timestamp = std::to_string(ts);
  850. json record = {
  851. {ipAddr, ts},
  852. };
  853. std::string device_network_insert = "INSERT INTO network_memberships_ctl (device_id, network_id, last_seen) "
  854. "VALUES ('"+w2.esc(memberId)+"', '"+w2.esc(networkId)+"', '"+w2.esc(record.dump())+"'::JSONB) "
  855. "ON CONFLICT (device_id, network_id) DO UPDATE SET last_seen = last_seen || EXCLUDED.last_seen";
  856. pipe.insert(device_network_insert);
  857. Metrics::pgsql_node_checkin++;
  858. }
  859. pipe.complete();;
  860. w2.commit();
  861. w.commit();
  862. fprintf(stderr, "%s: Updated online status of %lu members\n", _myAddressStr.c_str(), updateCount);
  863. } catch (std::exception &e) {
  864. fprintf(stderr, "%s ERROR: Error in onlineNotificationThread: %s\n", _myAddressStr.c_str(), e.what());
  865. } catch (...) {
  866. fprintf(stderr, "%s ERROR: Unknown error in onlineNotificationThread\n", _myAddressStr.c_str());
  867. }
  868. _pool->unborrow(c2);
  869. _pool->unborrow(c);
  870. std::this_thread::sleep_for(std::chrono::seconds(10));
  871. }
  872. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  873. if (_run == 1) {
  874. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  875. exit(6);
  876. }
  877. }
  878. #endif // ZT_CONTROLLER_USE_LIBPQ