CV2.cpp 36 KB

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