CV2.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. char myAddress[64];
  41. _myAddressStr = myId.address().toString(myAddress);
  42. _connString = std::string(path);
  43. auto f = std::make_shared<PostgresConnFactory>(_connString);
  44. _pool = std::make_shared<ConnectionPool<PostgresConnection> >(
  45. 15, 5, std::static_pointer_cast<ConnectionFactory>(f));
  46. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  47. char *const ssoPskHex = getenv("ZT_SSO_PSK");
  48. #ifdef ZT_TRACE
  49. fprintf(stderr, "ZT_SSO_PSK: %s\n", ssoPskHex);
  50. #endif
  51. if (ssoPskHex) {
  52. // SECURITY: note that ssoPskHex will always be null-terminated if libc actually
  53. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  54. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  55. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  56. }
  57. auto c = _pool->borrow();
  58. pqxx::work txn{*c->c};
  59. pqxx::row r{txn.exec1("SELECT version FROM ztc_database")};
  60. int dbVersion = r[0].as<int>();
  61. txn.commit();
  62. // if (dbVersion < DB_MINIMUM_VERSION) {
  63. // fprintf(stderr, "Central database schema version too low. This controller version requires a minimum schema version of %d. Please upgrade your Central instance", DB_MINIMUM_VERSION);
  64. // exit(1);
  65. // }
  66. _pool->unborrow(c);
  67. _readyLock.lock();
  68. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  69. _waitNoticePrinted = true;
  70. initializeNetworks();
  71. initializeMembers();
  72. _heartbeatThread = std::thread(&CV2::heartbeat, this);
  73. _membersDbWatcher = std::thread(&CV2::membersDbWatcher, this);
  74. _networksDbWatcher = std::thread(&CV2::networksDbWatcher, this);
  75. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  76. _commitThread[i] = std::thread(&CV2::commitThread, this);
  77. }
  78. _onlineNotificationThread = std::thread(&CV2::onlineNotificationThread, this);
  79. }
  80. CV2::~CV2()
  81. {
  82. _run = 0;
  83. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  84. _heartbeatThread.join();
  85. _membersDbWatcher.join();
  86. _networksDbWatcher.join();
  87. _commitQueue.stop();
  88. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  89. _commitThread[i].join();
  90. }
  91. _onlineNotificationThread.join();
  92. }
  93. bool CV2::waitForReady()
  94. {
  95. while (_ready < 2) {
  96. _readyLock.lock();
  97. _readyLock.unlock();
  98. }
  99. return true;
  100. }
  101. bool CV2::isReady()
  102. {
  103. return (_ready == 2) && _cldemote;
  104. }
  105. bool CV2::save(nlohmann::json &record,bool notifyListeners)
  106. {
  107. bool modified = false;
  108. try {
  109. if (!record.is_object()) {
  110. fprintf(stderr, "record is not an object?!?\n");
  111. return false;
  112. }
  113. const std::string objtype = record["objtype"];
  114. if (objtype == "network") {
  115. //fprintf(stderr, "network save\n");
  116. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  117. if (nwid) {
  118. nlohmann::json old;
  119. get(nwid,old);
  120. if ((!old.is_object())||(!_compareRecords(old,record))) {
  121. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  122. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  123. modified = true;
  124. }
  125. }
  126. } else if (objtype == "member") {
  127. std::string networkId = record["nwid"];
  128. std::string memberId = record["id"];
  129. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  130. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  131. //fprintf(stderr, "member save %s-%s\n", networkId.c_str(), memberId.c_str());
  132. if ((id)&&(nwid)) {
  133. nlohmann::json network,old;
  134. get(nwid,network,id,old);
  135. if ((!old.is_object())||(!_compareRecords(old,record))) {
  136. //fprintf(stderr, "commit queue post\n");
  137. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  138. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  139. modified = true;
  140. } else {
  141. //fprintf(stderr, "no change\n");
  142. }
  143. }
  144. } else {
  145. fprintf(stderr, "uhh waaat\n");
  146. }
  147. } catch (std::exception &e) {
  148. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  149. } catch (...) {
  150. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  151. }
  152. return modified;
  153. }
  154. void CV2::eraseNetwork(const uint64_t networkId)
  155. {
  156. fprintf(stderr, "PostgreSQL::eraseNetwork\n");
  157. char tmp2[24];
  158. waitForReady();
  159. Utils::hex(networkId, tmp2);
  160. std::pair<nlohmann::json,bool> tmp;
  161. tmp.first["id"] = tmp2;
  162. tmp.first["objtype"] = "_delete_network";
  163. tmp.second = true;
  164. _commitQueue.post(tmp);
  165. nlohmann::json nullJson;
  166. _networkChanged(tmp.first, nullJson, true);
  167. }
  168. void CV2::eraseMember(const uint64_t networkId, const uint64_t memberId)
  169. {
  170. fprintf(stderr, "PostgreSQL::eraseMember\n");
  171. char tmp2[24];
  172. waitForReady();
  173. std::pair<nlohmann::json,bool> tmp, nw;
  174. Utils::hex(networkId, tmp2);
  175. tmp.first["nwid"] = tmp2;
  176. Utils::hex(memberId, tmp2);
  177. tmp.first["id"] = tmp2;
  178. tmp.first["objtype"] = "_delete_member";
  179. tmp.second = true;
  180. _commitQueue.post(tmp);
  181. nlohmann::json nullJson;
  182. _memberChanged(tmp.first, nullJson, true);
  183. }
  184. void CV2::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  185. {
  186. std::lock_guard<std::mutex> l(_lastOnline_l);
  187. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  188. i.first = OSUtils::now();
  189. if (physicalAddress) {
  190. i.second = physicalAddress;
  191. }
  192. }
  193. AuthInfo CV2::getSSOAuthInfo(const nlohmann::json &member, const std::string &redirectURL)
  194. {
  195. // TODO: Redo this for CV2
  196. Metrics::db_get_sso_info++;
  197. // NONCE is just a random character string. no semantic meaning
  198. // state = HMAC SHA384 of Nonce based on shared sso key
  199. //
  200. // need nonce timeout in database? make sure it's used within X time
  201. // X is 5 minutes for now. Make configurable later?
  202. //
  203. // how do we tell when a nonce is used? if auth_expiration_time is set
  204. std::string networkId = member["nwid"];
  205. std::string memberId = member["id"];
  206. char authenticationURL[4096] = {0};
  207. AuthInfo info;
  208. info.enabled = true;
  209. //if (memberId == "a10dccea52" && networkId == "8056c2e21c24673d") {
  210. // fprintf(stderr, "invalid authinfo for grant's machine\n");
  211. // info.version=1;
  212. // return info;
  213. //}
  214. // fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  215. std::shared_ptr<PostgresConnection> c;
  216. try {
  217. // c = _pool->borrow();
  218. // pqxx::work w(*c->c);
  219. // char nonceBytes[16] = {0};
  220. // std::string nonce = "";
  221. // // check if the member exists first.
  222. // pqxx::row count = w.exec_params1("SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2 AND deleted = false", memberId, networkId);
  223. // if (count[0].as<int>() == 1) {
  224. // // get active nonce, if exists.
  225. // pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  226. // "WHERE network_id = $1 AND member_id = $2 "
  227. // "AND ((NOW() AT TIME ZONE 'UTC') <= authentication_expiry_time) AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  228. // networkId, memberId);
  229. // if (r.size() == 0) {
  230. // // no active nonce.
  231. // // find an unused nonce, if one exists.
  232. // pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  233. // "WHERE network_id = $1 AND member_id = $2 "
  234. // "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  235. // networkId, memberId);
  236. // if (r.size() == 1) {
  237. // // we have an existing nonce. Use it
  238. // nonce = r.at(0)[0].as<std::string>();
  239. // Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  240. // } else if (r.empty()) {
  241. // // create a nonce
  242. // Utils::getSecureRandom(nonceBytes, 16);
  243. // char nonceBuf[64] = {0};
  244. // Utils::hex(nonceBytes, sizeof(nonceBytes), nonceBuf);
  245. // nonce = std::string(nonceBuf);
  246. // pqxx::result ir = w.exec_params0("INSERT INTO ztc_sso_expiry "
  247. // "(nonce, nonce_expiration, network_id, member_id) VALUES "
  248. // "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  249. // nonce, OSUtils::now() + 300000, networkId, memberId);
  250. // w.commit();
  251. // } else {
  252. // // > 1 ?!? Thats an error!
  253. // fprintf(stderr, "> 1 unused nonce!\n");
  254. // exit(6);
  255. // }
  256. // } else if (r.size() == 1) {
  257. // nonce = r.at(0)[0].as<std::string>();
  258. // Utils::unhex(nonce.c_str(), nonceBytes, sizeof(nonceBytes));
  259. // } else {
  260. // // more than 1 nonce in use? Uhhh...
  261. // fprintf(stderr, "> 1 nonce in use for network member?!?\n");
  262. // exit(7);
  263. // }
  264. // r = w.exec_params(
  265. // "SELECT oc.client_id, oc.authorization_endpoint, oc.issuer, oc.provider, oc.sso_impl_version "
  266. // "FROM ztc_network AS n "
  267. // "INNER JOIN ztc_org o "
  268. // " ON o.owner_id = n.owner_id "
  269. // "LEFT OUTER JOIN ztc_network_oidc_config noc "
  270. // " ON noc.network_id = n.id "
  271. // "LEFT OUTER JOIN ztc_oidc_config oc "
  272. // " ON noc.client_id = oc.client_id AND oc.org_id = o.org_id "
  273. // "WHERE n.id = $1 AND n.sso_enabled = true", networkId);
  274. // std::string client_id = "";
  275. // std::string authorization_endpoint = "";
  276. // std::string issuer = "";
  277. // std::string provider = "";
  278. // uint64_t sso_version = 0;
  279. // if (r.size() == 1) {
  280. // client_id = r.at(0)[0].as<std::optional<std::string>>().value_or("");
  281. // authorization_endpoint = r.at(0)[1].as<std::optional<std::string>>().value_or("");
  282. // issuer = r.at(0)[2].as<std::optional<std::string>>().value_or("");
  283. // provider = r.at(0)[3].as<std::optional<std::string>>().value_or("");
  284. // sso_version = r.at(0)[4].as<std::optional<uint64_t>>().value_or(1);
  285. // } else if (r.size() > 1) {
  286. // fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  287. // } else {
  288. // fprintf(stderr, "No client or auth endpoint?!?\n");
  289. // }
  290. // info.version = sso_version;
  291. // // no catch all else because we don't actually care if no records exist here. just continue as normal.
  292. // if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  293. // uint8_t state[48];
  294. // HMACSHA384(_ssoPsk, nonceBytes, sizeof(nonceBytes), state);
  295. // char state_hex[256];
  296. // Utils::hex(state, 48, state_hex);
  297. // if (info.version == 0) {
  298. // char url[2048] = {0};
  299. // OSUtils::ztsnprintf(url, sizeof(authenticationURL),
  300. // "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redirect_uri=%s&nonce=%s&state=%s&client_id=%s",
  301. // authorization_endpoint.c_str(),
  302. // url_encode(redirectURL).c_str(),
  303. // nonce.c_str(),
  304. // state_hex,
  305. // client_id.c_str());
  306. // info.authenticationURL = std::string(url);
  307. // } else if (info.version == 1) {
  308. // info.ssoClientID = client_id;
  309. // info.issuerURL = issuer;
  310. // info.ssoProvider = provider;
  311. // info.ssoNonce = nonce;
  312. // info.ssoState = std::string(state_hex) + "_" +networkId;
  313. // info.centralAuthURL = redirectURL;
  314. // #ifdef ZT_DEBUG
  315. // fprintf(
  316. // stderr,
  317. // "ssoClientID: %s\nissuerURL: %s\nssoNonce: %s\nssoState: %s\ncentralAuthURL: %s\nprovider: %s\n",
  318. // info.ssoClientID.c_str(),
  319. // info.issuerURL.c_str(),
  320. // info.ssoNonce.c_str(),
  321. // info.ssoState.c_str(),
  322. // info.centralAuthURL.c_str(),
  323. // provider.c_str());
  324. // #endif
  325. // }
  326. // } else {
  327. // fprintf(stderr, "client_id: %s\nauthorization_endpoint: %s\n", client_id.c_str(), authorization_endpoint.c_str());
  328. // }
  329. // }
  330. // _pool->unborrow(c);
  331. } catch (std::exception &e) {
  332. fprintf(stderr, "ERROR: Error updating member on load for network %s: %s\n", networkId.c_str(), e.what());
  333. }
  334. return info; //std::string(authenticationURL);
  335. }
  336. void CV2::initializeNetworks()
  337. {
  338. try {
  339. // TODO: Update for CV2
  340. if (++this->_ready == 2) {
  341. if (_waitNoticePrinted) {
  342. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  343. }
  344. _readyLock.unlock();
  345. }
  346. fprintf(stderr, "network init done\n");
  347. } catch (std::exception &e) {
  348. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  349. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  350. exit(-1);
  351. }
  352. }
  353. void CV2::initializeMembers()
  354. {
  355. std::string memberId;
  356. std::string networkId;
  357. try {
  358. // TODO: Update for CV2
  359. if (++this->_ready == 2) {
  360. if (_waitNoticePrinted) {
  361. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  362. }
  363. _readyLock.unlock();
  364. }
  365. fprintf(stderr, "member init done\n");
  366. } catch (std::exception &e) {
  367. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  368. exit(-1);
  369. }
  370. }
  371. void CV2::heartbeat()
  372. {
  373. char publicId[1024];
  374. char hostnameTmp[1024];
  375. _myId.toString(false,publicId);
  376. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  377. hostnameTmp[0] = (char)0;
  378. } else {
  379. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  380. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  381. hostnameTmp[i] = (char)0;
  382. break;
  383. }
  384. }
  385. }
  386. const char *controllerId = _myAddressStr.c_str();
  387. const char *publicIdentity = publicId;
  388. const char *hostname = hostnameTmp;
  389. // TODO: Update for CV2
  390. while (_run == 1) {
  391. std::this_thread::sleep_for(std::chrono::seconds(5));
  392. }
  393. fprintf(stderr, "Exited heartbeat thread\n");
  394. }
  395. void CV2::membersDbWatcher() {
  396. auto c = _pool->borrow();
  397. std::string stream = "member_" + _myAddressStr;
  398. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  399. MemberNotificationReceiver m(this, *c->c, stream);
  400. while(_run == 1) {
  401. c->c->await_notification(5, 0);
  402. }
  403. _pool->unborrow(c);
  404. fprintf(stderr, "Exited membersDbWatcher\n");
  405. }
  406. void CV2::networksDbWatcher()
  407. {
  408. std::string stream = "network_" + _myAddressStr;
  409. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  410. auto c = _pool->borrow();
  411. NetworkNotificationReceiver n(this, *c->c, stream);
  412. while(_run == 1) {
  413. c->c->await_notification(5,0);
  414. }
  415. _pool->unborrow(c);
  416. fprintf(stderr, "Exited networksDbWatcher\n");
  417. }
  418. void CV2::commitThread()
  419. {
  420. // TODO: Update for CV2
  421. }
  422. void CV2::onlineNotificationThread() {
  423. waitForReady();
  424. _connected = 1;
  425. nlohmann::json jtmp1, jtmp2;
  426. while (_run == 1) {
  427. // TODO: Update for CV2
  428. }
  429. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  430. if (_run == 1) {
  431. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  432. exit(6);
  433. }
  434. }
  435. #endif // ZT_CONTROLLER_USE_LIBPQ