CV2.cpp 36 KB

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