PostgreSQL.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  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. // check if the member exists first.
  290. pqxx::row count = w.exec_params1("SELECT count(id) FROM ztc_member WHERE id = $1 AND network_id = $2", memberId, networkId);
  291. if (count[0].as<int>() == 1) {
  292. // find an unused nonce, if one exists.
  293. pqxx::result r = w.exec_params("SELECT nonce FROM ztc_sso_expiry "
  294. "WHERE network_id = $1 AND member_id = $2 "
  295. "AND authentication_expiry_time IS NULL AND ((NOW() AT TIME ZONE 'UTC') <= nonce_expiration)",
  296. networkId, memberId);
  297. if (r.size() == 1) {
  298. // we have an existing nonce. Use it
  299. nonce = r.at(0)[0].as<std::string>();
  300. } else if (r.empty()) {
  301. // create a nonce
  302. char randBuf[16] = {0};
  303. Utils::getSecureRandom(randBuf, 16);
  304. char nonceBuf[256] = {0};
  305. Utils::hex(randBuf, sizeof(randBuf), nonceBuf);
  306. nonce = std::string(nonceBuf);
  307. pqxx::result ir = w.exec_params0("INSERT INTO ztc_sso_expiry "
  308. "(nonce, nonce_expiration, network_id, member_id) VALUES "
  309. "($1, TO_TIMESTAMP($2::double precision/1000), $3, $4)",
  310. nonce, OSUtils::now() + 300000, networkId, memberId);
  311. } else {
  312. // > 1 ?!? Thats an error!
  313. fprintf(stderr, "> 1 unused nonce!\n");
  314. exit(6);
  315. }
  316. r = w.exec_params("SELECT org.client_id, org.authorization_endpoint "
  317. "FROM ztc_network AS nw, ztc_org AS org "
  318. "WHERE nw.id = $1 AND nw.sso_enabled = true AND org.owner_id = nw.owner_id", networkId);
  319. std::string client_id = "";
  320. std::string authorization_endpoint = "";
  321. if (r.size() == 1) {
  322. client_id = r.at(0)[0].as<std::string>();
  323. authorization_endpoint = r.at(0)[1].as<std::string>();
  324. } else if (r.size() > 1) {
  325. fprintf(stderr, "ERROR: More than one auth endpoint for an organization?!?!? NetworkID: %s\n", networkId.c_str());
  326. }
  327. // no catch all else because we don't actually care if no records exist here. just continue as normal.
  328. if ((!client_id.empty())&&(!authorization_endpoint.empty())) {
  329. have_auth = true;
  330. uint8_t state[48];
  331. HMACSHA384(_ssoPsk, nonce.data(), (unsigned int)nonce.length(), state);
  332. char state_hex[256];
  333. Utils::hex(state, 48, state_hex);
  334. const char *redirect_url = "redirect_uri=https%3A%2F%2Fmy.zerotier.com%2Fapi%2Fnetwork%2Fsso-auth"; // TODO: this should be configurable
  335. OSUtils::ztsnprintf(authenticationURL, sizeof(authenticationURL),
  336. "%s?response_type=id_token&response_mode=form_post&scope=openid+email+profile&redriect_uri=%s&nonce=%s&state=%s&client_id=%s",
  337. authorization_endpoint.c_str(),
  338. redirect_url,
  339. nonce.c_str(),
  340. state_hex,
  341. client_id.c_str());
  342. }
  343. }
  344. _pool->unborrow(c);
  345. } catch (std::exception &e) {
  346. fprintf(stderr, "ERROR: Error updating member on load: %s\n", e.what());
  347. }
  348. return std::string(authenticationURL);
  349. }
  350. void PostgreSQL::initializeNetworks()
  351. {
  352. try {
  353. std::string setKey = "networks:{" + _myAddressStr + "}";
  354. std::unordered_set<std::string> networkSet;
  355. fprintf(stderr, "Initializing Networks...\n");
  356. auto c = _pool->borrow();
  357. pqxx::work w{*c->c};
  358. pqxx::result r = w.exec_params("SELECT id, EXTRACT(EPOCH FROM creation_time AT TIME ZONE 'UTC')*1000 as creation_time, capabilities, "
  359. "enable_broadcast, EXTRACT(EPOCH FROM last_modified AT TIME ZONE 'UTC')*1000 AS last_modified, mtu, multicast_limit, name, private, remote_trace_level, "
  360. "remote_trace_target, revision, rules, tags, v4_assign_mode, v6_assign_mode, sso_enabled FROM ztc_network "
  361. "WHERE deleted = false AND controller_id = $1", _myAddressStr);
  362. for (auto row = r.begin(); row != r.end(); row++) {
  363. json empty;
  364. json config;
  365. initNetwork(config);
  366. std::string nwid = row[0].as<std::string>();
  367. networkSet.insert(nwid);
  368. config["id"] = nwid;
  369. config["nwid"] = nwid;
  370. try {
  371. config["creationTime"] = row[1].as<int64_t>();
  372. } catch (std::exception &e) {
  373. config["creationTime"] = 0ULL;
  374. }
  375. config["capabilities"] = row[2].as<std::string>();
  376. config["enableBroadcast"] = row[3].as<bool>();
  377. try {
  378. config["lastModified"] = row[4].as<uint64_t>();
  379. } catch (std::exception &e) {
  380. config["lastModified"] = 0ULL;
  381. }
  382. try {
  383. config["mtu"] = row[5].as<int>();
  384. } catch (std::exception &e) {
  385. config["mtu"] = 2800;
  386. }
  387. try {
  388. config["multicastLimit"] = row[6].as<int>();
  389. } catch (std::exception &e) {
  390. config["multicastLimit"] = 64;
  391. }
  392. config["name"] = row[7].as<std::string>();
  393. config["private"] = row[8].as<bool>();
  394. if (!row[9].is_null()) {
  395. config["remoteTraceLevel"] = row[9].as<int>();
  396. } else {
  397. config["remoteTraceLevel"] = 0;
  398. }
  399. if (!row[10].is_null()) {
  400. config["remoteTraceTarget"] = row[10].as<std::string>();
  401. } else {
  402. config["remoteTraceTarget"] = nullptr;
  403. }
  404. try {
  405. config["revision"] = row[11].as<uint64_t>();
  406. } catch (std::exception &e) {
  407. config["revision"] = 0ULL;
  408. //fprintf(stderr, "Error converting revision: %s\n", PQgetvalue(res, i, 11));
  409. }
  410. config["rules"] = json::parse(row[12].as<std::string>());
  411. config["tags"] = json::parse(row[13].as<std::string>());
  412. config["v4AssignMode"] = json::parse(row[14].as<std::string>());
  413. config["v6AssignMode"] = json::parse(row[15].as<std::string>());
  414. config["ssoEnabled"] = row[16].as<bool>();
  415. config["objtype"] = "network";
  416. config["ipAssignmentPools"] = json::array();
  417. config["routes"] = json::array();
  418. 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);
  419. for (auto row2 = r2.begin(); row2 != r2.end(); row2++) {
  420. json ip;
  421. ip["ipRangeStart"] = row2[0].as<std::string>();
  422. ip["ipRangeEnd"] = row2[1].as<std::string>();
  423. config["ipAssignmentPools"].push_back(ip);
  424. }
  425. r2 = w.exec_params("SELECT host(address), bits, host(via) FROM ztc_network_route WHERE network_id = $1", _myAddressStr);
  426. for (auto row2 = r2.begin(); row2 != r2.end(); row2++) {
  427. std::string addr = row2[0].as<std::string>();
  428. std::string bits = row2[1].as<std::string>();
  429. std::string via = row2[2].as<std::string>();
  430. json route;
  431. route["target"] = addr + "/" + bits;
  432. if (via == "NULL") {
  433. route["via"] = nullptr;
  434. } else {
  435. route["via"] = via;
  436. }
  437. config["routes"].push_back(route);
  438. }
  439. r2 = w.exec_params("SELECT domain, servers FROM ztc_network_dns WHERE network_id = $1", _myAddressStr);
  440. if (r2.size() > 1) {
  441. fprintf(stderr, "ERROR: invalid number of DNS configurations for network %s. Must be 0 or 1\n", nwid.c_str());
  442. } else if (r2.size() == 1) {
  443. auto dnsRow = r2.begin();
  444. json obj;
  445. std::string domain = dnsRow[0].as<std::string>();
  446. std::string serverList = dnsRow[1].as<std::string>();
  447. auto servers = json::array();
  448. if (serverList.rfind("{",0) != std::string::npos) {
  449. serverList = serverList.substr(1, serverList.size()-2);
  450. std::stringstream ss(serverList);
  451. while(ss.good()) {
  452. std::string server;
  453. std::getline(ss, server, ',');
  454. servers.push_back(server);
  455. }
  456. }
  457. obj["domain"] = domain;
  458. obj["servers"] = servers;
  459. config["dns"] = obj;
  460. }
  461. r2 = w.exec_params("SELECT org.client_id, org.authorization_endpoint "
  462. "FROM ztc_network nw "
  463. "INNER JOIN ztc_org org "
  464. " ON org.owner_id = nw.owner_id "
  465. "WHERE nw.id = $1 AND nw.sso_enabled = true", nwid);
  466. if (r2.size() == 1) {
  467. // only one should exist
  468. pqxx::row row = r.at(0);
  469. config["clientId"] = row[0].as<std::string>();
  470. config["authorizationEndpoint"] = row[1].as<std::string>();
  471. }
  472. _networkChanged(empty, config, false);
  473. }
  474. w.commit();
  475. _pool->unborrow(c);
  476. if (++this->_ready == 2) {
  477. if (_waitNoticePrinted) {
  478. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  479. }
  480. _readyLock.unlock();
  481. }
  482. } catch (sw::redis::Error &e) {
  483. fprintf(stderr, "ERROR: Error initializing networks in Redis: %s\n", e.what());
  484. exit(-1);
  485. } catch (std::exception &e) {
  486. fprintf(stderr, "ERROR: Error initializing networks: %s\n", e.what());
  487. exit(-1);
  488. }
  489. }
  490. void PostgreSQL::initializeMembers()
  491. {
  492. try {
  493. std::unordered_map<std::string, std::string> networkMembers;
  494. fprintf(stderr, "Initializing Members...\n");
  495. auto c = _pool->borrow();
  496. pqxx::work w{*c->c};
  497. pqxx::result r = w.exec_params(
  498. "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, "
  499. " (EXTRACT(EPOCH FROM m.last_authorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  500. " (EXTRACT(EPOCH FROM m.last_deauthorized_time AT TIME ZONE 'UTC')*1000)::bigint, "
  501. " m.remote_trace_level, m.remote_trace_target, m.tags, m.v_major, m.v_minor, m.v_rev, m.v_proto, "
  502. " m.no_auto_assign_ips, m.revision, sso_exempt "
  503. "FROM ztc_member m "
  504. "INNER JOIN ztc_network n "
  505. " ON n.id = m.network_id "
  506. "WHERE n.controller_id = $1 AND m.deleted = false", _myAddressStr);
  507. for (auto row = r.begin(); row != r.end(); row++) {
  508. json empty;
  509. json config;
  510. initMember(config);
  511. if (row[0].is_null()) {
  512. fprintf(stderr, "Null memberID?!?\n");
  513. continue;
  514. }
  515. if (row[1].is_null()) {
  516. fprintf(stderr, "Null NetworkID?!?\n");
  517. }
  518. std::string memberId = row[0].as<std::string>();
  519. std::string networkId = row[1].as<std::string>();
  520. config["id"] = memberId;
  521. config["nwid"] = networkId;
  522. config["activeBridge"] = row[2].as<bool>();
  523. config["authorized"] = row[3].as<bool>();
  524. if (row[4].is_null()) {
  525. config["capabilities"] = json::array();
  526. } else {
  527. try {
  528. config["capabilities"] = json::parse(row[4].as<std::string>());
  529. } catch (std::exception &e) {
  530. config["capabilities"] = json::array();
  531. }
  532. }
  533. config["creationTime"] = row[5].as<uint64_t>();
  534. config["identity"] = row[6].as<std::string>();
  535. try {
  536. config["lastAuthorizedTime"] = row[7].as<uint64_t>();
  537. } catch(std::exception &e) {
  538. config["lastAuthorizedTime"] = 0ULL;
  539. //fprintf(stderr, "Error updating last auth time (member): %s\n", PQgetvalue(res, i, 7));
  540. }
  541. try {
  542. config["lastDeauthorizedTime"] = row[8].as<uint64_t>();
  543. } catch( std::exception &e) {
  544. config["lastDeauthorizedTime"] = 0ULL;
  545. //fprintf(stderr, "Error updating last deauth time (member): %s\n", PQgetvalue(res, i, 8));
  546. }
  547. try {
  548. config["remoteTraceLevel"] = row[9].as<int>();
  549. } catch (std::exception &e) {
  550. config["remoteTraceLevel"] = 0;
  551. }
  552. if (!config["remoteTraceTarget"].is_null()) {
  553. config["remoteTraceTarget"] = row[10].as<std::string>();
  554. } else {
  555. config["remoteTraceTarget"] = "";
  556. }
  557. if (config["tags"].is_null()) {
  558. config["tags"] = json::array();
  559. } else {
  560. try {
  561. config["tags"] = json::parse(row[11].as<std::string>());
  562. } catch (std::exception &e) {
  563. config["tags"] = json::array();
  564. }
  565. }
  566. try {
  567. config["vMajor"] = row[12].as<int>();
  568. } catch(std::exception &e) {
  569. config["vMajor"] = -1;
  570. }
  571. try {
  572. config["vMinor"] = row[13].as<int>();
  573. } catch (std::exception &e) {
  574. config["vMinor"] = -1;
  575. }
  576. try {
  577. config["vRev"] = row[14].as<int>();
  578. } catch (std::exception &e) {
  579. config["vRev"] = -1;
  580. }
  581. try {
  582. config["vProto"] = row[15].as<int>();
  583. } catch (std::exception &e) {
  584. config["vProto"] = -1;
  585. }
  586. config["noAutoAssignIps"] = row[16].as<bool>();
  587. try {
  588. config["revision"] = row[17].as<uint64_t>();
  589. } catch (std::exception &e) {
  590. config["revision"] = 0ULL;
  591. //fprintf(stderr, "Error updating revision (member): %s\n", PQgetvalue(res, i, 17));
  592. }
  593. config["ssoExempt"] = row[18].as<bool>();
  594. config["authenticationExpiryTime"] = 0LL;
  595. pqxx::result authRes = w.exec_params(
  596. "SELECT (EXTRACT(EPOCH FROM e.authentication_expiry_time)*1000)::bigint "
  597. "FROM ztc_sso_expiry e "
  598. "INNER JOIN ztc_network n "
  599. " ON n.id = e.network_id "
  600. "WHERE e.network_id = $1 AND e.member_id = $2 AND n.sso_enabled = TRUE "
  601. "ORDER BY e.authentication_expiry_time LIMIT 1", networkId, memberId);
  602. if (authRes.size() == 1) {
  603. // there is an expiry time record
  604. config["authenticationExpiryTime"] = authRes.at(0)[0].as<int64_t>();
  605. }
  606. config["objtype"] = "member";
  607. config["ipAssignments"] = json::array();
  608. pqxx::result r2 = w.exec_params("SELECT DISTINCT address "
  609. "FROM ztc_member_ip_assignment "
  610. "WHERE member_id = $1 AND network_id = $2", memberId, networkId);
  611. for (auto row2 = r2.begin(); row2 != r2.end(); row2++) {
  612. std::string ipaddr = row2[0].as<std::string>();
  613. std::size_t pos = ipaddr.find('/');
  614. if (pos != std::string::npos) {
  615. ipaddr = ipaddr.substr(0, pos);
  616. }
  617. config["ipAssignments"].push_back(ipaddr);
  618. }
  619. _memberChanged(empty, config, false);
  620. }
  621. w.commit();
  622. _pool->unborrow(c);
  623. if (++this->_ready == 2) {
  624. if (_waitNoticePrinted) {
  625. fprintf(stderr,"[%s] NOTICE: %.10llx controller PostgreSQL data download complete." ZT_EOL_S,_timestr(),(unsigned long long)_myAddress.toInt());
  626. }
  627. _readyLock.unlock();
  628. }
  629. } catch (sw::redis::Error &e) {
  630. fprintf(stderr, "ERROR: Error initializing members (redis): %s\n", e.what());
  631. } catch (std::exception &e) {
  632. fprintf(stderr, "ERROR: Error initializing members: %s\n", e.what());
  633. exit(-1);
  634. }
  635. }
  636. void PostgreSQL::heartbeat()
  637. {
  638. char publicId[1024];
  639. char hostnameTmp[1024];
  640. _myId.toString(false,publicId);
  641. if (gethostname(hostnameTmp, sizeof(hostnameTmp))!= 0) {
  642. hostnameTmp[0] = (char)0;
  643. } else {
  644. for (int i = 0; i < (int)sizeof(hostnameTmp); ++i) {
  645. if ((hostnameTmp[i] == '.')||(hostnameTmp[i] == 0)) {
  646. hostnameTmp[i] = (char)0;
  647. break;
  648. }
  649. }
  650. }
  651. const char *controllerId = _myAddressStr.c_str();
  652. const char *publicIdentity = publicId;
  653. const char *hostname = hostnameTmp;
  654. while (_run == 1) {
  655. auto c = _pool->borrow();
  656. int64_t ts = OSUtils::now();
  657. if(c->c) {
  658. pqxx::work w{*c->c};
  659. std::string major = std::to_string(ZEROTIER_ONE_VERSION_MAJOR);
  660. std::string minor = std::to_string(ZEROTIER_ONE_VERSION_MINOR);
  661. std::string rev = std::to_string(ZEROTIER_ONE_VERSION_REVISION);
  662. std::string build = std::to_string(ZEROTIER_ONE_VERSION_BUILD);
  663. std::string now = std::to_string(ts);
  664. std::string host_port = std::to_string(_listenPort);
  665. std::string use_redis = "false"; // (_rc != NULL) ? "true" : "false";
  666. try {
  667. 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) "
  668. "VALUES ("+w.quote(controllerId)+", "+w.quote(hostname)+", TO_TIMESTAMP("+now+"::double precision/1000), "+
  669. w.quote(publicIdentity)+", "+major+", "+minor+", "+rev+", "+build+", "+host_port+", "+use_redis+") "
  670. "ON CONFLICT (id) DO UPDATE SET cluster_host = EXCLUDED.cluster_host, last_alive = EXCLUDED.last_alive, "
  671. "public_identity = EXCLUDED.public_identity, v_major = EXCLUDED.v_major, v_minor = EXCLUDED.v_minor, "
  672. "v_rev = EXCLUDED.v_rev, v_build = EXCLUDED.v_rev, host_port = EXCLUDED.host_port, "
  673. "use_redis = EXCLUDED.use_redis");
  674. } catch (std::exception &e) {
  675. fprintf(stderr, "Heartbeat update failed: %s\n", e.what());
  676. w.abort();
  677. _pool->unborrow(c);
  678. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  679. continue;
  680. }
  681. w.commit();
  682. }
  683. _pool->unborrow(c);
  684. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  685. }
  686. fprintf(stderr, "Exited heartbeat thread\n");
  687. }
  688. void PostgreSQL::membersDbWatcher()
  689. {
  690. if (_rc) {
  691. _membersWatcher_Redis();
  692. } else {
  693. _membersWatcher_Postgres();
  694. }
  695. if (_run == 1) {
  696. fprintf(stderr, "ERROR: %s membersDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  697. exit(9);
  698. }
  699. fprintf(stderr, "Exited membersDbWatcher\n");
  700. }
  701. void PostgreSQL::_membersWatcher_Postgres() {
  702. auto c = _pool->borrow();
  703. std::string stream = "member_" + _myAddressStr;
  704. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  705. MemberNotificationReceiver m(this, *c->c, stream);
  706. while(_run == 1) {
  707. c->c->await_notification(5, 0);
  708. }
  709. _pool->unborrow(c);
  710. }
  711. void PostgreSQL::_membersWatcher_Redis() {
  712. char buf[11] = {0};
  713. std::string key = "member-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  714. fprintf(stderr, "Listening to member stream: %s\n", key.c_str());
  715. while (_run == 1) {
  716. try {
  717. json tmp;
  718. std::unordered_map<std::string, ItemStream> result;
  719. if (_rc->clusterMode) {
  720. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  721. } else {
  722. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  723. }
  724. if (!result.empty()) {
  725. for (auto element : result) {
  726. #ifdef ZT_TRACE
  727. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  728. #endif
  729. for (auto rec : element.second) {
  730. std::string id = rec.first;
  731. auto attrs = rec.second;
  732. #ifdef ZT_TRACE
  733. fprintf(stdout, "Record ID: %s\n", id.c_str());
  734. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  735. #endif
  736. for (auto a : attrs) {
  737. #ifdef ZT_TRACE
  738. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  739. #endif
  740. try {
  741. tmp = json::parse(a.second);
  742. json &ov = tmp["old_val"];
  743. json &nv = tmp["new_val"];
  744. json oldConfig, newConfig;
  745. if (ov.is_object()) oldConfig = ov;
  746. if (nv.is_object()) newConfig = nv;
  747. if (oldConfig.is_object()||newConfig.is_object()) {
  748. _memberChanged(oldConfig,newConfig,(this->_ready >= 2));
  749. }
  750. } catch (...) {
  751. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  752. }
  753. }
  754. if (_rc->clusterMode) {
  755. _cluster->xdel(key, id);
  756. } else {
  757. _redis->xdel(key, id);
  758. }
  759. }
  760. }
  761. }
  762. } catch (sw::redis::Error &e) {
  763. fprintf(stderr, "Error in Redis members watcher: %s\n", e.what());
  764. }
  765. }
  766. fprintf(stderr, "membersWatcher ended\n");
  767. }
  768. void PostgreSQL::networksDbWatcher()
  769. {
  770. if (_rc) {
  771. _networksWatcher_Redis();
  772. } else {
  773. _networksWatcher_Postgres();
  774. }
  775. if (_run == 1) {
  776. fprintf(stderr, "ERROR: %s networksDbWatcher should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  777. exit(8);
  778. }
  779. fprintf(stderr, "Exited networksDbWatcher\n");
  780. }
  781. void PostgreSQL::_networksWatcher_Postgres() {
  782. std::string stream = "network_" + _myAddressStr;
  783. fprintf(stderr, "Listening to member stream: %s\n", stream.c_str());
  784. auto c = _pool->borrow();
  785. NetworkNotificationReceiver n(this, *c->c, stream);
  786. while(_run == 1) {
  787. c->c->await_notification(5,0);
  788. }
  789. }
  790. void PostgreSQL::_networksWatcher_Redis() {
  791. char buf[11] = {0};
  792. std::string key = "network-stream:{" + std::string(_myAddress.toString(buf)) + "}";
  793. while (_run == 1) {
  794. try {
  795. json tmp;
  796. std::unordered_map<std::string, ItemStream> result;
  797. if (_rc->clusterMode) {
  798. _cluster->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  799. } else {
  800. _redis->xread(key, "$", std::chrono::seconds(1), 0, std::inserter(result, result.end()));
  801. }
  802. if (!result.empty()) {
  803. for (auto element : result) {
  804. #ifdef ZT_TRACE
  805. fprintf(stdout, "Received notification from: %s\n", element.first.c_str());
  806. #endif
  807. for (auto rec : element.second) {
  808. std::string id = rec.first;
  809. auto attrs = rec.second;
  810. #ifdef ZT_TRACE
  811. fprintf(stdout, "Record ID: %s\n", id.c_str());
  812. fprintf(stdout, "attrs len: %lu\n", attrs.size());
  813. #endif
  814. for (auto a : attrs) {
  815. #ifdef ZT_TRACE
  816. fprintf(stdout, "key: %s\nvalue: %s\n", a.first.c_str(), a.second.c_str());
  817. #endif
  818. try {
  819. tmp = json::parse(a.second);
  820. json &ov = tmp["old_val"];
  821. json &nv = tmp["new_val"];
  822. json oldConfig, newConfig;
  823. if (ov.is_object()) oldConfig = ov;
  824. if (nv.is_object()) newConfig = nv;
  825. if (oldConfig.is_object()||newConfig.is_object()) {
  826. _networkChanged(oldConfig,newConfig,(this->_ready >= 2));
  827. }
  828. } catch (...) {
  829. fprintf(stderr, "json parse error in networkWatcher_Redis\n");
  830. }
  831. }
  832. if (_rc->clusterMode) {
  833. _cluster->xdel(key, id);
  834. } else {
  835. _redis->xdel(key, id);
  836. }
  837. }
  838. }
  839. }
  840. } catch (sw::redis::Error &e) {
  841. fprintf(stderr, "Error in Redis networks watcher: %s\n", e.what());
  842. }
  843. }
  844. fprintf(stderr, "networksWatcher ended\n");
  845. }
  846. void PostgreSQL::commitThread()
  847. {
  848. fprintf(stderr, "commitThread start\n");
  849. std::pair<nlohmann::json,bool> qitem;
  850. while(_commitQueue.get(qitem)&(_run == 1)) {
  851. fprintf(stderr, "commitThread tick\n");
  852. if (!qitem.first.is_object()) {
  853. fprintf(stderr, "not an object\n");
  854. continue;
  855. }
  856. try {
  857. nlohmann::json *config = &(qitem.first);
  858. const std::string objtype = (*config)["objtype"];
  859. if (objtype == "member") {
  860. fprintf(stderr, "commitThread: member\n");
  861. try {
  862. auto c = _pool->borrow();
  863. pqxx::work w(*c->c);
  864. std::string memberId = (*config)["id"];
  865. std::string networkId = (*config)["nwid"];
  866. std::string target = "NULL";
  867. if (!(*config)["remoteTraceTarget"].is_null()) {
  868. target = (*config)["remoteTraceTarget"];
  869. }
  870. pqxx::result res = w.exec_params0(
  871. "INSERT INTO ztc_member (id, network_id, active_bridge, authorized, capabilities, "
  872. "identity, last_authorized_time, last_deauthorized_time, no_auto_assign_ips, "
  873. "remote_trace_level, remote_trace_target, revision, tags, v_major, v_minor, v_rev, v_proto) "
  874. "VALUES ($1, $2, $3, $4, $5, $6, "
  875. "TO_TIMESTAMP($7::double precision/1000), TO_TIMESTAMP($8::double precision/1000), "
  876. "$9, $10, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (network_id, id) DO UPDATE SET "
  877. "active_bridge = EXCLUDED.active_bridge, authorized = EXCLUDED.authorized, capabilities = EXCLUDED.capabilities, "
  878. "identity = EXCLUDED.identity, last_authorized_time = EXCLUDED.last_authorized_time, "
  879. "last_deauthorized_time = EXCLUDED.last_deauthorized_time, no_auto_assign_ips = EXCLUDED.no_auto_assign_ips, "
  880. "remote_trace_level = EXCLUDED.remote_trace_level, remote_trace_target = EXCLUDED.remote_trace_target, "
  881. "revision = EXCLUDED.revision+1, tags = EXCLUDED.tags, v_major = EXCLUDED.v_major, "
  882. "v_minor = EXCLUDED.v_minor, v_rev = EXCLUDED.v_rev, v_proto = EXCLUDED.v_proto",
  883. memberId,
  884. networkId,
  885. (bool)(*config)["activeBridge"],
  886. (bool)(*config)["authorized"],
  887. OSUtils::jsonDump((*config)["capabilities"], -1),
  888. OSUtils::jsonString((*config)["identity"], ""),
  889. (uint64_t)(*config)["lastAuthorizedTime"],
  890. (uint64_t)(*config)["lastDeauthorizedTime"],
  891. (bool)(*config)["noAutoAssignIps"],
  892. (int)(*config)["remoteTraceLevel"],
  893. target,
  894. (uint64_t)(*config)["revision"],
  895. OSUtils::jsonDump((*config)["tags"], -1),
  896. (int)(*config)["vMajor"],
  897. (int)(*config)["vMinor"],
  898. (int)(*config)["vRev"],
  899. (int)(*config)["vProto"]);
  900. res = w.exec_params0("DELETE FROM ztc_member_ip_assignment WHERE member_id = $1 AND network_id = $2",
  901. memberId, networkId);
  902. std::vector<std::string> assignments;
  903. bool ipAssignError = false;
  904. for (auto i = (*config)["ipAssignments"].begin(); i != (*config)["ipAssignments"].end(); ++i) {
  905. std::string addr = *i;
  906. if (std::find(assignments.begin(), assignments.end(), addr) != assignments.end()) {
  907. continue;
  908. }
  909. res = w.exec_params0(
  910. "INSERT INTO ztc_member_ip_assignment (member_id, network_id, address) VALUES ($1, $2, $3) ON CONFLICT (network_id, member_id, address) DO NOTHING",
  911. memberId, networkId, addr);
  912. assignments.push_back(addr);
  913. }
  914. if (ipAssignError) {
  915. fprintf(stderr, "ipAssignError\n");
  916. delete config;
  917. config = nullptr;
  918. continue;
  919. }
  920. w.commit();
  921. _pool->unborrow(c);
  922. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  923. const uint64_t memberidInt = OSUtils::jsonIntHex((*config)["id"], 0ULL);
  924. if (nwidInt && memberidInt) {
  925. nlohmann::json nwOrig;
  926. nlohmann::json memOrig;
  927. nlohmann::json memNew(*config);
  928. get(nwidInt, nwOrig, memberidInt, memOrig);
  929. _memberChanged(memOrig, memNew, qitem.second);
  930. } else {
  931. fprintf(stderr, "Can't notify of change. Error parsing nwid or memberid: %llu-%llu\n", (unsigned long long)nwidInt, (unsigned long long)memberidInt);
  932. }
  933. } catch (std::exception &e) {
  934. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  935. }
  936. } else if (objtype == "network") {
  937. try {
  938. fprintf(stderr, "commitThread: network\n");
  939. auto c = _pool->borrow();
  940. pqxx::work w(*c->c);
  941. std::string id = (*config)["id"];
  942. std::string remoteTraceTarget = "";
  943. if(!(*config)["remoteTraceTarget"].is_null()) {
  944. remoteTraceTarget = (*config)["remoteTraceTarget"];
  945. }
  946. std::string rulesSource = "";
  947. if ((*config)["rulesSource"].is_string()) {
  948. rulesSource = (*config)["rulesSource"];
  949. }
  950. // This ugly query exists because when we want to mirror networks to/from
  951. // another data store (e.g. FileDB or LFDB) it is possible to get a network
  952. // that doesn't exist in Central's database. This does an upsert and sets
  953. // the owner_id to the "first" global admin in the user DB if the record
  954. // did not previously exist. If the record already exists owner_id is left
  955. // unchanged, so owner_id should be left out of the update clause.
  956. pqxx::result res = w.exec_params0(
  957. "INSERT INTO ztc_network (id, creation_time, owner_id, controller_id, capabilities, enable_broadcast, "
  958. "last_modified, mtu, multicast_limit, name, private, "
  959. "remote_trace_level, remote_trace_target, rules, rules_source, "
  960. "tags, v4_assign_mode, v6_assign_mode) VALUES ("
  961. "$1, TO_TIMESTAMP($5::double precision/1000), "
  962. "(SELECT user_id AS owner_id FROM ztc_global_permissions WHERE authorize = true AND del = true AND modify = true AND read = true LIMIT 1),"
  963. "$2, $3, $4, TO_TIMESTAMP($5::double precision/1000), "
  964. "$6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) "
  965. "ON CONFLICT (id) DO UPDATE set controller_id = EXCLUDED.controller_id, "
  966. "capabilities = EXCLUDED.capabilities, enable_broadcast = EXCLUDED.enable_broadcast, "
  967. "last_modified = EXCLUDED.last_modified, mtu = EXCLUDED.mtu, "
  968. "multicast_limit = EXCLUDED.multicast_limit, name = EXCLUDED.name, "
  969. "private = EXCLUDED.private, remote_trace_level = EXCLUDED.remote_trace_level, "
  970. "remote_trace_target = EXCLUDED.remote_trace_target, rules = EXCLUDED.rules, "
  971. "rules_source = EXCLUDED.rules_source, tags = EXCLUDED.tags, "
  972. "v4_assign_mode = EXCLUDED.v4_assign_mode, v6_assign_mode = EXCLUDED.v6_assign_mode",
  973. id,
  974. _myAddressStr,
  975. OSUtils::jsonDump((*config)["capabilitles"], -1),
  976. (bool)(*config)["enableBroadcast"],
  977. OSUtils::now(),
  978. (int)(*config)["mtu"],
  979. (int)(*config)["multicastLimit"],
  980. OSUtils::jsonString((*config)["name"],""),
  981. (bool)(*config)["private"],
  982. (int)(*config)["remoteTraceLevel"],
  983. remoteTraceTarget,
  984. OSUtils::jsonDump((*config)["rules"], -1),
  985. rulesSource,
  986. OSUtils::jsonDump((*config)["tags"], -1),
  987. OSUtils::jsonDump((*config)["v4AssignMode"],-1),
  988. OSUtils::jsonDump((*config)["v6AssignMode"], -1));
  989. res = w.exec_params0("DELETE FROM ztc_network_assignment_pool WHERE network_id = $1", 0);
  990. auto pool = (*config)["ipAssignmentPools"];
  991. bool err = false;
  992. for (auto i = pool.begin(); i != pool.end(); ++i) {
  993. std::string start = (*i)["ipRangeStart"];
  994. std::string end = (*i)["ipRangeEnd"];
  995. res = w.exec_params0(
  996. "INSERT INTO ztc_network_assignment_pool (network_id, ip_range_start, ip_range_end) "
  997. "VALUES ($1, $2, $3)", id, start, end);
  998. }
  999. res = w.exec_params0("DELETE FROM ztc_network_route WHERE network_id = $1", id);
  1000. auto routes = (*config)["routes"];
  1001. err = false;
  1002. for (auto i = routes.begin(); i != routes.end(); ++i) {
  1003. std::string t = (*i)["target"];
  1004. std::vector<std::string> target;
  1005. std::istringstream f(t);
  1006. std::string s;
  1007. while(std::getline(f, s, '/')) {
  1008. target.push_back(s);
  1009. }
  1010. if (target.empty() || target.size() != 2) {
  1011. continue;
  1012. }
  1013. std::string targetAddr = target[0];
  1014. std::string targetBits = target[1];
  1015. std::string via = "NULL";
  1016. if (!(*i)["via"].is_null()) {
  1017. via = (*i)["via"];
  1018. }
  1019. res = w.exec_params0("INSERT INTO ztc_network_route (network_id, address, bits, via) VALUES ($1, $2, $3, $4)",
  1020. id, targetAddr, targetBits, (via == "NULL" ? NULL : via.c_str()));
  1021. }
  1022. if (err) {
  1023. fprintf(stderr, "route add error\n");
  1024. w.abort();
  1025. _pool->unborrow(c);
  1026. delete config;
  1027. config = nullptr;
  1028. continue;
  1029. }
  1030. auto dns = (*config)["dns"];
  1031. std::string domain = dns["domain"];
  1032. std::stringstream servers;
  1033. servers << "{";
  1034. for (auto j = dns["servers"].begin(); j < dns["servers"].end(); ++j) {
  1035. servers << *j;
  1036. if ( (j+1) != dns["servers"].end()) {
  1037. servers << ",";
  1038. }
  1039. }
  1040. servers << "}";
  1041. std::string s = servers.str();
  1042. 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",
  1043. id, domain, s);
  1044. w.commit();
  1045. _pool->unborrow(c);
  1046. const uint64_t nwidInt = OSUtils::jsonIntHex((*config)["nwid"], 0ULL);
  1047. if (nwidInt) {
  1048. nlohmann::json nwOrig;
  1049. nlohmann::json nwNew(*config);
  1050. get(nwidInt, nwOrig);
  1051. _networkChanged(nwOrig, nwNew, qitem.second);
  1052. } else {
  1053. fprintf(stderr, "Can't notify network changed: %llu\n", (unsigned long long)nwidInt);
  1054. }
  1055. } catch (std::exception &e) {
  1056. fprintf(stderr, "ERROR: Error updating member: %s\n", e.what());
  1057. }
  1058. } else if (objtype == "_delete_network") {
  1059. fprintf(stderr, "commitThread: delete network\n");
  1060. try {
  1061. auto c = _pool->borrow();
  1062. pqxx::work w(*c->c);
  1063. std::string networkId = (*config)["nwid"];
  1064. pqxx::result res = w.exec_params0("UPDATE ztc_network SET deleted = true WHERE id = $1",
  1065. networkId);
  1066. w.commit();
  1067. _pool->unborrow(c);
  1068. } catch (std::exception &e) {
  1069. fprintf(stderr, "ERROR: Error deleting network: %s\n", e.what());
  1070. }
  1071. } else if (objtype == "_delete_member") {
  1072. fprintf(stderr, "commitThread: delete member\n");
  1073. try {
  1074. auto c = _pool->borrow();
  1075. pqxx::work w(*c->c);
  1076. std::string memberId = (*config)["id"];
  1077. std::string networkId = (*config)["nwid"];
  1078. pqxx::result res = w.exec_params0(
  1079. "UPDATE ztc_member SET hidden = true, deleted = true WHERE id = $1 AND network_id = $2",
  1080. memberId, networkId);
  1081. w.commit();
  1082. _pool->unborrow(c);
  1083. } catch (std::exception &e) {
  1084. fprintf(stderr, "ERROR: Error deleting member: %s\n", e.what());
  1085. }
  1086. } else {
  1087. fprintf(stderr, "ERROR: unknown objtype");
  1088. }
  1089. } catch (std::exception &e) {
  1090. fprintf(stderr, "ERROR: Error getting objtype: %s\n", e.what());
  1091. }
  1092. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1093. }
  1094. fprintf(stderr, "commitThread finished\n");
  1095. }
  1096. void PostgreSQL::onlineNotificationThread()
  1097. {
  1098. waitForReady();
  1099. onlineNotification_Postgres();
  1100. }
  1101. void PostgreSQL::onlineNotification_Postgres()
  1102. {
  1103. try {
  1104. auto c = _pool->borrow();
  1105. _pool->unborrow(c);
  1106. } catch(std::exception &e) {
  1107. fprintf(stderr, "error getting connection in onlineNotification thread\n");
  1108. exit(5);
  1109. }
  1110. _connected = 1;
  1111. nlohmann::json jtmp1, jtmp2;
  1112. while (_run == 1) {
  1113. try {
  1114. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1115. {
  1116. std::lock_guard<std::mutex> l(_lastOnline_l);
  1117. lastOnline.swap(_lastOnline);
  1118. }
  1119. auto c = _pool->borrow();
  1120. pqxx::work w(*c->c);
  1121. // using pqxx::stream_to would be a really nice alternative here, but
  1122. // unfortunately it doesn't support upserts.
  1123. fprintf(stderr, "online notification tick\n");
  1124. std::stringstream memberUpdate;
  1125. memberUpdate << "INSERT INTO ztc_member_status (network_id, member_id, address, last_updated) VALUES ";
  1126. bool firstRun = true;
  1127. bool memberAdded = false;
  1128. int updateCount = 0;
  1129. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1130. updateCount += 1;
  1131. uint64_t nwid_i = i->first.first;
  1132. char nwidTmp[64];
  1133. char memTmp[64];
  1134. char ipTmp[64];
  1135. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1136. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", i->first.second);
  1137. if(!get(nwid_i, jtmp1, i->first.second, jtmp2)) {
  1138. continue; // skip non existent networks/members
  1139. }
  1140. std::string networkId(nwidTmp);
  1141. std::string memberId(memTmp);
  1142. const char *qvals[2] = {
  1143. networkId.c_str(),
  1144. memberId.c_str()
  1145. };
  1146. try {
  1147. pqxx::row r = w.exec_params1("SELECT id, network_id FROM ztc_member WHERE network_id = $1 AND id = $2",
  1148. networkId, memberId);
  1149. } catch (pqxx::unexpected_rows &e) {
  1150. fprintf(stderr, "Member count failed: %s\n", e.what());
  1151. continue;
  1152. }
  1153. int64_t ts = i->second.first;
  1154. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1155. std::string timestamp = std::to_string(ts);
  1156. if (firstRun) {
  1157. firstRun = false;
  1158. } else {
  1159. memberUpdate << ", ";
  1160. }
  1161. memberUpdate << "('" << networkId << "', '" << memberId << "', ";
  1162. if (ipAddr.empty()) {
  1163. memberUpdate << "NULL, ";
  1164. } else {
  1165. memberUpdate << "'" << ipAddr << "', ";
  1166. }
  1167. memberUpdate << "TO_TIMESTAMP(" << timestamp << "::double precision/1000))";
  1168. memberAdded = true;
  1169. }
  1170. memberUpdate << " ON CONFLICT (network_id, member_id) DO UPDATE SET address = EXCLUDED.address, last_updated = EXCLUDED.last_updated;";
  1171. if (memberAdded) {
  1172. fprintf(stderr, "%s\n", memberUpdate.str().c_str());
  1173. pqxx::result res = w.exec0(memberUpdate.str());
  1174. w.commit();
  1175. }
  1176. fprintf(stderr, "Updated online status of %d members\n", updateCount);
  1177. _pool->unborrow(c);
  1178. } catch (std::exception &e) {
  1179. fprintf(stderr, "%s: error in onlinenotification thread: %s\n", _myAddressStr.c_str(), e.what());
  1180. }
  1181. std::this_thread::sleep_for(std::chrono::seconds(10));
  1182. }
  1183. fprintf(stderr, "%s: Fell out of run loop in onlineNotificationThread\n", _myAddressStr.c_str());
  1184. if (_run == 1) {
  1185. fprintf(stderr, "ERROR: %s onlineNotificationThread should still be running! Exiting Controller.\n", _myAddressStr.c_str());
  1186. exit(6);
  1187. }
  1188. }
  1189. void PostgreSQL::onlineNotification_Redis()
  1190. {
  1191. _connected = 1;
  1192. char buf[11] = {0};
  1193. std::string controllerId = std::string(_myAddress.toString(buf));
  1194. while (_run == 1) {
  1195. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > lastOnline;
  1196. {
  1197. std::lock_guard<std::mutex> l(_lastOnline_l);
  1198. lastOnline.swap(_lastOnline);
  1199. }
  1200. try {
  1201. if (!lastOnline.empty()) {
  1202. if (_rc->clusterMode) {
  1203. auto tx = _cluster->transaction(controllerId, true);
  1204. _doRedisUpdate(tx, controllerId, lastOnline);
  1205. } else {
  1206. auto tx = _redis->transaction(true);
  1207. _doRedisUpdate(tx, controllerId, lastOnline);
  1208. }
  1209. }
  1210. } catch (sw::redis::Error &e) {
  1211. #ifdef ZT_TRACE
  1212. fprintf(stderr, "Error in online notification thread (redis): %s\n", e.what());
  1213. #endif
  1214. }
  1215. std::this_thread::sleep_for(std::chrono::seconds(10));
  1216. }
  1217. }
  1218. void PostgreSQL::_doRedisUpdate(sw::redis::Transaction &tx, std::string &controllerId,
  1219. std::unordered_map< std::pair<uint64_t,uint64_t>,std::pair<int64_t,InetAddress>,_PairHasher > &lastOnline)
  1220. {
  1221. nlohmann::json jtmp1, jtmp2;
  1222. for (auto i=lastOnline.begin(); i != lastOnline.end(); ++i) {
  1223. uint64_t nwid_i = i->first.first;
  1224. uint64_t memberid_i = i->first.second;
  1225. char nwidTmp[64];
  1226. char memTmp[64];
  1227. char ipTmp[64];
  1228. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1229. OSUtils::ztsnprintf(memTmp,sizeof(memTmp), "%.10llx", memberid_i);
  1230. if (!get(nwid_i, jtmp1, memberid_i, jtmp2)){
  1231. continue; // skip non existent members/networks
  1232. }
  1233. std::string networkId(nwidTmp);
  1234. std::string memberId(memTmp);
  1235. int64_t ts = i->second.first;
  1236. std::string ipAddr = i->second.second.toIpString(ipTmp);
  1237. std::string timestamp = std::to_string(ts);
  1238. std::unordered_map<std::string, std::string> record = {
  1239. {"id", memberId},
  1240. {"address", ipAddr},
  1241. {"last_updated", std::to_string(ts)}
  1242. };
  1243. tx.zadd("nodes-online:{"+controllerId+"}", memberId, ts)
  1244. .zadd("nodes-online2:{"+controllerId+"}", networkId+"-"+memberId, ts)
  1245. .zadd("network-nodes-online:{"+controllerId+"}:"+networkId, memberId, ts)
  1246. .zadd("active-networks:{"+controllerId+"}", networkId, ts)
  1247. .sadd("network-nodes-all:{"+controllerId+"}:"+networkId, memberId)
  1248. .hmset("member:{"+controllerId+"}:"+networkId+":"+memberId, record.begin(), record.end());
  1249. }
  1250. // expire records from all-nodes and network-nodes member list
  1251. uint64_t expireOld = OSUtils::now() - 300000;
  1252. tx.zremrangebyscore("nodes-online:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1253. tx.zremrangebyscore("nodes-online2:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1254. tx.zremrangebyscore("active-networks:{"+controllerId+"}", sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1255. {
  1256. std::lock_guard<std::mutex> l(_networks_l);
  1257. for (const auto &it : _networks) {
  1258. uint64_t nwid_i = it.first;
  1259. char nwidTmp[64];
  1260. OSUtils::ztsnprintf(nwidTmp,sizeof(nwidTmp), "%.16llx", nwid_i);
  1261. tx.zremrangebyscore("network-nodes-online:{"+controllerId+"}:"+nwidTmp,
  1262. sw::redis::RightBoundedInterval<double>(expireOld, sw::redis::BoundType::LEFT_OPEN));
  1263. }
  1264. }
  1265. tx.exec();
  1266. }
  1267. #endif //ZT_CONTROLLER_USE_LIBPQ