PostgreSQL.cpp 47 KB

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