PostgreSQL.cpp 47 KB

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