CV2.cpp 36 KB

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