PostgreSQL.cpp 46 KB

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