CV2.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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 , (EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000)::bigint, "
  332. "(EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000)::bigint, revision "
  333. "FROM networks_ctl WHERE controller_id = '%s'", _myAddressStr.c_str());
  334. auto c = _pool->borrow();
  335. pqxx::work w(*c->c);
  336. fprintf(stderr, "Load networks from psql...\n");
  337. auto stream = pqxx::stream_from::query(w, qbuf);
  338. std::tuple<
  339. std::string // network ID
  340. , std::optional<std::string> // name
  341. , std::string // configuration
  342. , std::optional<uint64_t> // creation_time
  343. , std::optional<uint64_t> // last_modified
  344. , std::optional<uint64_t> // revision
  345. > row;
  346. uint64_t count = 0;
  347. uint64_t total = 0;
  348. while (stream >> row) {
  349. auto start = std::chrono::high_resolution_clock::now();
  350. json empty;
  351. json config;
  352. initNetwork(config);
  353. std::string nwid = std::get<0>(row);
  354. std::string name = std::get<1>(row).value_or("");
  355. json cfgtmp = json::parse(std::get<2>(row));
  356. std::optional<uint64_t> created_at = std::get<3>(row);
  357. std::optional<uint64_t> last_modified = std::get<4>(row);
  358. std::optional<uint64_t> revision = std::get<5>(row);
  359. config["id"] = nwid;
  360. config["name"] = name;
  361. config["creationTime"] = created_at.value_or(0);
  362. config["lastModified"] = last_modified.value_or(0);
  363. config["revision"] = revision.value_or(0);
  364. config["capabilities"] = cfgtmp["capabilities"].is_array() ? cfgtmp["capabilities"] : json::array();
  365. config["enableBroadcast"] = cfgtmp["enableBroadcast"].is_boolean() ? cfgtmp["enableBroadcast"].get<bool>() : false;
  366. config["mtu"] = cfgtmp["mtu"].is_number() ? cfgtmp["mtu"].get<int32_t>() : 2800;
  367. config["multicastLimit"] = cfgtmp["multicastLimit"].is_number() ? cfgtmp["multicastLimit"].get<int32_t>() : 64;
  368. config["private"] = cfgtmp["private"].is_boolean() ? cfgtmp["private"].get<bool>() : true;
  369. config["remoteTraceLevel"] = cfgtmp["remoteTraceLevel"].is_number() ? cfgtmp["remoteTraceLevel"].get<int32_t>() : 0;
  370. config["remoteTraceTarget"] = cfgtmp["remoteTraceTarget"].is_string() ? cfgtmp["remoteTraceTarget"].get<std::string>() : nullptr;
  371. config["revision"] = revision.value_or(0);
  372. config["rules"] = cfgtmp["rules"].is_array() ? cfgtmp["rules"] : json::array();
  373. config["tags"] = cfgtmp["tags"].is_array() ? cfgtmp["tags"] : json::array();
  374. if (cfgtmp["v4AssignMode"].is_object()) {
  375. config["v4AssignMode"] = cfgtmp["v4AssignMode"];
  376. } else {
  377. config["v4AssignMode"] = json::object();
  378. config["v4AssignMode"]["zt"] = true;
  379. }
  380. if (cfgtmp["v6AssignMode"].is_object()) {
  381. config["v6AssignMode"] = cfgtmp["v6AssignMode"];
  382. } else {
  383. config["v6AssignMode"] = json::object();
  384. config["v6AssignMode"]["zt"] = true;
  385. config["v6AssignMode"]["6plane"] = true;
  386. config["v6AssignMode"]["rfc4193"] = false;
  387. }
  388. config["ssoEnabled"] = cfgtmp["ssoEnabled"].is_boolean() ? cfgtmp["ssoEnabled"].get<bool>() : false;
  389. config["objtype"] = "network";
  390. config["routes"] = cfgtmp["routes"].is_array() ? cfgtmp["routes"] : json::array();
  391. config["clientId"] = cfgtmp["clientId"].is_string() ? cfgtmp["clientId"].get<std::string>() : nullptr;
  392. config["authorizationEndpoint"] = cfgtmp["authorizationEndpoint"].is_string() ? cfgtmp["authorizationEndpoint"].get<std::string>() : nullptr;
  393. config["provider"] = cfgtmp["ssoProvider"].is_string() ? cfgtmp["ssoProvider"].get<std::string>() : nullptr;
  394. if (!cfgtmp["dns"].is_object()) {
  395. cfgtmp["dns"] = json::object();
  396. cfgtmp["dns"]["domain"] = "";
  397. cfgtmp["dns"]["servers"] = json::array();
  398. } else {
  399. config["dns"] = cfgtmp["dns"];
  400. }
  401. config["ipAssignmentPools"] = cfgtmp["assignmentPools"].is_array() ? cfgtmp["assignmentPools"] : json::array();
  402. Metrics::network_count++;
  403. _networkChanged(empty, config, false);
  404. auto end = std::chrono::high_resolution_clock::now();
  405. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);;
  406. total += dur.count();
  407. ++count;
  408. if (count > 0 && count % 10000 == 0) {
  409. fprintf(stderr, "Averaging %lu us per network\n", (total/count));
  410. }
  411. }
  412. w.commit();
  413. _pool->unborrow(c);
  414. fprintf(stderr, "done.\n");
  415. if (++this->_ready == 2) {
  416. if (_waitNoticePrinted) {
  417. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  418. }
  419. _readyLock.unlock();
  420. }
  421. fprintf(stderr, "network init done\n");
  422. } catch (std::exception &e) {
  423. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  424. std::this_thread::sleep_for(std::chrono::milliseconds(5000));
  425. exit(-1);
  426. }
  427. }
  428. void CV2::initializeMembers()
  429. {
  430. std::string memberId;
  431. std::string networkId;
  432. try {
  433. char qbuf[2048];
  434. sprintf(qbuf,
  435. "SELECT nm.device_id, nm.network_id, nm.authorized, nm.active_bridge, nm.ip_assignments, nm.no_auto_assign_ips, "
  436. "nm.sso_exempt, (EXTRACT(EPOCH FROM nm.authentication_expiry_time AT TIME ZONE 'UTC')*1000)::bigint, "
  437. "EXTRACT(EPOCH FROM nm.creation_time AT TIME ZONE 'UTC')*1000)::bigint, nm.identity, nm.last_authorized_credential, "
  438. "EXTRACT(EPOCH FROM nm.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  439. "EXTRACT(EPOCH FROM nm.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  440. "nm.remote_trace_level, nm.remote_trace_target, nm.revision, nm.capabilities, nm.tags "
  441. "FROM network_memberships_ctl nm "
  442. "INNER JOIN networks_ctl n "
  443. " ON nm.network_id = n.id "
  444. "WHERE n.controller_id = '%s'", _myAddressStr.c_str());
  445. auto c = _pool->borrow();
  446. pqxx::work w(*c->c);
  447. fprintf(stderr, "Load members from psql...\n");
  448. auto stream = pqxx::stream_from::query(w, qbuf);
  449. std::tuple<
  450. std::string // device ID
  451. , std::string // network ID
  452. , bool // authorized
  453. , std::optional<bool> // active_bridge
  454. , std::optional<std::string> // ip_assignments
  455. , std::optional<bool> // no_auto_assign_ips
  456. , std::optional<bool> // sso_exempt
  457. , std::optional<uint64_t> // authentication_expiry_time
  458. , std::optional<uint64_t> // creation_time
  459. , std::optional<std::string> // identity
  460. , std::optional<std::string> // last_authorized_credential
  461. , std::optional<uint64_t> // last_authorized_time
  462. , std::optional<uint64_t> // last_deauthorized_time
  463. , std::optional<int32_t> // remote_trace_level
  464. , std::optional<std::string> // remote_trace_target
  465. , std::optional<uint64_t> // revision
  466. , std::optional<std::string> // capabilities
  467. , std::optional<std::string> // tags
  468. > row;
  469. uint64_t count = 0;
  470. uint64_t total = 0;
  471. while (stream >> row) {
  472. auto start = std::chrono::high_resolution_clock::now();
  473. json empty;
  474. json config;
  475. initMember(config);
  476. memberId = std::get<0>(row);
  477. networkId = std::get<1>(row);
  478. bool authorized = std::get<2>(row);
  479. std::optional<bool> active_bridge = std::get<3>(row);
  480. std::string ip_assignments = std::get<4>(row).value_or("");
  481. std::optional<bool> no_auto_assign_ips = std::get<5>(row);
  482. std::optional<bool> sso_exempt = std::get<6>(row);
  483. std::optional<uint64_t> authentication_expiry_time = std::get<7>(row);
  484. std::optional<uint64_t> creation_time = std::get<8>(row);
  485. std::optional<std::string> identity = std::get<9>(row);
  486. std::optional<std::string> last_authorized_credential = std::get<10>(row);
  487. std::optional<uint64_t> last_authorized_time = std::get<11>(row);
  488. std::optional<uint64_t> last_deauthorized_time = std::get<12>(row);
  489. std::optional<int32_t> remote_trace_level = std::get<13>(row);
  490. std::optional<std::string> remote_trace_target = std::get<14>(row);
  491. std::optional<uint64_t> revision = std::get<15>(row);
  492. std::optional<std::string> capabilities = std::get<16>(row);
  493. std::optional<std::string> tags = std::get<17>(row);
  494. config["objtype"] = "member";
  495. config["id"] = memberId;
  496. config["address"] = identity.value_or("");
  497. config["nwid"] = networkId;
  498. config["authorized"] = authorized;
  499. config["activeBridge"] = active_bridge.value_or(false);
  500. config["ipAssignments"] = json::array();
  501. if (ip_assignments != "{}") {
  502. std::string tmp = ip_assignments.substr(1, ip_assignments.length() - 2);
  503. std::vector<std::string> addrs = split(tmp, ',');
  504. for (auto it = addrs.begin(); it != addrs.end(); ++it) {
  505. config["ipAssignments"].push_back(*it);
  506. }
  507. }
  508. config["capabilities"] = json::parse(capabilities.value_or("[]"));
  509. config["creationTime"] = creation_time.value_or(0);
  510. config["lastAuthorizedCredential"] = last_authorized_credential.value_or("");
  511. config["lastAuthorizedTime"] = last_authorized_time.value_or(0);
  512. config["lastDeauthorizedTime"] = last_deauthorized_time.value_or(0);
  513. config["noAutoAssignIPs"] = no_auto_assign_ips.value_or(false);
  514. config["remoteTraceLevel"] = remote_trace_level.value_or(0);
  515. config["remoteTraceTarget"] = remote_trace_target.value_or(nullptr);
  516. config["revision"] = revision.value_or(0);
  517. config["ssoExempt"] = sso_exempt.value_or(false);
  518. config["authenticationExpiryTime"] = authentication_expiry_time.value_or(0);
  519. config["tags"] = json::parse(tags.value_or("[]"));
  520. Metrics::member_count++;
  521. _memberChanged(empty, config, false);
  522. memberId = "";
  523. networkId = "";
  524. auto end = std::chrono::high_resolution_clock::now();
  525. auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  526. total += dur.count();
  527. ++count;
  528. if (count > 0 && count % 10000 == 0) {
  529. fprintf(stderr, "Averaging %lu us per member\n", (total/count));
  530. }
  531. }
  532. if (count > 0) {
  533. fprintf(stderr, "Took %lu us per member to load\n", (total/count));
  534. }
  535. stream.complete();
  536. w.commit();
  537. _pool->unborrow(c);
  538. fprintf(stderr, "done.\n");
  539. if (++this->_ready == 2) {
  540. if (_waitNoticePrinted) {
  541. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  542. }
  543. _readyLock.unlock();
  544. }
  545. fprintf(stderr, "member init done\n");
  546. } catch (std::exception &e) {
  547. fprintf(stderr, "ERROR: Error initializing member: %s-%s %s\n", networkId.c_str(), memberId.c_str(), e.what());
  548. exit(-1);
  549. }
  550. }
  551. void CV2::heartbeat()
  552. {
  553. char publicId[1024];
  554. char hostnameTmp[1024];
  555. _myId.toString(false,publicId);
  556. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  557. hostnameTmp[0] = (char)0;
  558. } else {
  559. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  560. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  561. hostnameTmp[i] = (char)0;
  562. break;
  563. }
  564. }
  565. }
  566. const char *controllerId = _myAddressStr.c_str();
  567. const char *publicIdentity = publicId;
  568. const char *hostname = hostnameTmp;
  569. while (_run == 1) {
  570. auto c = _pool->borrow();
  571. int64_t ts = OSUtils::now();
  572. if (c->c) {
  573. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  574. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  575. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  576. std::string version = major + "." + minor + "." + rev;
  577. std::string versionStr = "v" + version;
  578. try {
  579. pqxx::work w{*c->c};
  580. w.exec_params0("INSERT INTO controllers_ctl (id, hostname, last_heartbeat, public_identity, version) VALUES "
  581. "($1, $2, TO_TIMESTAMP($3::double precision/1000), $4, $5) "
  582. "ON CONFLICT (id) DO UPDATE SET hostname = EXCLUDED.hostname, last_heartbeat = EXCLUDED.last_heartbeat, "
  583. "public_identity = EXCLUDED.public_identity, version = EXCLUDED.version",
  584. controllerId, hostname, ts, publicIdentity, versionStr);
  585. w.commit();
  586. } catch (std::exception &e) {
  587. fprintf(stderr, "ERROR: Error in heartbeat: %s\n", e.what());
  588. continue;
  589. } catch (...) {
  590. fprintf(stderr, "ERROR: Unknown error in heartbeat\n");
  591. continue;
  592. }
  593. }
  594. _pool->unborrow(c);
  595. std::this_thread::sleep_for(std::chrono::seconds(1));
  596. }
  597. fprintf(stderr, "Exited heartbeat thread\n");
  598. }
  599. void CV2::membersDbWatcher() {
  600. auto c = _pool->borrow();
  601. std::string stream = "member_" + _myAddressStr;
  602. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  603. MemberNotificationReceiver m(this, *c->c, stream);
  604. while(_run == 1) {
  605. c->c->await_notification(5, 0);
  606. }
  607. _pool->unborrow(c);
  608. fprintf(stderr, "Exited membersDbWatcher\n");
  609. }
  610. void CV2::networksDbWatcher()
  611. {
  612. std::string stream = "network_" + _myAddressStr;
  613. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  614. auto c = _pool->borrow();
  615. NetworkNotificationReceiver n(this, *c->c, stream);
  616. while(_run == 1) {
  617. c->c->await_notification(5,0);
  618. }
  619. _pool->unborrow(c);
  620. fprintf(stderr, "Exited networksDbWatcher\n");
  621. }
  622. void CV2::commitThread()
  623. {
  624. fprintf(stderr, "%s: commitThread start\n", _myAddressStr.c_str());
  625. std::pair<nlohmann::json,bool> qitem;
  626. while(_commitQueue.get(qitem)&&(_run == 1)) {
  627. //fprintf(stderr, "commitThread tick\n");
  628. if (!qitem.first.is_object()) {
  629. fprintf(stderr, "not an object\n");
  630. continue;
  631. }
  632. std::shared_ptr<PostgresConnection> c;
  633. try {
  634. c = _pool->borrow();
  635. } catch (std::exception &e) {
  636. fprintf(stderr, "ERROR: %s\n", e.what());
  637. continue;
  638. }
  639. if (!c) {
  640. fprintf(stderr, "Error getting database connection\n");
  641. continue;
  642. }
  643. Metrics::pgsql_commit_ticks++;
  644. try {
  645. nlohmann::json &config = (qitem.first);
  646. const std::string objtype = config["objtype"];
  647. if (objtype == "member") {
  648. // fprintf(stderr, "%s: commitThread: member\n", _myAddressStr.c_str());
  649. std::string memberId;
  650. std::string networkId;
  651. try {
  652. pqxx::work w(*c->c);
  653. memberId = config["id"];
  654. networkId = config["nwid"];
  655. std::string target = "NULL";
  656. if (!config["remoteTraceTarget"].is_null()) {
  657. target = config["remoteTraceTarget"];
  658. }
  659. pqxx::row nwrow = w.exec_params1("SELECT COUNT(id) FROM networks WHERE id = $1", networkId);
  660. int nwcount = nwrow[0].as<int>();
  661. if (nwcount != 1) {
  662. fprintf(stderr, "network %s does not exist. skipping member upsert\n", networkId.c_str());
  663. w.abort();
  664. _pool->unborrow(c);
  665. continue;
  666. }
  667. // only needed for hooks, and no hooks for now
  668. // pqxx::row mrow = w.exec_params1("SELECT COUNT(id) FROM device_networks WHERE device_id = $1 AND network_id = $2", memberId, networkId);
  669. // int membercount = mrow[0].as<int>();
  670. // bool isNewMember = (membercount == 0);
  671. pqxx::result res = w.exec_params0(
  672. "INSERT INTO network_memberships_ctl (device_id, network_id, authorized, active_bridge, ip_assignments, "
  673. "no_auto_assign_ips, sso_exempt, authentication_expiry_time, capabilities, creation_time, "
  674. "identity, last_authorized_credential, last_authorized_time, last_deauthorized_time, "
  675. "remote_trace_level, remote_trace_target, revision, tags, version_major, version_minor, "
  676. "version_revision, version_protocol) "
  677. "VALUES ($1, $2, $3, $4, $5, $6, $7, TO_TIMESTAMP($8::double precision/1000), $9, "
  678. "TO_TIMESTAMP($10::double precision/1000), $11, 12, TO_TIMESTAMP($13::double precision/1000), "
  679. "TO_TIMESTAMP($14::double precision/1000), $15, $16, $17, $18, $19, $20, $21, $22) "
  680. "ON CONFLICT (device_id, network_id) DO UPDATE SET "
  681. "authorized = EXCLUDED.authorized, active_bridge = EXCLUDED.active_bridge, "
  682. "ip_assignments = EXCLUDED.ip_assignments, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  683. "sso_exempt = EXCLUDED.sso_exempt, authentication_expiry_time = EXCLUDED.authentication_expiry_time, "
  684. "capabilities = EXCLUDED.capabilities, creation_time = EXCLUDED.creation_time, "
  685. "identity = EXCLUDED.identity, last_authorized_credential = EXCLUDED.last_authorized_credential, "
  686. "last_authorized_time = EXCLUDED.last_authorized_time, last_deauthorized_time = EXCLUDED.last_deauthorized_time, "
  687. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  688. "revision = EXCLUDED.revision, tags = EXCLUDED.tags, version_major = EXCLUDED.version_major, "
  689. "version_minor = EXCLUDED.version_minor, version_revision = EXCLUDED.version_revision, "
  690. "version_protocol = EXCLUDED.version_protocol",
  691. memberId,
  692. networkId,
  693. (bool)config["authorized"],
  694. (bool)config["activeBridge"],
  695. config["ipAssignments"].get<std::vector<std::string>>(),
  696. (bool)config["noAutoAssignIps"],
  697. (bool)config["ssoExempt"],
  698. (uint64_t)config["authenticationExpiryTime"],
  699. OSUtils::jsonDump(config["capabilities"], -1),
  700. (uint64_t)config["creationTime"],
  701. OSUtils::jsonString(config["identity"], ""),
  702. OSUtils::jsonString(config["lastAuthorizedCredential"], ""),
  703. (uint64_t)config["lastAuthorizedTime"],
  704. (uint64_t)config["lastDeauthorizedTime"],
  705. (int)config["remoteTraceLevel"],
  706. target,
  707. (uint64_t)config["revision"],
  708. OSUtils::jsonDump(config["tags"], -1),
  709. (int)config["vMajor"],
  710. (int)config["vMinor"],
  711. (int)config["vRev"],
  712. (int)config["vProto"]);
  713. w.commit();
  714. // No hooks for now
  715. // if (_smee != NULL && isNewMember) {
  716. // pqxx::row row = w.exec_params1(
  717. // "SELECT "
  718. // " count(h.hook_id) "
  719. // "FROM "
  720. // " ztc_hook h "
  721. // " INNER JOIN ztc_org o ON o.org_id = h.org_id "
  722. // " INNER JOIN ztc_network n ON n.owner_id = o.owner_id "
  723. // " WHERE "
  724. // "n.id = $1 ",
  725. // networkId
  726. // );
  727. // int64_t hookCount = row[0].as<int64_t>();
  728. // if (hookCount > 0) {
  729. // notifyNewMember(networkId, memberId);
  730. // }
  731. // }
  732. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  733. const uint64_t memberidInt = OSUtils::jsonIntHex(config["id"], 0ULL);
  734. if (nwidInt && memberidInt) {
  735. nlohmann::json nwOrig;
  736. nlohmann::json memOrig;
  737. nlohmann::json memNew(config);
  738. get(nwidInt, nwOrig, memberidInt, memOrig);
  739. _memberChanged(memOrig, memNew, qitem.second);
  740. } else {
  741. 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);
  742. }
  743. } catch (std::exception &e) {
  744. fprintf(stderr, "%s ERROR: Error updating member %s-%s: %s\n", _myAddressStr.c_str(), networkId.c_str(), memberId.c_str(), e.what());
  745. }
  746. } else if (objtype == "network") {
  747. try {
  748. // fprintf(stderr, "%s: commitThread: network\n", _myAddressStr.c_str());
  749. pqxx::work w(*c->c);
  750. std::string id = config["id"];
  751. // network must already exist
  752. pqxx::result res = w.exec_params0(
  753. "INSERT INTO networks_ctl (id, name, configuration, controller_id, revision) "
  754. "VALUES ($1, $2, $3, $4, $5) "
  755. "ON CONFLICT (id) DO UPDATE SET "
  756. "name = EXCLUDED.name, configuration = EXCLUDED.configuration, revision = EXCLUDED.revision+1",
  757. id,
  758. OSUtils::jsonString(config["name"], ""),
  759. OSUtils::jsonDump(config, -1),
  760. _myAddressStr,
  761. ((uint64_t)config["revision"])
  762. );
  763. w.commit();
  764. const uint64_t nwidInt = OSUtils::jsonIntHex(config["nwid"], 0ULL);
  765. if (nwidInt) {
  766. nlohmann::json nwOrig;
  767. nlohmann::json nwNew(config);
  768. get(nwidInt, nwOrig);
  769. _networkChanged(nwOrig, nwNew, qitem.second);
  770. } else {
  771. fprintf(stderr, "%s: Can't notify network changed: %llu\n", _myAddressStr.c_str(), (unsigned long long)nwidInt);
  772. }
  773. } catch (std::exception &e) {
  774. fprintf(stderr, "%s ERROR: Error updating network: %s\n", _myAddressStr.c_str(), e.what());
  775. }
  776. } else if (objtype == "_delete_network") {
  777. // fprintf(stderr, "%s: commitThread: delete network\n", _myAddressStr.c_str());
  778. try {
  779. // don't think we need this. Deletion handled by CV2 API
  780. pqxx::work w(*c->c);
  781. std::string networkId = config["id"];
  782. w.exec_params0("DELETE FROM network_memberships_ctl WHERE network_id = $1", networkId);
  783. w.exec_params0("DELETE FROM networks_ctl WHERE id = $1", networkId);
  784. w.commit();
  785. } catch (std::exception &e) {
  786. fprintf(stderr, "%s ERROR: Error deleting network: %s\n", _myAddressStr.c_str(), e.what());
  787. }
  788. } else if (objtype == "_delete_member") {
  789. // fprintf(stderr, "%s commitThread: delete member\n", _myAddressStr.c_str());
  790. try {
  791. pqxx::work w(*c->c);
  792. std::string memberId = config["id"];
  793. std::string networkId = config["nwid"];
  794. pqxx::result res = w.exec_params0(
  795. "DELETE FROM network_memberships_ctl WHERE device_id = $1 AND network_id = $2",
  796. memberId, networkId);
  797. w.commit();
  798. } catch (std::exception &e) {
  799. fprintf(stderr, "%s ERROR: Error deleting member: %s\n", _myAddressStr.c_str(), e.what());
  800. }
  801. } else {
  802. fprintf(stderr, "%s ERROR: unknown objtype\n", _myAddressStr.c_str());
  803. }
  804. } catch (std::exception &e) {
  805. fprintf(stderr, "%s ERROR: Error getting objtype: %s\n", _myAddressStr.c_str(), e.what());
  806. }
  807. _pool->unborrow(c);
  808. c.reset();
  809. }
  810. fprintf(stderr, "%s commitThread finished\n", _myAddressStr.c_str());
  811. }
  812. void CV2::onlineNotificationThread() {
  813. waitForReady();
  814. _connected = 1;
  815. nlohmann::json jtmp1, jtmp2;
  816. while (_run == 1) {
  817. auto c = _pool->borrow();
  818. auto c2 = _pool->borrow();
  819. try {
  820. fprintf(stderr, "%s onlineNotificationThread\n", _myAddressStr.c_str());
  821. std::unordered_map<std::pair<uint64_t, uint64_t>, std::pair<int64_t, InetAddress>,_PairHasher> lastOnline;
  822. {
  823. std::lock_guard<std::mutex> l(_lastOnline_l);
  824. lastOnline.swap(_lastOnline);
  825. }
  826. pqxx::work w(*c->c);
  827. pqxx::work w2(*c2->c);
  828. bool firstRun = true;
  829. bool memberAdded = false;
  830. uint64_t updateCount = 0;
  831. pqxx::pipeline pipe(w);
  832. for (auto i = lastOnline.begin(); i != lastOnline.end(); ++i) {
  833. updateCount++;
  834. uint64_t nwid_i = i->first.first;
  835. char nwidTmp[64];
  836. char memTmp[64];
  837. char ipTmp[64];
  838. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  839. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  840. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  841. continue; // skip non existent networks/members
  842. }
  843. std::string networkId(nwidTmp);
  844. std::string memberId(memTmp);
  845. try {
  846. pqxx::row r = w2.exec_params1("SELECT device_id, network_id FROM network_memberships_ctl WHERE network_id = $1 AND device_id = $2",
  847. networkId, memberId);
  848. } catch (pqxx::unexpected_rows &e) {
  849. continue;
  850. }
  851. int64_t ts = i->second.first;
  852. std::string ipAddr = i->second.second.toIpString(ipTmp);
  853. std::string timestamp = std::to_string(ts);
  854. json record = {
  855. {ipAddr, ts},
  856. };
  857. std::string device_network_insert = "INSERT INTO network_memberships_ctl (device_id, network_id, last_seen) "
  858. "VALUES ('"+w2.esc(memberId)+"', '"+w2.esc(networkId)+"', '"+w2.esc(record.dump())+"'::JSONB) "
  859. "ON CONFLICT (device_id, network_id) DO UPDATE SET last_seen = last_seen || EXCLUDED.last_seen";
  860. pipe.insert(device_network_insert);
  861. Metrics::pgsql_node_checkin++;
  862. }
  863. pipe.complete();;
  864. w2.commit();
  865. w.commit();
  866. fprintf(stderr, "%s: Updated online status of %lu members\n", _myAddressStr.c_str(), updateCount);
  867. } catch (std::exception &e) {
  868. fprintf(stderr, "%s ERROR: Error in onlineNotificationThread: %s\n", _myAddressStr.c_str(), e.what());
  869. } catch (...) {
  870. fprintf(stderr, "%s ERROR: Unknown error in onlineNotificationThread\n", _myAddressStr.c_str());
  871. }
  872. _pool->unborrow(c2);
  873. _pool->unborrow(c);
  874. std::this_thread::sleep_for(std::chrono::seconds(10));
  875. }
  876. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  877. if (_run == 1) {
  878. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  879. exit(6);
  880. }
  881. }
  882. #endif // ZT_CONTROLLER_USE_LIBPQ