PostgreSQL.cpp 47 KB

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