2
0

PostgreSQL.cpp 47 KB

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