CV2.cpp 16 KB

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