PostgreSQL.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  1. /*
  2. * Copyright (c)2019 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: 2025-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 "PostgreSQL.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 "Redis.hpp"
  20. #include <libpq-fe.h>
  21. #include <sstream>
  22. #include <climits>
  23. using json = nlohmann::json;
  24. namespace {
  25. static const int DB_MINIMUM_VERSION = 20;
  26. static const char *_timestr()
  27. {
  28. time_t t = time(0);
  29. char *ts = ctime(&t);
  30. char *p = ts;
  31. if (!p)
  32. return "";
  33. while (*p) {
  34. if (*p == '\n') {
  35. *p = (char)0;
  36. break;
  37. }
  38. ++p;
  39. }
  40. return ts;
  41. }
  42. /*
  43. std::string join(const std::vector<std::string> &elements, const char * const separator)
  44. {
  45. switch(elements.size()) {
  46. case 0:
  47. return "";
  48. case 1:
  49. return elements[0];
  50. default:
  51. std::ostringstream os;
  52. std::copy(elements.begin(), elements.end()-1, std::ostream_iterator<std::string>(os, separator));
  53. os << *elements.rbegin();
  54. return os.str();
  55. }
  56. }
  57. */
  58. } // anonymous namespace
  59. using namespace ZeroTier;
  60. MemberNotificationReceiver::MemberNotificationReceiver(PostgreSQL *p, pqxx::connection &c, const std::string &channel)
  61. : pqxx::notification_receiver(c, channel)
  62. , _psql(p)
  63. {
  64. fprintf(stderr, "initialize MemberNotificaitonReceiver\n");
  65. }
  66. void MemberNotificationReceiver::operator() (const std::string &payload, int packend_pid) {
  67. fprintf(stderr, "Member Notification received: %s\n", payload.c_str());
  68. json tmp(json::parse(payload));
  69. json &ov = tmp["old_val"];
  70. json &nv = tmp["new_val"];
  71. json oldConfig, newConfig;
  72. if (ov.is_object()) oldConfig = ov;
  73. if (nv.is_object()) newConfig = nv;
  74. if (oldConfig.is_object() || newConfig.is_object()) {
  75. _psql->_memberChanged(oldConfig,newConfig,(_psql->_ready>=2));
  76. fprintf(stderr, "payload sent\n");
  77. }
  78. }
  79. NetworkNotificationReceiver::NetworkNotificationReceiver(PostgreSQL *p, pqxx::connection &c, const std::string &channel)
  80. : pqxx::notification_receiver(c, channel)
  81. , _psql(p)
  82. {
  83. fprintf(stderr, "initialize NetworkNotificationReceiver\n");
  84. }
  85. void NetworkNotificationReceiver::operator() (const std::string &payload, int packend_pid) {
  86. fprintf(stderr, "Network Notificaiton received: %s\n", payload.c_str());
  87. json tmp(json::parse(payload));
  88. json &ov = tmp["old_val"];
  89. json &nv = tmp["new_val"];
  90. json oldConfig, newConfig;
  91. if (ov.is_object()) oldConfig = ov;
  92. if (nv.is_object()) newConfig = nv;
  93. if (oldConfig.is_object() || newConfig.is_object()) {
  94. _psql->_networkChanged(oldConfig,newConfig,(_psql->_ready>=2));
  95. fprintf(stderr, "payload sent\n");
  96. }
  97. }
  98. using Attrs = std::vector<std::pair<std::string, std::string>>;
  99. using Item = std::pair<std::string, Attrs>;
  100. using ItemStream = std::vector<Item>;
  101. PostgreSQL::PostgreSQL(const Identity &myId, const char *path, int listenPort, RedisConfig *rc)
  102. : DB()
  103. , _pool()
  104. , _myId(myId)
  105. , _myAddress(myId.address())
  106. , _ready(0)
  107. , _connected(1)
  108. , _run(1)
  109. , _waitNoticePrinted(false)
  110. , _listenPort(listenPort)
  111. , _rc(rc)
  112. , _redis(NULL)
  113. , _cluster(NULL)
  114. {
  115. char myAddress[64];
  116. _myAddressStr = myId.address().toString(myAddress);
  117. _connString = std::string(path) + " application_name=controller_" + _myAddressStr;
  118. auto f = std::make_shared<PostgresConnFactory>(_connString);
  119. _pool = std::make_shared<ConnectionPool<PostgresConnection> >(
  120. 15, 5, std::static_pointer_cast<ConnectionFactory>(f));
  121. memset(_ssoPsk, 0, sizeof(_ssoPsk));
  122. char *const ssoPskHex = getenv("ZT_SSO_PSK");
  123. if (ssoPskHex) {
  124. // SECURITY: note that ssoPskHex will always be null-terminated if libc acatually
  125. // returns something non-NULL. If the hex encodes something shorter than 48 bytes,
  126. // it will be padded at the end with zeroes. If longer, it'll be truncated.
  127. Utils::unhex(ssoPskHex, _ssoPsk, sizeof(_ssoPsk));
  128. }
  129. auto c = _pool->borrow();
  130. pqxx::work txn{*c->c};
  131. pqxx::row r{txn.exec1("SELECT version FROM ztc_database")};
  132. int dbVersion = r[0].as<int>();
  133. txn.commit();
  134. if (dbVersion < DB_MINIMUM_VERSION) {
  135. fprintf(stderr, "Central database schema version too low. This controller version requires a minimum schema version of %d. Please upgrade your Central instance", DB_MINIMUM_VERSION);
  136. exit(1);
  137. }
  138. _pool->unborrow(c);
  139. if (_rc != NULL) {
  140. sw::redis::ConnectionOptions opts;
  141. sw::redis::ConnectionPoolOptions poolOpts;
  142. opts.host = _rc->hostname;
  143. opts.port = _rc->port;
  144. opts.password = _rc->password;
  145. opts.db = 0;
  146. poolOpts.size = 10;
  147. if (_rc->clusterMode) {
  148. fprintf(stderr, "Using Redis in Cluster Mode\n");
  149. _cluster = std::make_shared<sw::redis::RedisCluster>(opts, poolOpts);
  150. } else {
  151. fprintf(stderr, "Using Redis in Standalone Mode\n");
  152. _redis = std::make_shared<sw::redis::Redis>(opts, poolOpts);
  153. }
  154. }
  155. _readyLock.lock();
  156. fprintf(stderr, "[%s] NOTICE: %.10llx controller PostgreSQL waiting for initial data download..." ZT_EOL_S, ::_timestr(), (unsigned long long)_myAddress.toInt());
  157. _waitNoticePrinted = true;
  158. initializeNetworks();
  159. initializeMembers();
  160. _heartbeatThread = std::thread(&PostgreSQL::heartbeat, this);
  161. _membersDbWatcher = std::thread(&PostgreSQL::membersDbWatcher, this);
  162. _networksDbWatcher = std::thread(&PostgreSQL::networksDbWatcher, this);
  163. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  164. _commitThread[i] = std::thread(&PostgreSQL::commitThread, this);
  165. }
  166. _onlineNotificationThread = std::thread(&PostgreSQL::onlineNotificationThread, this);
  167. }
  168. PostgreSQL::~PostgreSQL()
  169. {
  170. _run = 0;
  171. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  172. _heartbeatThread.join();
  173. _membersDbWatcher.join();
  174. _networksDbWatcher.join();
  175. _commitQueue.stop();
  176. for (int i = 0; i < ZT_CENTRAL_CONTROLLER_COMMIT_THREADS; ++i) {
  177. _commitThread[i].join();
  178. }
  179. _onlineNotificationThread.join();
  180. }
  181. bool PostgreSQL::waitForReady()
  182. {
  183. while (_ready < 2) {
  184. _readyLock.lock();
  185. _readyLock.unlock();
  186. }
  187. return true;
  188. }
  189. bool PostgreSQL::isReady()
  190. {
  191. return ((_ready == 2)&&(_connected));
  192. }
  193. bool PostgreSQL::save(nlohmann::json &record,bool notifyListeners)
  194. {
  195. fprintf(stderr, "PostgreSQL::save\n");
  196. bool modified = false;
  197. try {
  198. if (!record.is_object())
  199. return false;
  200. const std::string objtype = record["objtype"];
  201. if (objtype == "network") {
  202. const uint64_t nwid = OSUtils::jsonIntHex(record["id"],0ULL);
  203. if (nwid) {
  204. nlohmann::json old;
  205. get(nwid,old);
  206. if ((!old.is_object())||(!_compareRecords(old,record))) {
  207. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  208. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  209. modified = true;
  210. }
  211. }
  212. } else if (objtype == "member") {
  213. const uint64_t nwid = OSUtils::jsonIntHex(record["nwid"],0ULL);
  214. const uint64_t id = OSUtils::jsonIntHex(record["id"],0ULL);
  215. if ((id)&&(nwid)) {
  216. nlohmann::json network,old;
  217. get(nwid,network,id,old);
  218. if ((!old.is_object())||(!_compareRecords(old,record))) {
  219. record["revision"] = OSUtils::jsonInt(record["revision"],0ULL) + 1ULL;
  220. _commitQueue.post(std::pair<nlohmann::json,bool>(record,notifyListeners));
  221. modified = true;
  222. }
  223. }
  224. }
  225. } catch (std::exception &e) {
  226. fprintf(stderr, "Error on PostgreSQL::save: %s\n", e.what());
  227. } catch (...) {
  228. fprintf(stderr, "Unknown error on PostgreSQL::save\n");
  229. }
  230. return modified;
  231. }
  232. void PostgreSQL::eraseNetwork(const uint64_t networkId)
  233. {
  234. fprintf(stderr, "PostgreSQL::eraseNetwork\n");
  235. char tmp2[24];
  236. waitForReady();
  237. Utils::hex(networkId, tmp2);
  238. std::pair<nlohmann::json,bool> tmp;
  239. tmp.first["id"] = tmp2;
  240. tmp.first["objtype"] = "_delete_network";
  241. tmp.second = true;
  242. _commitQueue.post(tmp);
  243. nlohmann::json nullJson;
  244. _networkChanged(tmp.first, nullJson, true);
  245. }
  246. void PostgreSQL::eraseMember(const uint64_t networkId, const uint64_t memberId)
  247. {
  248. fprintf(stderr, "PostgreSQL::eraseMember\n");
  249. char tmp2[24];
  250. waitForReady();
  251. std::pair<nlohmann::json,bool> tmp, nw;
  252. Utils::hex(networkId, tmp2);
  253. tmp.first["nwid"] = tmp2;
  254. Utils::hex(memberId, tmp2);
  255. tmp.first["id"] = tmp2;
  256. tmp.first["objtype"] = "_delete_member";
  257. tmp.second = true;
  258. _commitQueue.post(tmp);
  259. nlohmann::json nullJson;
  260. _memberChanged(tmp.first, nullJson, true);
  261. }
  262. void PostgreSQL::nodeIsOnline(const uint64_t networkId, const uint64_t memberId, const InetAddress &physicalAddress)
  263. {
  264. std::lock_guard<std::mutex> l(_lastOnline_l);
  265. std::pair<int64_t, InetAddress> &i = _lastOnline[std::pair<uint64_t,uint64_t>(networkId, memberId)];
  266. i.first = OSUtils::now();
  267. if (physicalAddress) {
  268. i.second = physicalAddress;
  269. }
  270. }
  271. std::string PostgreSQL::getSSOAuthURL(const nlohmann::json &member)
  272. {
  273. // NONCE is just a random character string. no semantic meaning
  274. // state = HMAC SHA384 of Nonce based on shared sso key
  275. //
  276. // need nonce timeout in database? make sure it's used within X time
  277. // X is 5 minutes for now. Make configurable later?
  278. //
  279. // how do we tell when a nonce is used? if auth_expiration_time is set
  280. std::string networkId = member["nwid"];
  281. std::string memberId = member["id"];
  282. char authenticationURL[4096] = {0};
  283. fprintf(stderr, "PostgreSQL::updateMemberOnLoad: %s-%s\n", networkId.c_str(), memberId.c_str());
  284. bool have_auth = false;
  285. try {
  286. auto c = _pool->borrow();
  287. pqxx::work w(*c->c);
  288. std::string nonce = "";
  289. // find an unused nonce, if one exists.
  290. pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  291. "WHERE network_id = $1 AND member_id = $2 "
  292. "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  293. networkId, memberId);
  294. if (r.size() == 1) {
  295. // we have an existing nonce. Use it
  296. nonce = r.at(0)[0].as<std::string>();
  297. } else if (r.empty()) {
  298. // create a nonce
  299. char randBuf[16] = {0};
  300. Utils::getSecureRandom(randBuf, 16);
  301. char nonceBuf[256] = {0};
  302. Utils::hex(randBuf, sizeof(randBuf), nonceBuf);
  303. nonce = std::string(nonceBuf);
  304. pqxx::result ir = w.exec_params0("INSERT INTO ztc_sso_expiry "
  305. "(nonce, nonce_expiration, network_id, member_id) VALUES "
  306. "($1, TO_TIMESTAMP($2::double precision/1000) $3, $4)",
  307. nonce, OSUtils::now() + 300000, networkId, memberId);
  308. } else {
  309. // > 1 ?!? Thats an error!
  310. fprintf(stderr, "> 1 unused nonce!\n");
  311. exit(6);
  312. }
  313. r = w.exec_params("SELECT org.client_id, org.authorization_endpoint "
  314. "FROM ztc_network AS nw, ztc_org AS org "
  315. "WHERE nw.id = $1 AND nw.sso_enabled = true AND org.owner_id = nw.owner_id", networkId);
  316. std::string client_id = "";
  317. std::string authorization_endpoint = "";
  318. if (r.size() == 1) {
  319. client_id = r.at(0)[0].as<std::string>();
  320. authorization_endpoint = r.at(0)[1].as<std::string>();
  321. } else if (r.size() > 1) {
  322. fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  323. }
  324. // no catch all else because we don't actually care if no records exist here. just continue as normal.
  325. if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  326. have_auth = true;
  327. uint8_t state[48];
  328. HMACSHA384(_ssoPsk, nonce.data(), (unsigned int)nonce.length(), state);
  329. char state_hex[256];
  330. Utils::hex(state, 48, state_hex);
  331. const char *redirect_url = "redirect_uri=https%3A%2F%2Fmy.zerotier.com%2Fapi%2Fnetwork%2Fsso-auth"; // TODO: this should be configurable
  332. OSUtils::ztsnprintf(authenticationURL, sizeof(authenticationURL),
  333. "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redriect_uri=%s&nonce=%s&state=%s&client_id=%s",
  334. authorization_endpoint.c_str(),
  335. redirect_url,
  336. nonce.c_str(),
  337. state_hex,
  338. client_id.c_str());
  339. }
  340. _pool->unborrow(c);
  341. } catch (std::exception &e) {
  342. fprintf(stderr, "ERROR: Error updating member on load: %s\n", e.what());
  343. exit(-1);
  344. }
  345. return std::string(authenticationURL);
  346. }
  347. void PostgreSQL::initializeNetworks()
  348. {
  349. try {
  350. std::string setKey = "networks:{" + _myAddressStr + "}";
  351. std::unordered_set<std::string> networkSet;
  352. fprintf(stderr, "Initializing Networks...\n");
  353. auto c = _pool->borrow();
  354. pqxx::work w{*c->c};
  355. pqxx::result r = w.exec_params("SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000 as creation_time, capabilities, "
  356. "enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000 AS last_modified, mtu, multicast_limit, name, private, remote_trace_level, "
  357. "remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode, sso_enabled FROM ztc_network "
  358. "WHERE deleted = false AND controller_id = $1", _myAddressStr);
  359. for (auto row = r.begin(); row != r.end(); row++) {
  360. json empty;
  361. json config;
  362. initNetwork(config);
  363. std::string nwid = row[0].as<std::string>();
  364. networkSet.insert(nwid);
  365. config["id"] = nwid;
  366. config["nwid"] = nwid;
  367. try {
  368. config["creationTime"] = row[1].as<int64_t>();
  369. } catch (std::exception &e) {
  370. config["creationTime"] = 0ULL;
  371. }
  372. config["capabilities"] = row[2].as<std::string>();
  373. config["enableBroadcast"] = row[3].as<bool>();
  374. try {
  375. config["lastModified"] = row[4].as<uint64_t>();
  376. } catch (std::exception &e) {
  377. config["lastModified"] = 0ULL;
  378. }
  379. try {
  380. config["mtu"] = row[5].as<int>();
  381. } catch (std::exception &e) {
  382. config["mtu"] = 2800;
  383. }
  384. try {
  385. config["multicastLimit"] = row[6].as<int>();
  386. } catch (std::exception &e) {
  387. config["multicastLimit"] = 64;
  388. }
  389. config["name"] = row[7].as<std::string>();
  390. config["private"] = row[8].as<bool>();
  391. if (!row[9].is_null()) {
  392. config["remoteTraceLevel"] = row[9].as<int>();
  393. } else {
  394. config["remoteTraceLevel"] = 0;
  395. }
  396. if (!row[10].is_null()) {
  397. config["remoteTraceTarget"] = row[10].as<std::string>();
  398. } else {
  399. config["remoteTraceTarget"] = nullptr;
  400. }
  401. try {
  402. config["revision"] = row[11].as<uint64_t>();
  403. } catch (std::exception &e) {
  404. config["revision"] = 0ULL;
  405. //fprintf(stderr, "Error converting revision: %s\n", PQgetvalue(res, i, 11));
  406. }
  407. config["rules"] = json::parse(row[12].as<std::string>());
  408. config["tags"] = json::parse(row[13].as<std::string>());
  409. config["v4AssignMode"] = json::parse(row[14].as<std::string>());
  410. config["v6AssignMode"] = json::parse(row[15].as<std::string>());
  411. config["ssoEnabled"] = row[16].as<bool>();
  412. config["objtype"] = "network";
  413. config["ipAssignmentPools"] = json::array();
  414. config["routes"] = json::array();
  415. pqxx::result r2 = w.exec_params("SELECT host(ip_range_start), host(ip_range_end) FROM ztc_network_assignment_pool WHERE network_id = $1", _myAddressStr);
  416. for (auto row2 = r2.begin(); row2 != r2.end(); row2++) {
  417. json ip;
  418. ip["ipRangeStart"] = row2[0].as<std::string>();
  419. ip["ipRangeEnd"] = row2[1].as<std::string>();
  420. config["ipAssignmentPools"].push_back(ip);
  421. }
  422. r2 = w.exec_params("SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1", _myAddressStr);
  423. for (auto row2 = r2.begin(); row2 != r2.end(); row2++) {
  424. std::string addr = row2[0].as<std::string>();
  425. std::string bits = row2[1].as<std::string>();
  426. std::string via = row2[2].as<std::string>();
  427. json route;
  428. route["target"] = addr + "/" + bits;
  429. if (via == "NULL") {
  430. route["via"] = nullptr;
  431. } else {
  432. route["via"] = via;
  433. }
  434. config["routes"].push_back(route);
  435. }
  436. r2 = w.exec_params("SELECT domain, servers FROM ztc_network_dns WHERE network_id = $1", _myAddressStr);
  437. if (r2.size() > 1) {
  438. fprintf(stderr, "ERROR: invalid number of DNS configurations for network %s. Must be 0 or 1\n", nwid.c_str());
  439. } else if (r2.size() == 1) {
  440. auto dnsRow = r2.begin();
  441. json obj;
  442. std::string domain = dnsRow[0].as<std::string>();
  443. std::string serverList = dnsRow[1].as<std::string>();
  444. auto servers = json::array();
  445. if (serverList.rfind("{",0) != std::string::npos) {
  446. serverList = serverList.substr(1, serverList.size()-2);
  447. std::stringstream ss(serverList);
  448. while(ss.good()) {
  449. std::string server;
  450. std::getline(ss, server, ',');
  451. servers.push_back(server);
  452. }
  453. }
  454. obj["domain"] = domain;
  455. obj["servers"] = servers;
  456. config["dns"] = obj;
  457. }
  458. r2 = w.exec_params("SELECT org.client_id, org.authorization_endpoint "
  459. "FROM ztc_network nw "
  460. "INNER JOIN ztc_org org "
  461. " ON org.owner_id = nw.owner_id "
  462. "WHERE nw.id = $1 AND nw.sso_enabled = true", nwid);
  463. if (r2.size() == 1) {
  464. // only one should exist
  465. pqxx::row row = r.at(0);
  466. config["clientId"] = row[0].as<std::string>();
  467. config["authorizationEndpoint"] = row[1].as<std::string>();
  468. }
  469. _networkChanged(empty, config, false);
  470. }
  471. w.commit();
  472. _pool->unborrow(c);
  473. if (++this->_ready == 2) {
  474. if (_waitNoticePrinted) {
  475. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  476. }
  477. _readyLock.unlock();
  478. }
  479. } catch (sw::redis::Error &e) {
  480. fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
  481. exit(-1);
  482. } catch (std::exception &e) {
  483. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  484. exit(-1);
  485. }
  486. }
  487. void PostgreSQL::initializeMembers()
  488. {
  489. try {
  490. std::unordered_map<std::string, std::string> networkMembers;
  491. fprintf(stderr, "Initializing Members...\n");
  492. auto c = _pool->borrow();
  493. pqxx::work w{*c->c};
  494. pqxx::result r = w.exec_params(
  495. "SELECT m.id, m.network_id, m.active_bridge, m.authorized, m.capabilities, (EXTRACT(EPOCH FROM m.creation_time AT TIME ZONE 'UTC')*1000)::bigint, m.identity, "
  496. " (EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  497. " (EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  498. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  499. " m.no_auto_assign_ips, m.revision, sso_exempt "
  500. "FROM ztc_member m "
  501. "INNER JOIN ztc_network n "
  502. " ON n.id = m.network_id "
  503. "WHERE n.controller_id = $1 AND m.deleted = false", _myAddressStr);
  504. for (auto row = r.begin(); row != r.end(); row++) {
  505. json empty;
  506. json config;
  507. initMember(config);
  508. if (row[0].is_null()) {
  509. fprintf(stderr, "Null memberID?!?\n");
  510. continue;
  511. }
  512. if (row[1].is_null()) {
  513. fprintf(stderr, "Null NetworkID?!?\n");
  514. }
  515. std::string memberId = row[0].as<std::string>();
  516. std::string networkId = row[1].as<std::string>();
  517. config["id"] = memberId;
  518. config["nwid"] = networkId;
  519. config["activeBridge"] = row[2].as<bool>();
  520. config["authorized"] = row[3].as<bool>();
  521. if (row[4].is_null()) {
  522. config["capabilities"] = json::array();
  523. } else {
  524. try {
  525. config["capabilities"] = json::parse(row[4].as<std::string>());
  526. } catch (std::exception &e) {
  527. config["capabilities"] = json::array();
  528. }
  529. }
  530. config["creationTime"] = row[5].as<uint64_t>();
  531. config["identity"] = row[6].as<std::string>();
  532. try {
  533. config["lastAuthorizedTime"] = row[7].as<uint64_t>();
  534. } catch(std::exception &e) {
  535. config["lastAuthorizedTime"] = 0ULL;
  536. //fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
  537. }
  538. try {
  539. config["lastDeauthorizedTime"] = row[8].as<uint64_t>();
  540. } catch( std::exception &e) {
  541. config["lastDeauthorizedTime"] = 0ULL;
  542. //fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
  543. }
  544. try {
  545. config["remoteTraceLevel"] = row[9].as<int>();
  546. } catch (std::exception &e) {
  547. config["remoteTraceLevel"] = 0;
  548. }
  549. if (!config["remoteTraceTarget"].is_null()) {
  550. config["remoteTraceTarget"] = row[10].as<std::string>();
  551. } else {
  552. config["remoteTraceTarget"] = "";
  553. }
  554. if (config["tags"].is_null()) {
  555. config["tags"] = json::array();
  556. } else {
  557. try {
  558. config["tags"] = json::parse(row[11].as<std::string>());
  559. } catch (std::exception &e) {
  560. config["tags"] = json::array();
  561. }
  562. }
  563. try {
  564. config["vMajor"] = row[12].as<int>();
  565. } catch(std::exception &e) {
  566. config["vMajor"] = -1;
  567. }
  568. try {
  569. config["vMinor"] = row[13].as<int>();
  570. } catch (std::exception &e) {
  571. config["vMinor"] = -1;
  572. }
  573. try {
  574. config["vRev"] = row[14].as<int>();
  575. } catch (std::exception &e) {
  576. config["vRev"] = -1;
  577. }
  578. try {
  579. config["vProto"] = row[15].as<int>();
  580. } catch (std::exception &e) {
  581. config["vProto"] = -1;
  582. }
  583. config["noAutoAssignIps"] = row[16].as<bool>();
  584. try {
  585. config["revision"] = row[17].as<uint64_t>();
  586. } catch (std::exception &e) {
  587. config["revision"] = 0ULL;
  588. //fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
  589. }
  590. config["ssoExempt"] = row[18].as<bool>();
  591. config["authenticationExpiryTime"] = 0LL;
  592. pqxx::result authRes = w.exec_params(
  593. "SELECT (EXTRACT(EPOCH FROM e.authentication_expiry_time)*1000)::bigint "
  594. "FROM ztc_sso_expiry e "
  595. "INNER JOIN ztc_network n "
  596. " ON n.id = e.network_id "
  597. "WHERE e.network_id = $1 AND e.member_id = $2 AND n.sso_enabled = TRUE "
  598. "ORDER BY e.authentication_expiry_time LIMIT 1", networkId, memberId);
  599. if (authRes.size() == 1) {
  600. // there is an expiry time record
  601. config["authenticationExpiryTime"] = authRes.at(0)[0].as<int64_t>();
  602. }
  603. config["objtype"] = "member";
  604. config["ipAssignments"] = json::array();
  605. pqxx::result r2 = w.exec_params("SELECT DISTINCT address "
  606. "FROM ztc_member_ip_assignment "
  607. "WHERE member_id = $1 AND network_id = $2", memberId, networkId);
  608. for (auto row2 = r2.begin(); row2 != r2.end(); row2++) {
  609. std::string ipaddr = row2[0].as<std::string>();
  610. std::size_t pos = ipaddr.find('/');
  611. if (pos != std::string::npos) {
  612. ipaddr = ipaddr.substr(0, pos);
  613. }
  614. config["ipAssignments"].push_back(ipaddr);
  615. }
  616. _memberChanged(empty, config, false);
  617. }
  618. w.commit();
  619. _pool->unborrow(c);
  620. if (++this->_ready == 2) {
  621. if (_waitNoticePrinted) {
  622. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  623. }
  624. _readyLock.unlock();
  625. }
  626. } catch (sw::redis::Error &e) {
  627. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  628. } catch (std::exception &e) {
  629. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  630. exit(-1);
  631. }
  632. }
  633. void PostgreSQL::heartbeat()
  634. {
  635. char publicId[1024];
  636. char hostnameTmp[1024];
  637. _myId.toString(false,publicId);
  638. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  639. hostnameTmp[0] = (char)0;
  640. } else {
  641. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  642. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  643. hostnameTmp[i] = (char)0;
  644. break;
  645. }
  646. }
  647. }
  648. const char *controllerId = _myAddressStr.c_str();
  649. const char *publicIdentity = publicId;
  650. const char *hostname = hostnameTmp;
  651. while (_run == 1) {
  652. auto c = _pool->borrow();
  653. int64_t ts = OSUtils::now();
  654. if(c->c) {
  655. pqxx::work w{*c->c};
  656. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  657. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  658. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  659. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  660. std::string now = std::to_string(ts);
  661. std::string host_port = std::to_string(_listenPort);
  662. std::string use_redis = "false"; // (_rc != NULL) ? "true" : "false";
  663. try {
  664. pqxx::result res = w.exec0("INSERT INTO ztc_controller (id, cluster_host, last_alive, public_identity, v_major, v_minor, v_rev, v_build, host_port, use_redis) "
  665. "VALUES ("+w.quote(controllerId)+", "+w.quote(hostname)+", TO_TIMESTAMP("+now+"::double precision/1000), "+
  666. w.quote(publicIdentity)+", "+major+", "+minor+", "+rev+", "+build+", "+host_port+", "+use_redis+") "
  667. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  668. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  669. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  670. "use_redis = EXCLUDED.use_redis");
  671. } catch (std::exception &e) {
  672. fprintf(stderr, "Heartbeat update failed: %s\n", e.what());
  673. w.abort();
  674. _pool->unborrow(c);
  675. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  676. continue;
  677. }
  678. w.commit();
  679. }
  680. _pool->unborrow(c);
  681. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  682. }
  683. fprintf(stderr, "Exited heartbeat thread\n");
  684. }
  685. void PostgreSQL::membersDbWatcher()
  686. {
  687. if (_rc) {
  688. _membersWatcher_Redis();
  689. } else {
  690. _membersWatcher_Postgres();
  691. }
  692. if (_run == 1) {
  693. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  694. exit(9);
  695. }
  696. fprintf(stderr, "Exited membersDbWatcher\n");
  697. }
  698. void PostgreSQL::_membersWatcher_Postgres() {
  699. auto c = _pool->borrow();
  700. std::string stream = "member_" + _myAddressStr;
  701. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  702. MemberNotificationReceiver m(this, *c->c, stream);
  703. while(_run == 1) {
  704. c->c->await_notification(5, 0);
  705. }
  706. _pool->unborrow(c);
  707. }
  708. void PostgreSQL::_membersWatcher_Redis() {
  709. char buf[11] = {0};
  710. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  711. fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
  712. while (_run == 1) {
  713. try {
  714. json tmp;
  715. std::unordered_map<std::string, ItemStream> result;
  716. if (_rc->clusterMode) {
  717. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  718. } else {
  719. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  720. }
  721. if (!result.empty()) {
  722. for (auto element : result) {
  723. #ifdef ZT_TRACE
  724. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  725. #endif
  726. for (auto rec : element.second) {
  727. std::string id = rec.first;
  728. auto attrs = rec.second;
  729. #ifdef ZT_TRACE
  730. fprintf(stdout, "Record ID: %s\n", id.c_str());
  731. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  732. #endif
  733. for (auto a : attrs) {
  734. #ifdef ZT_TRACE
  735. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  736. #endif
  737. try {
  738. tmp = json::parse(a.second);
  739. json &ov = tmp["old_val"];
  740. json &nv = tmp["new_val"];
  741. json oldConfig, newConfig;
  742. if (ov.is_object()) oldConfig = ov;
  743. if (nv.is_object()) newConfig = nv;
  744. if (oldConfig.is_object()||newConfig.is_object()) {
  745. _memberChanged(oldConfig,newConfig,(this->_ready >= 2));
  746. }
  747. } catch (...) {
  748. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  749. }
  750. }
  751. if (_rc->clusterMode) {
  752. _cluster->xdel(key, id);
  753. } else {
  754. _redis->xdel(key, id);
  755. }
  756. }
  757. }
  758. }
  759. } catch (sw::redis::Error &e) {
  760. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  761. }
  762. }
  763. fprintf(stderr, "membersWatcher ended\n");
  764. }
  765. void PostgreSQL::networksDbWatcher()
  766. {
  767. if (_rc) {
  768. _networksWatcher_Redis();
  769. } else {
  770. _networksWatcher_Postgres();
  771. }
  772. if (_run == 1) {
  773. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  774. exit(8);
  775. }
  776. fprintf(stderr, "Exited networksDbWatcher\n");
  777. }
  778. void PostgreSQL::_networksWatcher_Postgres() {
  779. std::string stream = "network_" + _myAddressStr;
  780. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  781. auto c = _pool->borrow();
  782. NetworkNotificationReceiver n(this, *c->c, stream);
  783. while(_run == 1) {
  784. c->c->await_notification(5,0);
  785. }
  786. }
  787. void PostgreSQL::_networksWatcher_Redis() {
  788. char buf[11] = {0};
  789. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  790. while (_run == 1) {
  791. try {
  792. json tmp;
  793. std::unordered_map<std::string, ItemStream> result;
  794. if (_rc->clusterMode) {
  795. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  796. } else {
  797. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  798. }
  799. if (!result.empty()) {
  800. for (auto element : result) {
  801. #ifdef ZT_TRACE
  802. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  803. #endif
  804. for (auto rec : element.second) {
  805. std::string id = rec.first;
  806. auto attrs = rec.second;
  807. #ifdef ZT_TRACE
  808. fprintf(stdout, "Record ID: %s\n", id.c_str());
  809. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  810. #endif
  811. for (auto a : attrs) {
  812. #ifdef ZT_TRACE
  813. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  814. #endif
  815. try {
  816. tmp = json::parse(a.second);
  817. json &ov = tmp["old_val"];
  818. json &nv = tmp["new_val"];
  819. json oldConfig, newConfig;
  820. if (ov.is_object()) oldConfig = ov;
  821. if (nv.is_object()) newConfig = nv;
  822. if (oldConfig.is_object()||newConfig.is_object()) {
  823. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  824. }
  825. } catch (...) {
  826. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  827. }
  828. }
  829. if (_rc->clusterMode) {
  830. _cluster->xdel(key, id);
  831. } else {
  832. _redis->xdel(key, id);
  833. }
  834. }
  835. }
  836. }
  837. } catch (sw::redis::Error &e) {
  838. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  839. }
  840. }
  841. fprintf(stderr, "networksWatcher ended\n");
  842. }
  843. void PostgreSQL::commitThread()
  844. {
  845. fprintf(stderr, "commitThread start\n");
  846. std::pair<nlohmann::json,bool> qitem;
  847. while(_commitQueue.get(qitem)&(_run == 1)) {
  848. fprintf(stderr, "commitThread tick\n");
  849. if (!qitem.first.is_object()) {
  850. fprintf(stderr, "not an object\n");
  851. continue;
  852. }
  853. try {
  854. nlohmann::json *config = &(qitem.first);
  855. const std::string objtype = (*config)["objtype"];
  856. if (objtype == "member") {
  857. fprintf(stderr, "commitThread: member\n");
  858. try {
  859. auto c = _pool->borrow();
  860. pqxx::work w(*c->c);
  861. std::string memberId = (*config)["id"];
  862. std::string networkId = (*config)["nwid"];
  863. std::string target = "NULL";
  864. if (!(*config)["remoteTraceTarget"].is_null()) {
  865. target = (*config)["remoteTraceTarget"];
  866. }
  867. pqxx::result res = w.exec_params0(
  868. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  869. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  870. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  871. "VALUES ($1, $2, $3, $4, $5, $6, "
  872. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  873. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  874. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  875. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  876. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  877. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  878. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  879. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  880. memberId,
  881. networkId,
  882. (bool)(*config)["activeBridge"],
  883. (bool)(*config)["authorized"],
  884. OSUtils::jsonDump((*config)["capabilities"], -1),
  885. OSUtils::jsonString((*config)["identity"], ""),
  886. (uint64_t)(*config)["lastAuthorizedTime"],
  887. (uint64_t)(*config)["lastDeauthorizedTime"],
  888. (bool)(*config)["noAutoAssignIps"],
  889. (int)(*config)["remoteTraceLevel"],
  890. target,
  891. (uint64_t)(*config)["revision"],
  892. OSUtils::jsonDump((*config)["tags"], -1),
  893. (int)(*config)["vMajor"],
  894. (int)(*config)["vMinor"],
  895. (int)(*config)["vRev"],
  896. (int)(*config)["vProto"]);
  897. res = w.exec_params0("DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  898. memberId, networkId);
  899. std::vector<std::string> assignments;
  900. bool ipAssignError = false;
  901. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  902. std::string addr = *i;
  903. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  904. continue;
  905. }
  906. res = w.exec_params0(
  907. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING",
  908. memberId, networkId, addr);
  909. assignments.push_back(addr);
  910. }
  911. if (ipAssignError) {
  912. fprintf(stderr, "ipAssignError\n");
  913. delete config;
  914. config = nullptr;
  915. continue;
  916. }
  917. w.commit();
  918. _pool->unborrow(c);
  919. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  920. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  921. if (nwidInt && memberidInt) {
  922. nlohmann::json nwOrig;
  923. nlohmann::json memOrig;
  924. nlohmann::json memNew(*config);
  925. get(nwidInt, nwOrig, memberidInt, memOrig);
  926. _memberChanged(memOrig, memNew, qitem.second);
  927. } else {
  928. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  929. }
  930. } catch (std::exception &e) {
  931. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  932. }
  933. } else if (objtype == "network") {
  934. try {
  935. fprintf(stderr, "commitThread: network\n");
  936. auto c = _pool->borrow();
  937. pqxx::work w(*c->c);
  938. std::string id = (*config)["id"];
  939. std::string remoteTraceTarget = "";
  940. if(!(*config)["remoteTraceTarget"].is_null()) {
  941. remoteTraceTarget = (*config)["remoteTraceTarget"];
  942. }
  943. std::string rulesSource = "";
  944. if ((*config)["rulesSource"].is_string()) {
  945. rulesSource = (*config)["rulesSource"];
  946. }
  947. // This ugly query exists because when we want to mirror networks to/from
  948. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  949. // that doesn't exist in Central's database. This does an upsert and sets
  950. // the owner_id to the "first" global admin in the user DB if the record
  951. // did not previously exist. If the record already exists owner_id is left
  952. // unchanged, so owner_id should be left out of the update clause.
  953. pqxx::result res = w.exec_params0(
  954. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  955. "last_modified, mtu, multicast_limit, name, private, "
  956. "remote_trace_level, remote_trace_target, rules, rules_source, "
  957. "tags, v4_assign_mode, v6_assign_mode) VALUES ("
  958. "$1, TO_TIMESTAMP($5::double precision/1000), "
  959. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  960. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  961. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
  962. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  963. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  964. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  965. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  966. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  967. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  968. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  969. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
  970. id,
  971. _myAddressStr,
  972. OSUtils::jsonDump((*config)["capabilitles"], -1),
  973. (bool)(*config)["enableBroadcast"],
  974. OSUtils::now(),
  975. (int)(*config)["mtu"],
  976. (int)(*config)["multicastLimit"],
  977. OSUtils::jsonString((*config)["name"],""),
  978. (bool)(*config)["private"],
  979. (int)(*config)["remoteTraceLevel"],
  980. remoteTraceTarget,
  981. OSUtils::jsonDump((*config)["rules"], -1),
  982. rulesSource,
  983. OSUtils::jsonDump((*config)["tags"], -1),
  984. OSUtils::jsonDump((*config)["v4AssignMode"],-1),
  985. OSUtils::jsonDump((*config)["v6AssignMode"], -1));
  986. res = w.exec_params0("DELETE FROM ztc_network_assignment_pool WHERE network_id = $1", 0);
  987. auto pool = (*config)["ipAssignmentPools"];
  988. bool err = false;
  989. for (auto i = pool.begin(); i != pool.end(); ++i) {
  990. std::string start = (*i)["ipRangeStart"];
  991. std::string end = (*i)["ipRangeEnd"];
  992. res = w.exec_params0(
  993. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  994. "VALUES ($1, $2, $3)", id, start, end);
  995. }
  996. res = w.exec_params0("DELETE FROM ztc_network_route WHERE network_id = $1", id);
  997. auto routes = (*config)["routes"];
  998. err = false;
  999. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1000. std::string t = (*i)["target"];
  1001. std::vector<std::string> target;
  1002. std::istringstream f(t);
  1003. std::string s;
  1004. while(std::getline(f, s, '/')) {
  1005. target.push_back(s);
  1006. }
  1007. if (target.empty() || target.size() != 2) {
  1008. continue;
  1009. }
  1010. std::string targetAddr = target[0];
  1011. std::string targetBits = target[1];
  1012. std::string via = "NULL";
  1013. if (!(*i)["via"].is_null()) {
  1014. via = (*i)["via"];
  1015. }
  1016. res = w.exec_params0("INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1017. id, targetAddr, targetBits, (via == "NULL" ? NULL : via.c_str()));
  1018. }
  1019. if (err) {
  1020. fprintf(stderr, "route add error\n");
  1021. w.abort();
  1022. _pool->unborrow(c);
  1023. delete config;
  1024. config = nullptr;
  1025. continue;
  1026. }
  1027. auto dns = (*config)["dns"];
  1028. std::string domain = dns["domain"];
  1029. std::stringstream servers;
  1030. servers << "{";
  1031. for (auto j = dns["servers"].begin(); j < dns["servers"].end(); ++j) {
  1032. servers << *j;
  1033. if ( (j+1) != dns["servers"].end()) {
  1034. servers << ",";
  1035. }
  1036. }
  1037. servers << "}";
  1038. std::string s = servers.str();
  1039. res = w.exec_params0("INSERT INTO ztc_network_dns (network_id, domain, servers) VALUES ($1, $2, $3) ON CONFLICT (network_id) DO UPDATE SET domain = EXCLUDED.domain, servers = EXCLUDED.servers",
  1040. id, domain, s);
  1041. w.commit();
  1042. _pool->unborrow(c);
  1043. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1044. if (nwidInt) {
  1045. nlohmann::json nwOrig;
  1046. nlohmann::json nwNew(*config);
  1047. get(nwidInt, nwOrig);
  1048. _networkChanged(nwOrig, nwNew, qitem.second);
  1049. } else {
  1050. fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
  1051. }
  1052. } catch (std::exception &e) {
  1053. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1054. }
  1055. } else if (objtype == "_delete_network") {
  1056. fprintf(stderr, "commitThread: delete network\n");
  1057. try {
  1058. auto c = _pool->borrow();
  1059. pqxx::work w(*c->c);
  1060. std::string networkId = (*config)["nwid"];
  1061. pqxx::result res = w.exec_params0("UPDATE ztc_network SET deleted = true WHERE id = $1",
  1062. networkId);
  1063. w.commit();
  1064. _pool->unborrow(c);
  1065. } catch (std::exception &e) {
  1066. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  1067. }
  1068. } else if (objtype == "_delete_member") {
  1069. fprintf(stderr, "commitThread: delete member\n");
  1070. try {
  1071. auto c = _pool->borrow();
  1072. pqxx::work w(*c->c);
  1073. std::string memberId = (*config)["id"];
  1074. std::string networkId = (*config)["nwid"];
  1075. pqxx::result res = w.exec_params0(
  1076. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1077. memberId, networkId);
  1078. w.commit();
  1079. _pool->unborrow(c);
  1080. } catch (std::exception &e) {
  1081. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1082. }
  1083. } else {
  1084. fprintf(stderr, "ERROR: unknown objtype");
  1085. }
  1086. } catch (std::exception &e) {
  1087. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1088. }
  1089. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1090. }
  1091. fprintf(stderr, "commitThread finished\n");
  1092. }
  1093. void PostgreSQL::onlineNotificationThread()
  1094. {
  1095. waitForReady();
  1096. onlineNotification_Postgres();
  1097. }
  1098. void PostgreSQL::onlineNotification_Postgres()
  1099. {
  1100. try {
  1101. auto c = _pool->borrow();
  1102. _pool->unborrow(c);
  1103. } catch(std::exception &e) {
  1104. fprintf(stderr, "error getting connection in onlineNotification thread\n");
  1105. exit(5);
  1106. }
  1107. _connected = 1;
  1108. nlohmann::json jtmp1, jtmp2;
  1109. while (_run == 1) {
  1110. try {
  1111. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1112. {
  1113. std::lock_guard<std::mutex> l(_lastOnline_l);
  1114. lastOnline.swap(_lastOnline);
  1115. }
  1116. auto c = _pool->borrow();
  1117. pqxx::work w(*c->c);
  1118. // using pqxx::stream_to would be a really nice alternative here, but
  1119. // unfortunately it doesn't support upserts.
  1120. fprintf(stderr, "online notification tick\n");
  1121. std::stringstream memberUpdate;
  1122. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ";
  1123. bool firstRun = true;
  1124. bool memberAdded = false;
  1125. int updateCount = 0;
  1126. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1127. updateCount += 1;
  1128. uint64_t nwid_i = i->first.first;
  1129. char nwidTmp[64];
  1130. char memTmp[64];
  1131. char ipTmp[64];
  1132. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1133. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1134. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1135. continue; // skip non existent networks/members
  1136. }
  1137. std::string networkId(nwidTmp);
  1138. std::string memberId(memTmp);
  1139. const char *qvals[2] = {
  1140. networkId.c_str(),
  1141. memberId.c_str()
  1142. };
  1143. try {
  1144. pqxx::row r = w.exec_params1("SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1145. networkId, memberId);
  1146. } catch (pqxx::unexpected_rows &e) {
  1147. fprintf(stderr, "Member count failed: %s\n", e.what());
  1148. continue;
  1149. }
  1150. int64_t ts = i->second.first;
  1151. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1152. std::string timestamp = std::to_string(ts);
  1153. if (firstRun) {
  1154. firstRun = false;
  1155. } else {
  1156. memberUpdate << ", ";
  1157. }
  1158. memberUpdate << "('" << networkId << "', '" << memberId << "', ";
  1159. if (ipAddr.empty()) {
  1160. memberUpdate << "NULL, ";
  1161. } else {
  1162. memberUpdate << "'" << ipAddr << "', ";
  1163. }
  1164. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
  1165. memberAdded = true;
  1166. }
  1167. memberUpdate << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated;";
  1168. if (memberAdded) {
  1169. fprintf(stderr, "%s\n", memberUpdate.str().c_str());
  1170. pqxx::result res = w.exec0(memberUpdate.str());
  1171. w.commit();
  1172. }
  1173. fprintf(stderr, "Updated online status of %d members\n", updateCount);
  1174. _pool->unborrow(c);
  1175. } catch (std::exception &e) {
  1176. fprintf(stderr, "%s: error in onlinenotification thread: %s\n", _myAddressStr.c_str(), e.what());
  1177. }
  1178. std::this_thread::sleep_for(std::chrono::seconds(10));
  1179. }
  1180. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1181. if (_run == 1) {
  1182. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1183. exit(6);
  1184. }
  1185. }
  1186. void PostgreSQL::onlineNotification_Redis()
  1187. {
  1188. _connected = 1;
  1189. char buf[11] = {0};
  1190. std::string controllerId = std::string(_myAddress.toString(buf));
  1191. while (_run == 1) {
  1192. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1193. {
  1194. std::lock_guard<std::mutex> l(_lastOnline_l);
  1195. lastOnline.swap(_lastOnline);
  1196. }
  1197. try {
  1198. if (!lastOnline.empty()) {
  1199. if (_rc->clusterMode) {
  1200. auto tx = _cluster->transaction(controllerId, true);
  1201. _doRedisUpdate(tx, controllerId, lastOnline);
  1202. } else {
  1203. auto tx = _redis->transaction(true);
  1204. _doRedisUpdate(tx, controllerId, lastOnline);
  1205. }
  1206. }
  1207. } catch (sw::redis::Error &e) {
  1208. #ifdef ZT_TRACE
  1209. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1210. #endif
  1211. }
  1212. std::this_thread::sleep_for(std::chrono::seconds(10));
  1213. }
  1214. }
  1215. void PostgreSQL::_doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
  1216. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline)
  1217. {
  1218. nlohmann::json jtmp1, jtmp2;
  1219. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1220. uint64_t nwid_i = i->first.first;
  1221. uint64_t memberid_i = i->first.second;
  1222. char nwidTmp[64];
  1223. char memTmp[64];
  1224. char ipTmp[64];
  1225. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1226. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", memberid_i);
  1227. if (!get(nwid_i, jtmp1, memberid_i, jtmp2)){
  1228. continue; // skip non existent members/networks
  1229. }
  1230. std::string networkId(nwidTmp);
  1231. std::string memberId(memTmp);
  1232. int64_t ts = i->second.first;
  1233. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1234. std::string timestamp = std::to_string(ts);
  1235. std::unordered_map<std::string, std::string> record = {
  1236. {"id", memberId},
  1237. {"address", ipAddr},
  1238. {"last_updated", std::to_string(ts)}
  1239. };
  1240. tx.zadd("nodes-online:{"+controllerId+"}", memberId, ts)
  1241. .zadd("nodes-online2:{"+controllerId+"}", networkId+"-"+memberId, ts)
  1242. .zadd("network-nodes-online:{"+controllerId+"}:"+networkId, memberId, ts)
  1243. .zadd("active-networks:{"+controllerId+"}", networkId, ts)
  1244. .sadd("network-nodes-all:{"+controllerId+"}:"+networkId, memberId)
  1245. .hmset("member:{"+controllerId+"}:"+networkId+":"+memberId, record.begin(), record.end());
  1246. }
  1247. // expire records from all-nodes and network-nodes member list
  1248. uint64_t expireOld = OSUtils::now() - 300000;
  1249. tx.zremrangebyscore("nodes-online:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1250. tx.zremrangebyscore("nodes-online2:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1251. tx.zremrangebyscore("active-networks:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1252. {
  1253. std::lock_guard<std::mutex> l(_networks_l);
  1254. for (const auto &it : _networks) {
  1255. uint64_t nwid_i = it.first;
  1256. char nwidTmp[64];
  1257. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1258. tx.zremrangebyscore("network-nodes-online:{"+controllerId+"}:"+nwidTmp,
  1259. sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1260. }
  1261. }
  1262. tx.exec();
  1263. }
  1264. #endif //ZT_CONTROLLER_USE_LIBPQ