EmbeddedNetworkController.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  1. /* (c) ZeroTier, Inc.
  2. * See LICENSE.txt in nonfree/
  3. */
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <time.h>
  9. #ifndef _WIN32
  10. #include <sys/time.h>
  11. #endif
  12. #include "../../include/ZeroTierOne.h"
  13. #include "EmbeddedNetworkController.hpp"
  14. #include "FileDB.hpp"
  15. #include <algorithm>
  16. #include <cctype>
  17. #include <map>
  18. #include <memory>
  19. #include <sstream>
  20. #include <sys/types.h>
  21. #include <thread>
  22. #include <utility>
  23. #ifdef ZT_CONTROLLER_USE_LIBPQ
  24. #include "CV1.hpp"
  25. #include "CV2.hpp"
  26. #endif
  27. #include "../node/CertificateOfMembership.hpp"
  28. #include "../node/Dictionary.hpp"
  29. #include "../node/NetworkConfig.hpp"
  30. #include "../node/Node.hpp"
  31. #include "opentelemetry/trace/provider.h"
  32. using json = nlohmann::json;
  33. // API version reported via JSON control plane
  34. #define ZT_NETCONF_CONTROLLER_API_VERSION 4
  35. // Min duration between requests for an address/nwid combo to prevent floods
  36. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  37. // Global maximum size of arrays in JSON objects
  38. #define ZT_CONTROLLER_MAX_ARRAY_SIZE 16384
  39. namespace ZeroTier {
  40. namespace {
  41. static json _renderRule(ZT_VirtualNetworkRule& rule)
  42. {
  43. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  44. auto tracer = provider->GetTracer("embedded_controller");
  45. auto span = tracer->StartSpan("embedded_controller::renderRule");
  46. auto scope = tracer->WithActiveSpan(span);
  47. char tmp[128];
  48. json r = json::object();
  49. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rule.t & 0x3f);
  50. switch (rt) {
  51. case ZT_NETWORK_RULE_ACTION_DROP:
  52. r["type"] = "ACTION_DROP";
  53. break;
  54. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  55. r["type"] = "ACTION_ACCEPT";
  56. break;
  57. case ZT_NETWORK_RULE_ACTION_TEE:
  58. r["type"] = "ACTION_TEE";
  59. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  60. r["flags"] = (unsigned int)rule.v.fwd.flags;
  61. r["length"] = (unsigned int)rule.v.fwd.length;
  62. break;
  63. case ZT_NETWORK_RULE_ACTION_WATCH:
  64. r["type"] = "ACTION_WATCH";
  65. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  66. r["flags"] = (unsigned int)rule.v.fwd.flags;
  67. r["length"] = (unsigned int)rule.v.fwd.length;
  68. break;
  69. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  70. r["type"] = "ACTION_REDIRECT";
  71. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  72. r["flags"] = (unsigned int)rule.v.fwd.flags;
  73. break;
  74. case ZT_NETWORK_RULE_ACTION_BREAK:
  75. r["type"] = "ACTION_BREAK";
  76. break;
  77. default:
  78. break;
  79. }
  80. if (r.empty()) {
  81. switch (rt) {
  82. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  83. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  84. r["zt"] = Address(rule.v.zt).toString(tmp);
  85. break;
  86. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  87. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  88. r["zt"] = Address(rule.v.zt).toString(tmp);
  89. break;
  90. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  91. r["type"] = "MATCH_VLAN_ID";
  92. r["vlanId"] = (unsigned int)rule.v.vlanId;
  93. break;
  94. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  95. r["type"] = "MATCH_VLAN_PCP";
  96. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  97. break;
  98. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  99. r["type"] = "MATCH_VLAN_DEI";
  100. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  101. break;
  102. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  103. r["type"] = "MATCH_MAC_SOURCE";
  104. OSUtils::ztsnprintf(
  105. tmp,
  106. sizeof(tmp),
  107. "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
  108. (unsigned int)rule.v.mac[0],
  109. (unsigned int)rule.v.mac[1],
  110. (unsigned int)rule.v.mac[2],
  111. (unsigned int)rule.v.mac[3],
  112. (unsigned int)rule.v.mac[4],
  113. (unsigned int)rule.v.mac[5]);
  114. r["mac"] = tmp;
  115. break;
  116. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  117. r["type"] = "MATCH_MAC_DEST";
  118. OSUtils::ztsnprintf(
  119. tmp,
  120. sizeof(tmp),
  121. "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
  122. (unsigned int)rule.v.mac[0],
  123. (unsigned int)rule.v.mac[1],
  124. (unsigned int)rule.v.mac[2],
  125. (unsigned int)rule.v.mac[3],
  126. (unsigned int)rule.v.mac[4],
  127. (unsigned int)rule.v.mac[5]);
  128. r["mac"] = tmp;
  129. break;
  130. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  131. r["type"] = "MATCH_IPV4_SOURCE";
  132. r["ip"] = InetAddress(&(rule.v.ipv4.ip), 4, (unsigned int)rule.v.ipv4.mask).toString(tmp);
  133. break;
  134. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  135. r["type"] = "MATCH_IPV4_DEST";
  136. r["ip"] = InetAddress(&(rule.v.ipv4.ip), 4, (unsigned int)rule.v.ipv4.mask).toString(tmp);
  137. break;
  138. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  139. r["type"] = "MATCH_IPV6_SOURCE";
  140. r["ip"] = InetAddress(rule.v.ipv6.ip, 16, (unsigned int)rule.v.ipv6.mask).toString(tmp);
  141. break;
  142. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  143. r["type"] = "MATCH_IPV6_DEST";
  144. r["ip"] = InetAddress(rule.v.ipv6.ip, 16, (unsigned int)rule.v.ipv6.mask).toString(tmp);
  145. break;
  146. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  147. r["type"] = "MATCH_IP_TOS";
  148. r["mask"] = (unsigned int)rule.v.ipTos.mask;
  149. r["start"] = (unsigned int)rule.v.ipTos.value[0];
  150. r["end"] = (unsigned int)rule.v.ipTos.value[1];
  151. break;
  152. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  153. r["type"] = "MATCH_IP_PROTOCOL";
  154. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  155. break;
  156. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  157. r["type"] = "MATCH_ETHERTYPE";
  158. r["etherType"] = (unsigned int)rule.v.etherType;
  159. break;
  160. case ZT_NETWORK_RULE_MATCH_ICMP:
  161. r["type"] = "MATCH_ICMP";
  162. r["icmpType"] = (unsigned int)rule.v.icmp.type;
  163. if ((rule.v.icmp.flags & 0x01) != 0)
  164. r["icmpCode"] = (unsigned int)rule.v.icmp.code;
  165. else
  166. r["icmpCode"] = json();
  167. break;
  168. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  169. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  170. r["start"] = (unsigned int)rule.v.port[0];
  171. r["end"] = (unsigned int)rule.v.port[1];
  172. break;
  173. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  174. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  175. r["start"] = (unsigned int)rule.v.port[0];
  176. r["end"] = (unsigned int)rule.v.port[1];
  177. break;
  178. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  179. r["type"] = "MATCH_CHARACTERISTICS";
  180. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%.16llx", rule.v.characteristics);
  181. r["mask"] = tmp;
  182. break;
  183. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  184. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  185. r["start"] = (unsigned int)rule.v.frameSize[0];
  186. r["end"] = (unsigned int)rule.v.frameSize[1];
  187. break;
  188. case ZT_NETWORK_RULE_MATCH_RANDOM:
  189. r["type"] = "MATCH_RANDOM";
  190. r["probability"] = (unsigned long)rule.v.randomProbability;
  191. break;
  192. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  193. r["type"] = "MATCH_TAGS_DIFFERENCE";
  194. r["id"] = rule.v.tag.id;
  195. r["value"] = rule.v.tag.value;
  196. break;
  197. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  198. r["type"] = "MATCH_TAGS_BITWISE_AND";
  199. r["id"] = rule.v.tag.id;
  200. r["value"] = rule.v.tag.value;
  201. break;
  202. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  203. r["type"] = "MATCH_TAGS_BITWISE_OR";
  204. r["id"] = rule.v.tag.id;
  205. r["value"] = rule.v.tag.value;
  206. break;
  207. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  208. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  209. r["id"] = rule.v.tag.id;
  210. r["value"] = rule.v.tag.value;
  211. break;
  212. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL:
  213. r["type"] = "MATCH_TAGS_EQUAL";
  214. r["id"] = rule.v.tag.id;
  215. r["value"] = rule.v.tag.value;
  216. break;
  217. case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
  218. r["type"] = "MATCH_TAG_SENDER";
  219. r["id"] = rule.v.tag.id;
  220. r["value"] = rule.v.tag.value;
  221. break;
  222. case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER:
  223. r["type"] = "MATCH_TAG_RECEIVER";
  224. r["id"] = rule.v.tag.id;
  225. r["value"] = rule.v.tag.value;
  226. break;
  227. case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE:
  228. r["type"] = "INTEGER_RANGE";
  229. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%.16llx", rule.v.intRange.start);
  230. r["start"] = tmp;
  231. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%.16llx", rule.v.intRange.start + (uint64_t)rule.v.intRange.end);
  232. r["end"] = tmp;
  233. r["idx"] = rule.v.intRange.idx;
  234. r["little"] = ((rule.v.intRange.format & 0x80) != 0);
  235. r["bits"] = (rule.v.intRange.format & 63) + 1;
  236. break;
  237. default:
  238. break;
  239. }
  240. if (! r.empty()) {
  241. r["not"] = ((rule.t & 0x80) != 0);
  242. r["or"] = ((rule.t & 0x40) != 0);
  243. }
  244. }
  245. return r;
  246. }
  247. static bool _parseRule(json& r, ZT_VirtualNetworkRule& rule)
  248. {
  249. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  250. auto tracer = provider->GetTracer("embedded_controller");
  251. auto span = tracer->StartSpan("embedded_controller::parseRule");
  252. auto scope = tracer->WithActiveSpan(span);
  253. if (! r.is_object())
  254. return false;
  255. const std::string t(OSUtils::jsonString(r["type"], ""));
  256. memset(&rule, 0, sizeof(ZT_VirtualNetworkRule));
  257. if (OSUtils::jsonBool(r["not"], false))
  258. rule.t = 0x80;
  259. else
  260. rule.t = 0x00;
  261. if (OSUtils::jsonBool(r["or"], false))
  262. rule.t |= 0x40;
  263. bool tag = false;
  264. if (t == "ACTION_DROP") {
  265. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  266. return true;
  267. }
  268. else if (t == "ACTION_ACCEPT") {
  269. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  270. return true;
  271. }
  272. else if (t == "ACTION_TEE") {
  273. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  274. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"], "0").c_str()) & 0xffffffffffULL;
  275. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"], 0ULL) & 0xffffffffULL);
  276. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"], 0ULL) & 0xffffULL);
  277. return true;
  278. }
  279. else if (t == "ACTION_WATCH") {
  280. rule.t |= ZT_NETWORK_RULE_ACTION_WATCH;
  281. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"], "0").c_str()) & 0xffffffffffULL;
  282. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"], 0ULL) & 0xffffffffULL);
  283. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"], 0ULL) & 0xffffULL);
  284. return true;
  285. }
  286. else if (t == "ACTION_REDIRECT") {
  287. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  288. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"], "0").c_str()) & 0xffffffffffULL;
  289. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"], 0ULL) & 0xffffffffULL);
  290. return true;
  291. }
  292. else if (t == "ACTION_BREAK") {
  293. rule.t |= ZT_NETWORK_RULE_ACTION_BREAK;
  294. return true;
  295. }
  296. else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  297. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  298. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"], "0").c_str()) & 0xffffffffffULL;
  299. return true;
  300. }
  301. else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  302. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  303. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"], "0").c_str()) & 0xffffffffffULL;
  304. return true;
  305. }
  306. else if (t == "MATCH_VLAN_ID") {
  307. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  308. rule.v.vlanId = (uint16_t)(OSUtils::jsonInt(r["vlanId"], 0ULL) & 0xffffULL);
  309. return true;
  310. }
  311. else if (t == "MATCH_VLAN_PCP") {
  312. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  313. rule.v.vlanPcp = (uint8_t)(OSUtils::jsonInt(r["vlanPcp"], 0ULL) & 0xffULL);
  314. return true;
  315. }
  316. else if (t == "MATCH_VLAN_DEI") {
  317. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  318. rule.v.vlanDei = (uint8_t)(OSUtils::jsonInt(r["vlanDei"], 0ULL) & 0xffULL);
  319. return true;
  320. }
  321. else if (t == "MATCH_MAC_SOURCE") {
  322. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  323. std::string mac(OSUtils::jsonString(r["mac"], "0"));
  324. Utils::cleanMac(mac);
  325. Utils::unhex(mac.c_str(), (unsigned int)mac.length(), rule.v.mac, 6);
  326. return true;
  327. }
  328. else if (t == "MATCH_MAC_DEST") {
  329. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  330. std::string mac(OSUtils::jsonString(r["mac"], "0"));
  331. Utils::cleanMac(mac);
  332. Utils::unhex(mac.c_str(), (unsigned int)mac.length(), rule.v.mac, 6);
  333. return true;
  334. }
  335. else if (t == "MATCH_IPV4_SOURCE") {
  336. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  337. InetAddress ip(OSUtils::jsonString(r["ip"], "0.0.0.0").c_str());
  338. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in*>(&ip)->sin_addr.s_addr;
  339. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in*>(&ip)->sin_port) & 0xff;
  340. if (rule.v.ipv4.mask > 32)
  341. rule.v.ipv4.mask = 32;
  342. return true;
  343. }
  344. else if (t == "MATCH_IPV4_DEST") {
  345. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  346. InetAddress ip(OSUtils::jsonString(r["ip"], "0.0.0.0").c_str());
  347. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in*>(&ip)->sin_addr.s_addr;
  348. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in*>(&ip)->sin_port) & 0xff;
  349. if (rule.v.ipv4.mask > 32)
  350. rule.v.ipv4.mask = 32;
  351. return true;
  352. }
  353. else if (t == "MATCH_IPV6_SOURCE") {
  354. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  355. InetAddress ip(OSUtils::jsonString(r["ip"], "::0").c_str());
  356. memcpy(rule.v.ipv6.ip, reinterpret_cast<struct sockaddr_in6*>(&ip)->sin6_addr.s6_addr, 16);
  357. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6*>(&ip)->sin6_port) & 0xff;
  358. if (rule.v.ipv6.mask > 128)
  359. rule.v.ipv6.mask = 128;
  360. return true;
  361. }
  362. else if (t == "MATCH_IPV6_DEST") {
  363. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  364. InetAddress ip(OSUtils::jsonString(r["ip"], "::0").c_str());
  365. memcpy(rule.v.ipv6.ip, reinterpret_cast<struct sockaddr_in6*>(&ip)->sin6_addr.s6_addr, 16);
  366. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6*>(&ip)->sin6_port) & 0xff;
  367. if (rule.v.ipv6.mask > 128)
  368. rule.v.ipv6.mask = 128;
  369. return true;
  370. }
  371. else if (t == "MATCH_IP_TOS") {
  372. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  373. rule.v.ipTos.mask = (uint8_t)(OSUtils::jsonInt(r["mask"], 0ULL) & 0xffULL);
  374. rule.v.ipTos.value[0] = (uint8_t)(OSUtils::jsonInt(r["start"], 0ULL) & 0xffULL);
  375. rule.v.ipTos.value[1] = (uint8_t)(OSUtils::jsonInt(r["end"], 0ULL) & 0xffULL);
  376. return true;
  377. }
  378. else if (t == "MATCH_IP_PROTOCOL") {
  379. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  380. rule.v.ipProtocol = (uint8_t)(OSUtils::jsonInt(r["ipProtocol"], 0ULL) & 0xffULL);
  381. return true;
  382. }
  383. else if (t == "MATCH_ETHERTYPE") {
  384. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  385. rule.v.etherType = (uint16_t)(OSUtils::jsonInt(r["etherType"], 0ULL) & 0xffffULL);
  386. return true;
  387. }
  388. else if (t == "MATCH_ICMP") {
  389. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  390. rule.v.icmp.type = (uint8_t)(OSUtils::jsonInt(r["icmpType"], 0ULL) & 0xffULL);
  391. json& code = r["icmpCode"];
  392. if (code.is_null()) {
  393. rule.v.icmp.code = 0;
  394. rule.v.icmp.flags = 0x00;
  395. }
  396. else {
  397. rule.v.icmp.code = (uint8_t)(OSUtils::jsonInt(code, 0ULL) & 0xffULL);
  398. rule.v.icmp.flags = 0x01;
  399. }
  400. return true;
  401. }
  402. else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  403. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  404. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"], 0ULL) & 0xffffULL);
  405. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"], (uint64_t)rule.v.port[0]) & 0xffffULL);
  406. return true;
  407. }
  408. else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  409. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  410. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"], 0ULL) & 0xffffULL);
  411. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"], (uint64_t)rule.v.port[0]) & 0xffffULL);
  412. return true;
  413. }
  414. else if (t == "MATCH_CHARACTERISTICS") {
  415. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  416. if (r.count("mask")) {
  417. json& v = r["mask"];
  418. if (v.is_number()) {
  419. rule.v.characteristics = v;
  420. }
  421. else {
  422. std::string tmp = v;
  423. rule.v.characteristics = Utils::hexStrToU64(tmp.c_str());
  424. }
  425. }
  426. return true;
  427. }
  428. else if (t == "MATCH_FRAME_SIZE_RANGE") {
  429. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  430. rule.v.frameSize[0] = (uint16_t)(OSUtils::jsonInt(r["start"], 0ULL) & 0xffffULL);
  431. rule.v.frameSize[1] = (uint16_t)(OSUtils::jsonInt(r["end"], (uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  432. return true;
  433. }
  434. else if (t == "MATCH_RANDOM") {
  435. rule.t |= ZT_NETWORK_RULE_MATCH_RANDOM;
  436. rule.v.randomProbability = (uint32_t)(OSUtils::jsonInt(r["probability"], 0ULL) & 0xffffffffULL);
  437. return true;
  438. }
  439. else if (t == "MATCH_TAGS_DIFFERENCE") {
  440. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  441. tag = true;
  442. }
  443. else if (t == "MATCH_TAGS_BITWISE_AND") {
  444. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  445. tag = true;
  446. }
  447. else if (t == "MATCH_TAGS_BITWISE_OR") {
  448. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  449. tag = true;
  450. }
  451. else if (t == "MATCH_TAGS_BITWISE_XOR") {
  452. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  453. tag = true;
  454. }
  455. else if (t == "MATCH_TAGS_EQUAL") {
  456. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_EQUAL;
  457. tag = true;
  458. }
  459. else if (t == "MATCH_TAG_SENDER") {
  460. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_SENDER;
  461. tag = true;
  462. }
  463. else if (t == "MATCH_TAG_RECEIVER") {
  464. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_RECEIVER;
  465. tag = true;
  466. }
  467. else if (t == "INTEGER_RANGE") {
  468. json& s = r["start"];
  469. if (s.is_string()) {
  470. std::string tmp = s;
  471. rule.v.intRange.start = Utils::hexStrToU64(tmp.c_str());
  472. }
  473. else {
  474. rule.v.intRange.start = OSUtils::jsonInt(s, 0ULL);
  475. }
  476. json& e = r["end"];
  477. if (e.is_string()) {
  478. std::string tmp = e;
  479. rule.v.intRange.end = (uint32_t)(Utils::hexStrToU64(tmp.c_str()) - rule.v.intRange.start);
  480. }
  481. else {
  482. rule.v.intRange.end = (uint32_t)(OSUtils::jsonInt(e, 0ULL) - rule.v.intRange.start);
  483. }
  484. rule.v.intRange.idx = (uint16_t)OSUtils::jsonInt(r["idx"], 0ULL);
  485. rule.v.intRange.format = (OSUtils::jsonBool(r["little"], false)) ? 0x80 : 0x00;
  486. rule.v.intRange.format |= (uint8_t)((OSUtils::jsonInt(r["bits"], 1ULL) - 1) & 63);
  487. }
  488. if (tag) {
  489. rule.v.tag.id = (uint32_t)(OSUtils::jsonInt(r["id"], 0ULL) & 0xffffffffULL);
  490. rule.v.tag.value = (uint32_t)(OSUtils::jsonInt(r["value"], 0ULL) & 0xffffffffULL);
  491. return true;
  492. }
  493. return false;
  494. }
  495. } // anonymous namespace
  496. EmbeddedNetworkController::EmbeddedNetworkController(Node* node, const char* ztPath, const char* dbPath, int listenPort, RedisConfig* rc)
  497. : _startTime(OSUtils::now())
  498. , _listenPort(listenPort)
  499. , _node(node)
  500. , _ztPath(ztPath)
  501. , _path(dbPath)
  502. , _signingId()
  503. , _signingIdAddressString()
  504. , _sender((NetworkController::Sender*)0)
  505. , _db(this)
  506. , _queue()
  507. , _threads()
  508. , _threads_l()
  509. , _memberStatus()
  510. , _memberStatus_l()
  511. , _expiringSoon()
  512. , _expiringSoon_l()
  513. , _rc(rc)
  514. , _ssoExpiryRunning(true)
  515. , _ssoExpiry(std::thread(&EmbeddedNetworkController::_ssoExpiryThread, this))
  516. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  517. , _member_status_lookup { "nc_member_status_lookup", "" }
  518. , _member_status_lookup_count { "nc_member_status_lookup_count", "" }
  519. , _node_is_online { "nc_node_is_online", "" }
  520. , _node_is_online_count { "nc_node_is_online_count", "" }
  521. , _get_and_init_member { "nc_get_and_init_member", "" }
  522. , _get_and_init_member_count { "nc_get_and_init_member_count", "" }
  523. , _have_identity { "nc_have_identity", "" }
  524. , _have_identity_count { "nc_have_identity_count", "" }
  525. , _determine_auth { "nc_determine_auth", "" }
  526. , _determine_auth_count { "nc_determine_auth_count", "" }
  527. , _sso_check { "nc_sso_check", "" }
  528. , _sso_check_count { "nc_sso_check_count", "" }
  529. , _auth_check { "nc_auth_check", "" }
  530. , _auth_check_count { "nc_auth_check_count", "" }
  531. , _json_schlep { "nc_json_schlep", "" }
  532. , _json_schlep_count { "nc_json_schlep_count", "" }
  533. , _issue_certificate { "nc_issue_certificate", "" }
  534. , _issue_certificate_count { "nc_issue_certificate_count", "" }
  535. , _save_member { "nc_save_member", "" }
  536. , _save_member_count { "nc_save_member_count", "" }
  537. , _send_netconf { "nc_send_netconf2", "" }
  538. , _send_netconf_count { "nc_send_netconf2_count", "" }
  539. #endif
  540. {
  541. }
  542. EmbeddedNetworkController::~EmbeddedNetworkController()
  543. {
  544. std::lock_guard<std::mutex> l(_threads_l);
  545. _queue.stop();
  546. for (auto t = _threads.begin(); t != _threads.end(); ++t) {
  547. t->join();
  548. }
  549. _ssoExpiryRunning = false;
  550. _ssoExpiry.join();
  551. }
  552. void EmbeddedNetworkController::setSSORedirectURL(const std::string& url)
  553. {
  554. _ssoRedirectURL = url;
  555. }
  556. void EmbeddedNetworkController::init(const Identity& signingId, Sender* sender)
  557. {
  558. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  559. auto tracer = provider->GetTracer("embedded_controller");
  560. auto span = tracer->StartSpan("embedded_controller::init");
  561. auto scope = tracer->WithActiveSpan(span);
  562. char tmp[64];
  563. _signingId = signingId;
  564. _sender = sender;
  565. _signingIdAddressString = signingId.address().toString(tmp);
  566. #ifdef ZT_CONTROLLER_USE_LIBPQ
  567. if ((_path.length() > 9) && (_path.substr(0, 9) == "postgres:")) {
  568. fprintf(stderr, "CV1\n");
  569. _db.addDB(std::shared_ptr<CV1>(new CV1(_signingId, _path.substr(9).c_str(), _listenPort, _rc)));
  570. }
  571. else if ((_path.length() > 4) && (_path.substr(0, 4) == "cv2:")) {
  572. fprintf(stderr, "CV2\n");
  573. _db.addDB(std::shared_ptr<CV2>(new CV2(_signingId, _path.substr(4).c_str(), _listenPort)));
  574. }
  575. else {
  576. fprintf(stderr, "FileDB\n");
  577. #endif
  578. _db.addDB(std::shared_ptr<FileDB>(new FileDB(_path.c_str())));
  579. #ifdef ZT_CONTROLLER_USE_LIBPQ
  580. }
  581. #endif
  582. _db.waitForReady();
  583. }
  584. void EmbeddedNetworkController::request(uint64_t nwid, const InetAddress& fromAddr, uint64_t requestPacketId, const Identity& identity, const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY>& metaData)
  585. {
  586. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  587. auto tracer = provider->GetTracer("embedded_controller");
  588. auto span = tracer->StartSpan("embedded_controller::request");
  589. auto scope = tracer->WithActiveSpan(span);
  590. if (((! _signingId) || (! _signingId.hasPrivate())) || (_signingId.address().toInt() != (nwid >> 24)) || (! _sender))
  591. return;
  592. _startThreads();
  593. const int64_t now = OSUtils::now();
  594. if (requestPacketId) {
  595. std::lock_guard<std::mutex> l(_memberStatus_l);
  596. _MemberStatus& ms = _memberStatus[_MemberStatusKey(nwid, identity.address().toInt())];
  597. if ((now - ms.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD) {
  598. return;
  599. }
  600. ms.lastRequestTime = now;
  601. }
  602. _RQEntry* qe = new _RQEntry;
  603. qe->nwid = nwid;
  604. qe->requestPacketId = requestPacketId;
  605. qe->fromAddr = fromAddr;
  606. qe->identity = identity;
  607. qe->metaData = metaData;
  608. qe->type = _RQEntry::RQENTRY_TYPE_REQUEST;
  609. _queue.post(qe);
  610. }
  611. std::string EmbeddedNetworkController::networkUpdateFromPostData(uint64_t networkID, const std::string& body)
  612. {
  613. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  614. auto tracer = provider->GetTracer("embedded_controller");
  615. auto span = tracer->StartSpan("embedded_controller::networkUpdateFromPostData");
  616. auto scope = tracer->WithActiveSpan(span);
  617. json b = OSUtils::jsonParse(body);
  618. char nwids[24];
  619. OSUtils::ztsnprintf(nwids, sizeof(nwids), "%.16llx", networkID);
  620. json network;
  621. _db.get(networkID, network);
  622. DB::initNetwork(network);
  623. if (b.count("name"))
  624. network["name"] = OSUtils::jsonString(b["name"], "");
  625. if (b.count("private"))
  626. network["private"] = OSUtils::jsonBool(b["private"], true);
  627. if (b.count("enableBroadcast"))
  628. network["enableBroadcast"] = OSUtils::jsonBool(b["enableBroadcast"], false);
  629. if (b.count("multicastLimit"))
  630. network["multicastLimit"] = OSUtils::jsonInt(b["multicastLimit"], 32ULL);
  631. if (b.count("mtu"))
  632. network["mtu"] = std::max(std::min((unsigned int)OSUtils::jsonInt(b["mtu"], ZT_DEFAULT_MTU), (unsigned int)ZT_MAX_MTU), (unsigned int)ZT_MIN_MTU);
  633. if (b.count("remoteTraceTarget")) {
  634. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"], ""));
  635. if (rtt.length() == 10) {
  636. network["remoteTraceTarget"] = rtt;
  637. }
  638. else {
  639. network["remoteTraceTarget"] = json();
  640. }
  641. }
  642. if (b.count("remoteTraceLevel"))
  643. network["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"], 0ULL);
  644. if (b.count("v4AssignMode")) {
  645. json nv4m;
  646. json& v4m = b["v4AssignMode"];
  647. if (v4m.is_string()) { // backward compatibility
  648. nv4m["zt"] = (OSUtils::jsonString(v4m, "") == "zt");
  649. }
  650. else if (v4m.is_object()) {
  651. nv4m["zt"] = OSUtils::jsonBool(v4m["zt"], false);
  652. }
  653. else
  654. nv4m["zt"] = false;
  655. network["v4AssignMode"] = nv4m;
  656. }
  657. if (b.count("v6AssignMode")) {
  658. json nv6m;
  659. json& v6m = b["v6AssignMode"];
  660. if (! nv6m.is_object())
  661. nv6m = json::object();
  662. if (v6m.is_string()) { // backward compatibility
  663. std::vector<std::string> v6ms(OSUtils::split(OSUtils::jsonString(v6m, "").c_str(), ",", "", ""));
  664. std::sort(v6ms.begin(), v6ms.end());
  665. v6ms.erase(std::unique(v6ms.begin(), v6ms.end()), v6ms.end());
  666. nv6m["rfc4193"] = false;
  667. nv6m["zt"] = false;
  668. nv6m["6plane"] = false;
  669. for (std::vector<std::string>::iterator i(v6ms.begin()); i != v6ms.end(); ++i) {
  670. if (*i == "rfc4193")
  671. nv6m["rfc4193"] = true;
  672. else if (*i == "zt")
  673. nv6m["zt"] = true;
  674. else if (*i == "6plane")
  675. nv6m["6plane"] = true;
  676. }
  677. }
  678. else if (v6m.is_object()) {
  679. if (v6m.count("rfc4193"))
  680. nv6m["rfc4193"] = OSUtils::jsonBool(v6m["rfc4193"], false);
  681. if (v6m.count("zt"))
  682. nv6m["zt"] = OSUtils::jsonBool(v6m["zt"], false);
  683. if (v6m.count("6plane"))
  684. nv6m["6plane"] = OSUtils::jsonBool(v6m["6plane"], false);
  685. }
  686. else {
  687. nv6m["rfc4193"] = false;
  688. nv6m["zt"] = false;
  689. nv6m["6plane"] = false;
  690. }
  691. network["v6AssignMode"] = nv6m;
  692. }
  693. if (b.count("relays")) {
  694. json nrelays = json::array();
  695. char rtmp[64];
  696. json& relays = b["relays"];
  697. if (relays.is_array()) {
  698. for (unsigned long i = 0; i < relays.size(); ++i) {
  699. json& relay = relays[i];
  700. if (relay.is_string()) {
  701. nrelays.push_back(Address(Utils::hexStrToU64(OSUtils::jsonString(relay, "0").c_str()) & 0xffffffffffULL).toString(rtmp));
  702. }
  703. }
  704. }
  705. if (nrelays.size() > 0)
  706. network["relays"] = nrelays;
  707. else
  708. network.erase("relays");
  709. }
  710. if (b.count("routes")) {
  711. json& rts = b["routes"];
  712. if (rts.is_array()) {
  713. json nrts = json::array();
  714. for (unsigned long i = 0; i < rts.size(); ++i) {
  715. json& rt = rts[i];
  716. if (rt.is_object()) {
  717. json& target = rt["target"];
  718. json& via = rt["via"];
  719. if (target.is_string()) {
  720. InetAddress t(target.get<std::string>().c_str());
  721. InetAddress v;
  722. if (via.is_string())
  723. v.fromString(via.get<std::string>().c_str());
  724. if (((t.ss_family == AF_INET) || (t.ss_family == AF_INET6)) && (t.netmaskBitsValid())) {
  725. json tmp;
  726. char tmp2[64];
  727. tmp["target"] = t.toString(tmp2);
  728. if (v.ss_family == t.ss_family)
  729. tmp["via"] = v.toIpString(tmp2);
  730. else
  731. tmp["via"] = json();
  732. nrts.push_back(tmp);
  733. if (nrts.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  734. break;
  735. }
  736. }
  737. }
  738. }
  739. network["routes"] = nrts;
  740. }
  741. }
  742. if (b.count("ipAssignmentPools")) {
  743. json& ipp = b["ipAssignmentPools"];
  744. if (ipp.is_array()) {
  745. json nipp = json::array();
  746. for (unsigned long i = 0; i < ipp.size(); ++i) {
  747. json& ip = ipp[i];
  748. if ((ip.is_object()) && (ip.count("ipRangeStart")) && (ip.count("ipRangeEnd"))) {
  749. InetAddress f(OSUtils::jsonString(ip["ipRangeStart"], "").c_str());
  750. InetAddress t(OSUtils::jsonString(ip["ipRangeEnd"], "").c_str());
  751. if (((f.ss_family == AF_INET) || (f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family)) {
  752. json tmp = json::object();
  753. char tmp2[64];
  754. tmp["ipRangeStart"] = f.toIpString(tmp2);
  755. tmp["ipRangeEnd"] = t.toIpString(tmp2);
  756. nipp.push_back(tmp);
  757. if (nipp.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  758. break;
  759. }
  760. }
  761. }
  762. network["ipAssignmentPools"] = nipp;
  763. }
  764. }
  765. if (b.count("rules")) {
  766. json& rules = b["rules"];
  767. if (rules.is_array()) {
  768. json nrules = json::array();
  769. for (unsigned long i = 0; i < rules.size(); ++i) {
  770. json& rule = rules[i];
  771. if (rule.is_object()) {
  772. ZT_VirtualNetworkRule ztr;
  773. if (_parseRule(rule, ztr)) {
  774. nrules.push_back(_renderRule(ztr));
  775. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  776. break;
  777. }
  778. }
  779. }
  780. network["rules"] = nrules;
  781. }
  782. }
  783. if (b.count("authTokens")) {
  784. json& authTokens = b["authTokens"];
  785. if (authTokens.is_object()) {
  786. json nat;
  787. for (json::iterator t(authTokens.begin()); t != authTokens.end(); ++t) {
  788. if ((t.value().is_number()) && (t.value() >= 0))
  789. nat[t.key()] = t.value();
  790. }
  791. network["authTokens"] = nat;
  792. }
  793. else {
  794. network["authTokens"] = { {} };
  795. }
  796. }
  797. if (b.count("capabilities")) {
  798. json& capabilities = b["capabilities"];
  799. if (capabilities.is_array()) {
  800. std::map<uint64_t, json> ncaps;
  801. for (unsigned long i = 0; i < capabilities.size(); ++i) {
  802. json& cap = capabilities[i];
  803. if (cap.is_object()) {
  804. json ncap = json::object();
  805. const uint64_t capId = OSUtils::jsonInt(cap["id"], 0ULL);
  806. ncap["id"] = capId;
  807. ncap["default"] = OSUtils::jsonBool(cap["default"], false);
  808. json& rules = cap["rules"];
  809. json nrules = json::array();
  810. if (rules.is_array()) {
  811. for (unsigned long i = 0; i < rules.size(); ++i) {
  812. json& rule = rules[i];
  813. if (rule.is_object()) {
  814. ZT_VirtualNetworkRule ztr;
  815. if (_parseRule(rule, ztr)) {
  816. nrules.push_back(_renderRule(ztr));
  817. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  818. break;
  819. }
  820. }
  821. }
  822. }
  823. ncap["rules"] = nrules;
  824. ncaps[capId] = ncap;
  825. }
  826. }
  827. json ncapsa = json::array();
  828. for (std::map<uint64_t, json>::iterator c(ncaps.begin()); c != ncaps.end(); ++c) {
  829. ncapsa.push_back(c->second);
  830. if (ncapsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  831. break;
  832. }
  833. network["capabilities"] = ncapsa;
  834. }
  835. }
  836. if (b.count("tags")) {
  837. json& tags = b["tags"];
  838. if (tags.is_array()) {
  839. std::map<uint64_t, json> ntags;
  840. for (unsigned long i = 0; i < tags.size(); ++i) {
  841. json& tag = tags[i];
  842. if (tag.is_object()) {
  843. json ntag = json::object();
  844. const uint64_t tagId = OSUtils::jsonInt(tag["id"], 0ULL);
  845. ntag["id"] = tagId;
  846. json& dfl = tag["default"];
  847. if (dfl.is_null())
  848. ntag["default"] = dfl;
  849. else
  850. ntag["default"] = OSUtils::jsonInt(dfl, 0ULL);
  851. ntags[tagId] = ntag;
  852. }
  853. }
  854. json ntagsa = json::array();
  855. for (std::map<uint64_t, json>::iterator t(ntags.begin()); t != ntags.end(); ++t) {
  856. ntagsa.push_back(t->second);
  857. if (ntagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  858. break;
  859. }
  860. network["tags"] = ntagsa;
  861. }
  862. }
  863. if (b.count("dns")) {
  864. json& dns = b["dns"];
  865. if (dns.is_object()) {
  866. json nd;
  867. nd["domain"] = dns["domain"];
  868. json& srv = dns["servers"];
  869. if (srv.is_array()) {
  870. json ns = json::array();
  871. for (unsigned int i = 0; i < srv.size(); ++i) {
  872. ns.push_back(srv[i]);
  873. }
  874. nd["servers"] = ns;
  875. }
  876. network["dns"] = nd;
  877. }
  878. }
  879. network["id"] = nwids;
  880. network["nwid"] = nwids;
  881. DB::cleanNetwork(network);
  882. _db.save(network, true);
  883. return network.dump();
  884. }
  885. void EmbeddedNetworkController::configureHTTPControlPlane(httplib::Server& s, httplib::Server& sv6, const std::function<void(const httplib::Request&, httplib::Response&, std::string)> setContent)
  886. {
  887. // Control plane Endpoints
  888. std::string controllerPath = "/controller";
  889. std::string networkListPath = "/controller/network";
  890. std::string networkListPath2 = "/unstable/controller/network";
  891. std::string networkPath = "/controller/network/([0-9a-fA-F]{16})";
  892. std::string oldAndBustedNetworkCreatePath = "/controller/network/([0-9a-fA-F]{10})______";
  893. std::string memberListPath = "/controller/network/([0-9a-fA-F]{16})/member";
  894. std::string memberListPath2 = "/unstable/controller/network/([0-9a-fA-F]{16})/member";
  895. std::string memberPath = "/controller/network/([0-9a-fA-F]{16})/member/([0-9a-fA-F]{10})";
  896. auto controllerGet = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  897. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  898. auto tracer = provider->GetTracer("embedded_controller");
  899. auto span = tracer->StartSpan("embedded_controller::controllerGet");
  900. auto scope = tracer->WithActiveSpan(span);
  901. char tmp[4096];
  902. const bool dbOk = _db.isReady();
  903. OSUtils::ztsnprintf(
  904. tmp,
  905. sizeof(tmp),
  906. "{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",
  907. ZT_NETCONF_CONTROLLER_API_VERSION,
  908. (unsigned long long)OSUtils::now(),
  909. dbOk ? "true" : "false");
  910. if (! dbOk) {
  911. res.status = 503;
  912. }
  913. setContent(req, res, tmp);
  914. };
  915. s.Get(controllerPath, controllerGet);
  916. sv6.Get(controllerPath, controllerGet);
  917. auto networkListGet = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  918. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  919. auto tracer = provider->GetTracer("embedded_controller");
  920. auto span = tracer->StartSpan("embedded_controller::networkListGet");
  921. auto scope = tracer->WithActiveSpan(span);
  922. std::set<uint64_t> networkIds;
  923. _db.networks(networkIds);
  924. char tmp[64];
  925. auto out = json::array();
  926. for (std::set<uint64_t>::const_iterator i(networkIds.begin()); i != networkIds.end(); ++i) {
  927. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%.16llx", *i);
  928. out.push_back(tmp);
  929. }
  930. setContent(req, res, out.dump());
  931. };
  932. s.Get(networkListPath, networkListGet);
  933. sv6.Get(networkListPath, networkListGet);
  934. auto networkListGet2 = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  935. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  936. auto tracer = provider->GetTracer("embedded_controller");
  937. auto span = tracer->StartSpan("embedded_controller::networkListGet2");
  938. auto scope = tracer->WithActiveSpan(span);
  939. std::set<uint64_t> networkIds;
  940. _db.networks(networkIds);
  941. auto meta = json::object();
  942. auto data = json::array();
  943. uint64_t networkCount = 0;
  944. for (std::set<uint64_t>::const_iterator nwid(networkIds.begin()); nwid != networkIds.end(); ++nwid) {
  945. json network;
  946. if (! _db.get(*nwid, network)) {
  947. continue;
  948. }
  949. std::vector<json> memTmp;
  950. if (_db.get(*nwid, network, memTmp)) {
  951. if (! network.is_null()) {
  952. uint64_t authorizedCount = 0;
  953. uint64_t totalCount = memTmp.size();
  954. networkCount++;
  955. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  956. bool a = OSUtils::jsonBool((*m)["authorized"], 0);
  957. if (a) {
  958. authorizedCount++;
  959. }
  960. }
  961. auto nwMeta = json::object();
  962. nwMeta["totalMemberCount"] = totalCount;
  963. nwMeta["authorizedMemberCount"] = authorizedCount;
  964. network["meta"] = nwMeta;
  965. data.push_back(network);
  966. }
  967. }
  968. }
  969. meta["networkCount"] = networkCount;
  970. auto out = json::object();
  971. out["data"] = data;
  972. out["meta"] = meta;
  973. setContent(req, res, out.dump());
  974. };
  975. s.Get(networkListPath2, networkListGet2);
  976. sv6.Get(networkListPath2, networkListGet2);
  977. auto networkGet = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  978. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  979. auto tracer = provider->GetTracer("embedded_controller");
  980. auto span = tracer->StartSpan("embedded_controller::networkGet");
  981. auto scope = tracer->WithActiveSpan(span);
  982. auto networkID = req.matches[1];
  983. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  984. json network;
  985. if (! _db.get(nwid, network)) {
  986. res.status = 404;
  987. return;
  988. }
  989. setContent(req, res, network.dump());
  990. };
  991. s.Get(networkPath, networkGet);
  992. sv6.Get(networkPath, networkGet);
  993. auto createNewNetwork = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  994. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  995. auto tracer = provider->GetTracer("embedded_controller");
  996. auto span = tracer->StartSpan("embedded_controller::createNewNetwork");
  997. auto scope = tracer->WithActiveSpan(span);
  998. // fprintf(stderr, "creating new network (new style)\n");
  999. uint64_t nwid = 0;
  1000. uint64_t nwidPrefix = (Utils::hexStrToU64(_signingIdAddressString.c_str()) << 24) & 0xffffffffff000000ULL;
  1001. uint64_t nwidPostfix = 0;
  1002. for (unsigned long k = 0; k < 100000; ++k) { // sanity limit on trials
  1003. Utils::getSecureRandom(&nwidPostfix, sizeof(nwidPostfix));
  1004. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1005. if ((tryNwid & 0xffffffULL) == 0ULL)
  1006. tryNwid |= 1ULL;
  1007. if (! _db.hasNetwork(tryNwid)) {
  1008. nwid = tryNwid;
  1009. break;
  1010. }
  1011. }
  1012. if (! nwid) {
  1013. res.status = 503;
  1014. return;
  1015. }
  1016. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  1017. };
  1018. s.Put(networkListPath, createNewNetwork);
  1019. s.Post(networkListPath, createNewNetwork);
  1020. sv6.Put(networkListPath, createNewNetwork);
  1021. sv6.Post(networkListPath, createNewNetwork);
  1022. auto createNewNetworkOldAndBusted = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1023. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1024. auto tracer = provider->GetTracer("embedded_controller");
  1025. auto span = tracer->StartSpan("embedded_controller::createNewNetworkOldAndBusted");
  1026. auto scope = tracer->WithActiveSpan(span);
  1027. auto inID = req.matches[1].str();
  1028. if (inID != _signingIdAddressString) {
  1029. res.status = 400;
  1030. return;
  1031. }
  1032. uint64_t nwid = 0;
  1033. uint64_t nwidPrefix = (Utils::hexStrToU64(inID.c_str()) << 24) & 0xffffffffff000000ULL;
  1034. uint64_t nwidPostfix = 0;
  1035. for (unsigned long k = 0; k < 100000; ++k) { // sanity limit on trials
  1036. Utils::getSecureRandom(&nwidPostfix, sizeof(nwidPostfix));
  1037. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1038. if ((tryNwid & 0xffffffULL) == 0ULL)
  1039. tryNwid |= 1ULL;
  1040. if (! _db.hasNetwork(tryNwid)) {
  1041. nwid = tryNwid;
  1042. break;
  1043. }
  1044. }
  1045. if (! nwid) {
  1046. res.status = 503;
  1047. return;
  1048. }
  1049. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  1050. };
  1051. s.Put(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  1052. s.Post(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  1053. sv6.Put(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  1054. sv6.Post(oldAndBustedNetworkCreatePath, createNewNetworkOldAndBusted);
  1055. auto networkPost = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1056. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1057. auto tracer = provider->GetTracer("embedded_controller");
  1058. auto span = tracer->StartSpan("embedded_controller::networkPost");
  1059. auto scope = tracer->WithActiveSpan(span);
  1060. auto networkID = req.matches[1].str();
  1061. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1062. res.status = 200;
  1063. setContent(req, res, networkUpdateFromPostData(nwid, req.body));
  1064. };
  1065. s.Put(networkPath, networkPost);
  1066. s.Post(networkPath, networkPost);
  1067. sv6.Put(networkPath, networkPost);
  1068. sv6.Post(networkPath, networkPost);
  1069. auto networkDelete = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1070. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1071. auto tracer = provider->GetTracer("embedded_controller");
  1072. auto span = tracer->StartSpan("embedded_controller::networkDelete");
  1073. auto scope = tracer->WithActiveSpan(span);
  1074. auto networkID = req.matches[1].str();
  1075. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1076. json network;
  1077. if (! _db.get(nwid, network)) {
  1078. res.status = 404;
  1079. return;
  1080. }
  1081. _db.eraseNetwork(nwid);
  1082. setContent(req, res, network.dump());
  1083. };
  1084. s.Delete(networkPath, networkDelete);
  1085. sv6.Delete(networkPath, networkDelete);
  1086. auto memberListGet = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1087. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1088. auto tracer = provider->GetTracer("embedded_controller");
  1089. auto span = tracer->StartSpan("embedded_controller::memberListGet");
  1090. auto scope = tracer->WithActiveSpan(span);
  1091. auto networkID = req.matches[1];
  1092. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  1093. json network;
  1094. if (! _db.get(nwid, network)) {
  1095. res.status = 404;
  1096. return;
  1097. }
  1098. json out = json::object();
  1099. std::vector<json> memTmp;
  1100. if (_db.get(nwid, network, memTmp)) {
  1101. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  1102. int revision = OSUtils::jsonInt((*m)["revision"], 0);
  1103. std::string id = OSUtils::jsonString((*m)["id"], "");
  1104. if (id.length() == 10) {
  1105. out[id] = revision;
  1106. }
  1107. }
  1108. }
  1109. setContent(req, res, out.dump());
  1110. };
  1111. s.Get(memberListPath, memberListGet);
  1112. sv6.Get(memberListPath, memberListGet);
  1113. auto memberListGet2 = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1114. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1115. auto tracer = provider->GetTracer("embedded_controller");
  1116. auto span = tracer->StartSpan("embedded_controller::memberListGet2");
  1117. auto scope = tracer->WithActiveSpan(span);
  1118. auto networkID = req.matches[1];
  1119. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  1120. json network;
  1121. if (! _db.get(nwid, network)) {
  1122. res.status = 404;
  1123. return;
  1124. }
  1125. auto out = nlohmann::json::object();
  1126. auto meta = nlohmann::json::object();
  1127. std::vector<json> memTmp;
  1128. if (_db.get(nwid, network, memTmp)) {
  1129. uint64_t authorizedCount = 0;
  1130. uint64_t totalCount = memTmp.size();
  1131. for (auto m = memTmp.begin(); m != memTmp.end(); ++m) {
  1132. bool a = OSUtils::jsonBool((*m)["authorized"], 0);
  1133. if (a) {
  1134. authorizedCount++;
  1135. }
  1136. }
  1137. meta["totalCount"] = totalCount;
  1138. meta["authorizedCount"] = authorizedCount;
  1139. out["data"] = memTmp;
  1140. out["meta"] = meta;
  1141. setContent(req, res, out.dump());
  1142. }
  1143. else {
  1144. res.status = 404;
  1145. return;
  1146. }
  1147. };
  1148. s.Get(memberListPath2, memberListGet2);
  1149. sv6.Get(memberListPath2, memberListGet2);
  1150. auto memberGet = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1151. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1152. auto tracer = provider->GetTracer("embedded_controller");
  1153. auto span = tracer->StartSpan("embedded_controller::memberGet");
  1154. auto scope = tracer->WithActiveSpan(span);
  1155. auto networkID = req.matches[1];
  1156. auto memberID = req.matches[2];
  1157. uint64_t nwid = Utils::hexStrToU64(networkID.str().c_str());
  1158. uint64_t memid = Utils::hexStrToU64(memberID.str().c_str());
  1159. json network;
  1160. json member;
  1161. if (! _db.get(nwid, network, memid, member)) {
  1162. res.status = 404;
  1163. return;
  1164. }
  1165. setContent(req, res, member.dump());
  1166. };
  1167. s.Get(memberPath, memberGet);
  1168. sv6.Get(memberPath, memberGet);
  1169. auto memberPost = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1170. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1171. auto tracer = provider->GetTracer("embedded_controller");
  1172. auto span = tracer->StartSpan("embedded_controller::memberPost");
  1173. auto scope = tracer->WithActiveSpan(span);
  1174. auto networkID = req.matches[1].str();
  1175. auto memberID = req.matches[2].str();
  1176. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1177. uint64_t memid = Utils::hexStrToU64(memberID.c_str());
  1178. if (! _db.hasNetwork(nwid)) {
  1179. res.status = 404;
  1180. return;
  1181. }
  1182. json network;
  1183. json member;
  1184. _db.get(nwid, network, memid, member);
  1185. DB::initMember(member);
  1186. json b = OSUtils::jsonParse(req.body);
  1187. if (b.count("activeBridge"))
  1188. member["activeBridge"] = OSUtils::jsonBool(b["activeBridge"], false);
  1189. if (b.count("noAutoAssignIps"))
  1190. member["noAutoAssignIps"] = OSUtils::jsonBool(b["noAutoAssignIps"], false);
  1191. if (b.count("authenticationExpiryTime"))
  1192. member["authenticationExpiryTime"] = (uint64_t)OSUtils::jsonInt(b["authenticationExpiryTime"], 0ULL);
  1193. if (b.count("authenticationURL"))
  1194. member["authenticationURL"] = OSUtils::jsonString(b["authenticationURL"], "");
  1195. if (b.count("name"))
  1196. member["name"] = OSUtils::jsonString(b["name"], "");
  1197. if (b.count("remoteTraceTarget")) {
  1198. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"], ""));
  1199. if (rtt.length() == 10) {
  1200. member["remoteTraceTarget"] = rtt;
  1201. }
  1202. else {
  1203. member["remoteTraceTarget"] = json();
  1204. }
  1205. }
  1206. if (b.count("remoteTraceLevel"))
  1207. member["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"], 0ULL);
  1208. if (b.count("authorized")) {
  1209. const bool newAuth = OSUtils::jsonBool(b["authorized"], false);
  1210. if (newAuth != OSUtils::jsonBool(member["authorized"], false)) {
  1211. member["authorized"] = newAuth;
  1212. member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = OSUtils::now();
  1213. if (newAuth) {
  1214. member["lastAuthorizedCredentialType"] = "api";
  1215. member["lastAuthorizedCredential"] = json();
  1216. }
  1217. }
  1218. }
  1219. if (b.count("ipAssignments")) {
  1220. json& ipa = b["ipAssignments"];
  1221. if (ipa.is_array()) {
  1222. json mipa(json::array());
  1223. for (unsigned long i = 0; i < ipa.size(); ++i) {
  1224. std::string ips = ipa[i];
  1225. InetAddress ip(ips.c_str());
  1226. if ((ip.ss_family == AF_INET) || (ip.ss_family == AF_INET6)) {
  1227. char tmpip[64];
  1228. mipa.push_back(ip.toIpString(tmpip));
  1229. if (mipa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1230. break;
  1231. }
  1232. }
  1233. member["ipAssignments"] = mipa;
  1234. }
  1235. }
  1236. if (b.count("tags")) {
  1237. json& tags = b["tags"];
  1238. if (tags.is_array()) {
  1239. std::map<uint64_t, uint64_t> mtags;
  1240. for (unsigned long i = 0; i < tags.size(); ++i) {
  1241. json& tag = tags[i];
  1242. if ((tag.is_array()) && (tag.size() == 2))
  1243. mtags[OSUtils::jsonInt(tag[0], 0ULL) & 0xffffffffULL] = OSUtils::jsonInt(tag[1], 0ULL) & 0xffffffffULL;
  1244. }
  1245. json mtagsa = json::array();
  1246. for (std::map<uint64_t, uint64_t>::iterator t(mtags.begin()); t != mtags.end(); ++t) {
  1247. json ta = json::array();
  1248. ta.push_back(t->first);
  1249. ta.push_back(t->second);
  1250. mtagsa.push_back(ta);
  1251. if (mtagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1252. break;
  1253. }
  1254. member["tags"] = mtagsa;
  1255. }
  1256. }
  1257. if (b.count("capabilities")) {
  1258. json& capabilities = b["capabilities"];
  1259. if (capabilities.is_array()) {
  1260. json mcaps = json::array();
  1261. for (unsigned long i = 0; i < capabilities.size(); ++i) {
  1262. mcaps.push_back(OSUtils::jsonInt(capabilities[i], 0ULL));
  1263. if (mcaps.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  1264. break;
  1265. }
  1266. std::sort(mcaps.begin(), mcaps.end());
  1267. mcaps.erase(std::unique(mcaps.begin(), mcaps.end()), mcaps.end());
  1268. member["capabilities"] = mcaps;
  1269. }
  1270. }
  1271. member["id"] = memberID;
  1272. member["address"] = memberID;
  1273. member["nwid"] = networkID;
  1274. DB::cleanMember(member);
  1275. _db.save(member, true);
  1276. setContent(req, res, member.dump());
  1277. };
  1278. s.Put(memberPath, memberPost);
  1279. s.Post(memberPath, memberPost);
  1280. sv6.Put(memberPath, memberPost);
  1281. sv6.Post(memberPath, memberPost);
  1282. auto memberDelete = [&, setContent](const httplib::Request& req, httplib::Response& res) {
  1283. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1284. auto tracer = provider->GetTracer("embedded_controller");
  1285. auto span = tracer->StartSpan("embedded_controller::memberDelete");
  1286. auto scope = tracer->WithActiveSpan(span);
  1287. auto networkID = req.matches[1].str();
  1288. auto memberID = req.matches[2].str();
  1289. uint64_t nwid = Utils::hexStrToU64(networkID.c_str());
  1290. uint64_t address = Utils::hexStrToU64(memberID.c_str());
  1291. json network, member;
  1292. if (! _db.get(nwid, network, address, member)) {
  1293. res.status = 404;
  1294. return;
  1295. }
  1296. if (! member.size()) {
  1297. res.status = 404;
  1298. return;
  1299. }
  1300. _db.eraseMember(nwid, address);
  1301. setContent(req, res, member.dump());
  1302. };
  1303. s.Delete(memberPath, memberDelete);
  1304. sv6.Delete(memberPath, memberDelete);
  1305. }
  1306. void EmbeddedNetworkController::handleRemoteTrace(const ZT_RemoteTrace& rt)
  1307. {
  1308. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1309. auto tracer = provider->GetTracer("embedded_controller");
  1310. auto span = tracer->StartSpan("embedded_controller::handleRemoteTrace");
  1311. auto scope = tracer->WithActiveSpan(span);
  1312. static volatile unsigned long idCounter = 0;
  1313. char id[128], tmp[128];
  1314. std::string k, v;
  1315. try {
  1316. // Convert Dictionary into JSON object
  1317. json d;
  1318. char* saveptr = (char*)0;
  1319. for (char* l = Utils::stok(rt.data, "\n", &saveptr); (l); l = Utils::stok((char*)0, "\n", &saveptr)) {
  1320. char* eq = strchr(l, '=');
  1321. if (eq > l) {
  1322. k.assign(l, (unsigned long)(eq - l));
  1323. v.clear();
  1324. ++eq;
  1325. while (*eq) {
  1326. if (*eq == '\\') {
  1327. ++eq;
  1328. if (*eq) {
  1329. switch (*eq) {
  1330. case 'r':
  1331. v.push_back('\r');
  1332. break;
  1333. case 'n':
  1334. v.push_back('\n');
  1335. break;
  1336. case '0':
  1337. v.push_back((char)0);
  1338. break;
  1339. case 'e':
  1340. v.push_back('=');
  1341. break;
  1342. default:
  1343. v.push_back(*eq);
  1344. break;
  1345. }
  1346. ++eq;
  1347. }
  1348. }
  1349. else {
  1350. v.push_back(*(eq++));
  1351. }
  1352. }
  1353. if ((k.length() > 0) && (v.length() > 0))
  1354. d[k] = v;
  1355. }
  1356. }
  1357. const int64_t now = OSUtils::now();
  1358. OSUtils::ztsnprintf(id, sizeof(id), "%.10llx-%.16llx-%.10llx-%.4x", _signingId.address().toInt(), now, rt.origin, (unsigned int)(idCounter++ & 0xffff));
  1359. d["id"] = id;
  1360. d["objtype"] = "trace";
  1361. d["ts"] = now;
  1362. d["nodeId"] = Utils::hex10(rt.origin, tmp);
  1363. _db.save(d, true);
  1364. }
  1365. catch (...) {
  1366. // drop invalid trace messages if an error occurs
  1367. }
  1368. }
  1369. void EmbeddedNetworkController::onNetworkUpdate(const void* db, uint64_t networkId, const nlohmann::json& network)
  1370. {
  1371. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1372. auto tracer = provider->GetTracer("embedded_controller");
  1373. auto span = tracer->StartSpan("embedded_controller::onNetworkUpdate");
  1374. auto scope = tracer->WithActiveSpan(span);
  1375. // Send an update to all members of the network that are online
  1376. const int64_t now = OSUtils::now();
  1377. std::lock_guard<std::mutex> l(_memberStatus_l);
  1378. for (auto i = _memberStatus.begin(); i != _memberStatus.end(); ++i) {
  1379. if ((i->first.networkId == networkId) && (i->second.online(now)) && (i->second.lastRequestMetaData))
  1380. request(networkId, InetAddress(), 0, i->second.identity, i->second.lastRequestMetaData);
  1381. }
  1382. }
  1383. void EmbeddedNetworkController::onNetworkMemberUpdate(const void* db, uint64_t networkId, uint64_t memberId, const nlohmann::json& member)
  1384. {
  1385. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1386. auto tracer = provider->GetTracer("embedded_controller");
  1387. auto span = tracer->StartSpan("embedded_controller::onNetworkMemberUpdate");
  1388. auto scope = tracer->WithActiveSpan(span);
  1389. // Push update to member if online
  1390. try {
  1391. std::lock_guard<std::mutex> l(_memberStatus_l);
  1392. _MemberStatus& ms = _memberStatus[_MemberStatusKey(networkId, memberId)];
  1393. if ((ms.online(OSUtils::now())) && (ms.lastRequestMetaData))
  1394. request(networkId, InetAddress(), 0, ms.identity, ms.lastRequestMetaData);
  1395. }
  1396. catch (...) {
  1397. }
  1398. }
  1399. void EmbeddedNetworkController::onNetworkMemberDeauthorize(const void* db, uint64_t networkId, uint64_t memberId)
  1400. {
  1401. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1402. auto tracer = provider->GetTracer("embedded_controller");
  1403. auto span = tracer->StartSpan("embedded_controller::onNetworkMemberDeauthorize");
  1404. auto scope = tracer->WithActiveSpan(span);
  1405. const int64_t now = OSUtils::now();
  1406. Revocation rev((uint32_t)_node->prng(), networkId, 0, now, ZT_REVOCATION_FLAG_FAST_PROPAGATE, Address(memberId), Revocation::CREDENTIAL_TYPE_COM);
  1407. rev.sign(_signingId);
  1408. {
  1409. std::lock_guard<std::mutex> l(_memberStatus_l);
  1410. for (auto i = _memberStatus.begin(); i != _memberStatus.end(); ++i) {
  1411. if ((i->first.networkId == networkId) && (i->second.online(now)))
  1412. _node->ncSendRevocation(Address(i->first.nodeId), rev);
  1413. }
  1414. }
  1415. }
  1416. void EmbeddedNetworkController::_request(uint64_t nwid, const InetAddress& fromAddr, uint64_t requestPacketId, const Identity& identity, const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY>& metaData)
  1417. {
  1418. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  1419. auto tracer = provider->GetTracer("embedded_controller");
  1420. auto span = tracer->StartSpan("embedded_controller::_request");
  1421. auto scope = tracer->WithActiveSpan(span);
  1422. Metrics::network_config_request++;
  1423. auto tid = std::this_thread::get_id();
  1424. std::stringstream ss;
  1425. ss << tid;
  1426. std::string threadID = ss.str();
  1427. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1428. auto b1 = _member_status_lookup.Add({ { "thread", threadID } });
  1429. auto c1 = _member_status_lookup_count.Add({ { "thread", threadID } });
  1430. c1++;
  1431. b1.start();
  1432. #endif
  1433. char nwids[24];
  1434. DB::NetworkSummaryInfo ns;
  1435. json network, member;
  1436. if (((! _signingId) || (! _signingId.hasPrivate())) || (_signingId.address().toInt() != (nwid >> 24)) || (! _sender)) {
  1437. return;
  1438. }
  1439. const int64_t now = OSUtils::now();
  1440. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1441. b1.stop();
  1442. auto b2 = _node_is_online.Add({ { "thread", threadID } });
  1443. auto c2 = _node_is_online_count.Add({ { "thread", threadID } });
  1444. c2++;
  1445. b2.start();
  1446. #endif
  1447. char osArch[256];
  1448. metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_OS_ARCH, osArch, sizeof(osArch));
  1449. // fprintf(stderr, "Network Config Request: nwid=%.16llx, nodeid=%.10llx, osArch=%s\n",
  1450. // nwid, identity.address().toInt(), osArch);
  1451. _db.nodeIsOnline(nwid, identity.address().toInt(), fromAddr, osArch);
  1452. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1453. b2.stop();
  1454. auto b3 = _get_and_init_member.Add({ { "thread", threadID } });
  1455. auto c3 = _get_and_init_member_count.Add({ { "thread", threadID } });
  1456. c3++;
  1457. b3.start();
  1458. #endif
  1459. Utils::hex(nwid, nwids);
  1460. _db.get(nwid, network, identity.address().toInt(), member, ns);
  1461. if ((! network.is_object()) || (network.empty())) {
  1462. _sender->ncSendError(nwid, requestPacketId, identity.address(), NetworkController::NC_ERROR_OBJECT_NOT_FOUND, nullptr, 0);
  1463. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1464. b3.stop();
  1465. #endif
  1466. return;
  1467. }
  1468. const bool newMember = ((! member.is_object()) || (member.empty()));
  1469. DB::initMember(member);
  1470. _MemberStatusKey msk(nwid, identity.address().toInt());
  1471. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1472. b3.stop();
  1473. #endif
  1474. {
  1475. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1476. auto b4 = _have_identity.Add({ { "thread", threadID } });
  1477. auto c4 = _have_identity_count.Add({ { "thread", threadID } });
  1478. c4++;
  1479. b4.start();
  1480. #endif
  1481. const std::string haveIdStr(OSUtils::jsonString(member["identity"], ""));
  1482. if (haveIdStr.length() > 0) {
  1483. // If we already know this member's identity perform a full compare. This prevents
  1484. // a "collision" from being able to auth onto our network in place of an already
  1485. // known member.
  1486. try {
  1487. if (Identity(haveIdStr.c_str()) != identity) {
  1488. _sender->ncSendError(nwid, requestPacketId, identity.address(), NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1489. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1490. b4.stop();
  1491. #endif
  1492. return;
  1493. }
  1494. }
  1495. catch (...) {
  1496. _sender->ncSendError(nwid, requestPacketId, identity.address(), NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1497. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1498. b4.stop();
  1499. #endif
  1500. return;
  1501. }
  1502. }
  1503. else {
  1504. // If we do not yet know this member's identity, learn it.
  1505. char idtmp[1024];
  1506. member["identity"] = identity.toString(false, idtmp);
  1507. }
  1508. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1509. b4.stop();
  1510. #endif
  1511. }
  1512. // These are always the same, but make sure they are set
  1513. {
  1514. char tmpid[128];
  1515. const std::string addrs(identity.address().toString(tmpid));
  1516. member["id"] = addrs;
  1517. member["address"] = addrs;
  1518. member["nwid"] = nwids;
  1519. }
  1520. // Determine whether and how member is authorized
  1521. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1522. auto b5 = _determine_auth.Add({ { "thread", threadID } });
  1523. auto c5 = _determine_auth_count.Add({ { "thread", threadID } });
  1524. c5++;
  1525. b5.start();
  1526. #endif
  1527. bool authorized = false;
  1528. bool autoAuthorized = false;
  1529. json autoAuthCredentialType, autoAuthCredential;
  1530. if (OSUtils::jsonBool(member["authorized"], false)) {
  1531. authorized = true;
  1532. }
  1533. else if (! OSUtils::jsonBool(network["private"], true)) {
  1534. authorized = true;
  1535. autoAuthorized = true;
  1536. autoAuthCredentialType = "public";
  1537. }
  1538. else {
  1539. char presentedAuth[512];
  1540. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH, presentedAuth, sizeof(presentedAuth)) > 0) {
  1541. presentedAuth[511] = (char)0; // sanity check
  1542. if ((strlen(presentedAuth) > 6) && (! strncmp(presentedAuth, "token:", 6))) {
  1543. const char* const presentedToken = presentedAuth + 6;
  1544. json authTokens(network["authTokens"]);
  1545. json& tokenExpires = authTokens[presentedToken];
  1546. if (tokenExpires.is_number()) {
  1547. if ((tokenExpires == 0) || (tokenExpires > now)) {
  1548. authorized = true;
  1549. autoAuthorized = true;
  1550. autoAuthCredentialType = "token";
  1551. autoAuthCredential = presentedToken;
  1552. }
  1553. }
  1554. }
  1555. }
  1556. }
  1557. // If we auto-authorized, update member record
  1558. if ((autoAuthorized) && (authorized)) {
  1559. member["authorized"] = true;
  1560. member["lastAuthorizedTime"] = now;
  1561. member["lastAuthorizedCredentialType"] = autoAuthCredentialType;
  1562. member["lastAuthorizedCredential"] = autoAuthCredential;
  1563. }
  1564. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1565. b5.stop();
  1566. #endif
  1567. // Should we check SSO Stuff?
  1568. // If network is configured with SSO, and the member is not marked exempt: yes
  1569. // Otherwise no, we use standard auth logic.
  1570. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1571. auto b6 = _sso_check.Add({ { "thread", threadID } });
  1572. auto c6 = _sso_check_count.Add({ { "thread", threadID } });
  1573. c6++;
  1574. b6.start();
  1575. #endif
  1576. AuthInfo info;
  1577. int64_t authenticationExpiryTime = -1;
  1578. bool networkSSOEnabled = OSUtils::jsonBool(network["ssoEnabled"], false);
  1579. bool memberSSOExempt = OSUtils::jsonBool(member["ssoExempt"], false);
  1580. if (networkSSOEnabled && ! memberSSOExempt) {
  1581. authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1582. info = _db.getSSOAuthInfo(member, _ssoRedirectURL);
  1583. assert(info.enabled == networkSSOEnabled);
  1584. if (authenticationExpiryTime <= now) {
  1585. if (info.version == 0) {
  1586. Dictionary<4096> authInfo;
  1587. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, (uint64_t)0ULL);
  1588. authInfo.add(ZT_AUTHINFO_DICT_KEY_AUTHENTICATION_URL, info.authenticationURL.c_str());
  1589. _sender->ncSendError(nwid, requestPacketId, identity.address(), NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1590. }
  1591. else if (info.version == 1) {
  1592. Dictionary<8192> authInfo;
  1593. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, info.version);
  1594. authInfo.add(ZT_AUTHINFO_DICT_KEY_ISSUER_URL, info.issuerURL.c_str());
  1595. authInfo.add(ZT_AUTHINFO_DICT_KEY_CENTRAL_ENDPOINT_URL, info.centralAuthURL.c_str());
  1596. authInfo.add(ZT_AUTHINFO_DICT_KEY_NONCE, info.ssoNonce.c_str());
  1597. authInfo.add(ZT_AUTHINFO_DICT_KEY_STATE, info.ssoState.c_str());
  1598. authInfo.add(ZT_AUTHINFO_DICT_KEY_CLIENT_ID, info.ssoClientID.c_str());
  1599. authInfo.add(ZT_AUTHINFO_DICT_KEY_SSO_PROVIDER, info.ssoProvider.c_str());
  1600. _sender->ncSendError(nwid, requestPacketId, identity.address(), NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1601. }
  1602. DB::cleanMember(member);
  1603. _db.save(member, true);
  1604. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1605. b6.stop();
  1606. #endif
  1607. return;
  1608. }
  1609. }
  1610. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1611. b6.stop();
  1612. auto b7 = _auth_check.Add({ { "thread", threadID } });
  1613. auto c7 = _auth_check_count.Add({ { "thread", threadID } });
  1614. c7++;
  1615. b7.start();
  1616. #endif
  1617. if (authorized) {
  1618. // Update version info and meta-data if authorized and if this is a genuine request
  1619. if (requestPacketId) {
  1620. const uint64_t vMajor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION, 0);
  1621. const uint64_t vMinor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION, 0);
  1622. const uint64_t vRev = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION, 0);
  1623. const uint64_t vProto = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION, 0);
  1624. member["vMajor"] = vMajor;
  1625. member["vMinor"] = vMinor;
  1626. member["vRev"] = vRev;
  1627. member["vProto"] = vProto;
  1628. {
  1629. std::lock_guard<std::mutex> l(_memberStatus_l);
  1630. _MemberStatus& ms = _memberStatus[msk];
  1631. ms.authenticationExpiryTime = authenticationExpiryTime;
  1632. ms.vMajor = (int)vMajor;
  1633. ms.vMinor = (int)vMinor;
  1634. ms.vRev = (int)vRev;
  1635. ms.vProto = (int)vProto;
  1636. ms.lastRequestMetaData = metaData;
  1637. ms.identity = identity;
  1638. }
  1639. if (authenticationExpiryTime > 0) {
  1640. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1641. _expiringSoon.insert(std::pair<int64_t, _MemberStatusKey>(authenticationExpiryTime, msk));
  1642. }
  1643. }
  1644. }
  1645. else {
  1646. // If they are not authorized, STOP!
  1647. DB::cleanMember(member);
  1648. _db.save(member, true);
  1649. _sender->ncSendError(nwid, requestPacketId, identity.address(), NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1650. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1651. b7.stop();
  1652. #endif
  1653. return;
  1654. }
  1655. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1656. b7.stop();
  1657. #endif
  1658. // -------------------------------------------------------------------------
  1659. // If we made it this far, they are authorized (and authenticated).
  1660. // -------------------------------------------------------------------------
  1661. // Default timeout: 15 minutes. Maximum: two hours. Can be specified by an optional field in the network config
  1662. // if something longer than 15 minutes is desired. Minimum is 5 minutes since shorter than that would be flaky.
  1663. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  1664. auto b8 = _json_schlep.Add({ { "thread", threadID } });
  1665. auto c8 = _json_schlep_count.Add({ { "thread", threadID } });
  1666. c8++;
  1667. b8.start();
  1668. #endif
  1669. int64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_DFL_MAX_DELTA;
  1670. if (network.contains("certificateTimeoutWindowSize")) {
  1671. credentialtmd = (int64_t)network["certificateTimeoutWindowSize"];
  1672. }
  1673. credentialtmd = std::max(std::min(credentialtmd, ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA), ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA);
  1674. std::unique_ptr<NetworkConfig> nc(new NetworkConfig());
  1675. nc->networkId = nwid;
  1676. nc->type = OSUtils::jsonBool(network["private"], true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  1677. nc->timestamp = now;
  1678. nc->credentialTimeMaxDelta = credentialtmd;
  1679. nc->revision = OSUtils::jsonInt(network["revision"], 0ULL);
  1680. nc->issuedTo = identity.address();
  1681. if (OSUtils::jsonBool(network["enableBroadcast"], true))
  1682. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  1683. Utils::scopy(nc->name, sizeof(nc->name), OSUtils::jsonString(network["name"], "").c_str());
  1684. nc->mtu = std::max(std::min((unsigned int)OSUtils::jsonInt(network["mtu"], ZT_DEFAULT_MTU), (unsigned int)ZT_MAX_MTU), (unsigned int)ZT_MIN_MTU);
  1685. nc->multicastLimit = (unsigned int)OSUtils::jsonInt(network["multicastLimit"], 32ULL);
  1686. nc->ssoEnabled = networkSSOEnabled; // OSUtils::jsonBool(network["ssoEnabled"], false);
  1687. nc->ssoVersion = info.version;
  1688. if (info.version == 0) {
  1689. nc->authenticationExpiryTime = OSUtils::jsonInt(member["authenticationExpiryTime"], 0LL);
  1690. if (! info.authenticationURL.empty()) {
  1691. Utils::scopy(nc->authenticationURL, sizeof(nc->authenticationURL), info.authenticationURL.c_str());
  1692. }
  1693. }
  1694. else if (info.version == 1) {
  1695. nc->authenticationExpiryTime = OSUtils::jsonInt(member["authenticationExpiryTime"], 0LL);
  1696. if (! info.authenticationURL.empty()) {
  1697. Utils::scopy(nc->authenticationURL, sizeof(nc->authenticationURL), info.authenticationURL.c_str());
  1698. }
  1699. if (! info.centralAuthURL.empty()) {
  1700. Utils::scopy(nc->centralAuthURL, sizeof(nc->centralAuthURL), info.centralAuthURL.c_str());
  1701. }
  1702. if (! info.issuerURL.empty()) {
  1703. #ifdef ZT_DEBUG
  1704. fprintf(stderr, "copying issuerURL to nc: %s\n", info.issuerURL.c_str());
  1705. #endif
  1706. Utils::scopy(nc->issuerURL, sizeof(nc->issuerURL), info.issuerURL.c_str());
  1707. }
  1708. if (! info.ssoNonce.empty()) {
  1709. Utils::scopy(nc->ssoNonce, sizeof(nc->ssoNonce), info.ssoNonce.c_str());
  1710. }
  1711. if (! info.ssoState.empty()) {
  1712. Utils::scopy(nc->ssoState, sizeof(nc->ssoState), info.ssoState.c_str());
  1713. }
  1714. if (! info.ssoClientID.empty()) {
  1715. Utils::scopy(nc->ssoClientID, sizeof(nc->ssoClientID), info.ssoClientID.c_str());
  1716. }
  1717. }
  1718. std::string rtt(OSUtils::jsonString(member["remoteTraceTarget"], ""));
  1719. if (rtt.length() == 10) {
  1720. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1721. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(member["remoteTraceLevel"], 0ULL);
  1722. }
  1723. else {
  1724. rtt = OSUtils::jsonString(network["remoteTraceTarget"], "");
  1725. if (rtt.length() == 10) {
  1726. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1727. }
  1728. else {
  1729. nc->remoteTraceTarget.zero();
  1730. }
  1731. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(network["remoteTraceLevel"], 0ULL);
  1732. }
  1733. for (std::vector<Address>::const_iterator ab(ns.activeBridges.begin()); ab != ns.activeBridges.end(); ++ab) {
  1734. nc->addSpecialist(*ab, ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1735. }
  1736. json& v4AssignMode = network["v4AssignMode"];
  1737. json& v6AssignMode = network["v6AssignMode"];
  1738. json& ipAssignmentPools = network["ipAssignmentPools"];
  1739. json& routes = network["routes"];
  1740. json& relays = network["relays"];
  1741. json& rules = network["rules"];
  1742. json& capabilities = network["capabilities"];
  1743. json& tags = network["tags"];
  1744. json& memberCapabilities = member["capabilities"];
  1745. json& memberTags = member["tags"];
  1746. json& dns = network["dns"];
  1747. // fprintf(stderr, "IP Assignment Pools for Network %s: %s\n", nwids, OSUtils::jsonDump(ipAssignmentPools, 2).c_str());
  1748. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV, 0) <= 0) {
  1749. // Old versions with no rules engine support get an allow everything rule.
  1750. // Since rules are enforced bidirectionally, newer versions *will* still
  1751. // enforce rules on the inbound side.
  1752. nc->ruleCount = 1;
  1753. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1754. }
  1755. else {
  1756. if (rules.is_array()) {
  1757. for (unsigned long i = 0; i < rules.size(); ++i) {
  1758. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1759. break;
  1760. if (_parseRule(rules[i], nc->rules[nc->ruleCount]))
  1761. ++nc->ruleCount;
  1762. }
  1763. }
  1764. std::map<uint64_t, json*> capsById;
  1765. if (! memberCapabilities.is_array())
  1766. memberCapabilities = json::array();
  1767. if (capabilities.is_array()) {
  1768. for (unsigned long i = 0; i < capabilities.size(); ++i) {
  1769. json& cap = capabilities[i];
  1770. if (cap.is_object()) {
  1771. const uint64_t id = OSUtils::jsonInt(cap["id"], 0ULL) & 0xffffffffULL;
  1772. capsById[id] = &cap;
  1773. if ((newMember) && (OSUtils::jsonBool(cap["default"], false))) {
  1774. bool have = false;
  1775. for (unsigned long i = 0; i < memberCapabilities.size(); ++i) {
  1776. if (id == (OSUtils::jsonInt(memberCapabilities[i], 0ULL) & 0xffffffffULL)) {
  1777. have = true;
  1778. break;
  1779. }
  1780. }
  1781. if (! have)
  1782. memberCapabilities.push_back(id);
  1783. }
  1784. }
  1785. }
  1786. }
  1787. for (unsigned long i = 0; i < memberCapabilities.size(); ++i) {
  1788. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i], 0ULL) & 0xffffffffULL;
  1789. std::map<uint64_t, json*>::const_iterator ctmp = capsById.find(capId);
  1790. if (ctmp != capsById.end()) {
  1791. json* cap = ctmp->second;
  1792. if ((cap) && (cap->is_object()) && (! cap->empty())) {
  1793. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1794. unsigned int caprc = 0;
  1795. json& caprj = (*cap)["rules"];
  1796. if ((caprj.is_array()) && (! caprj.empty())) {
  1797. for (unsigned long j = 0; j < caprj.size(); ++j) {
  1798. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1799. break;
  1800. if (_parseRule(caprj[j], capr[caprc]))
  1801. ++caprc;
  1802. }
  1803. }
  1804. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId, nwid, now, 1, capr, caprc);
  1805. if (nc->capabilities[nc->capabilityCount].sign(_signingId, identity.address()))
  1806. ++nc->capabilityCount;
  1807. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1808. break;
  1809. }
  1810. }
  1811. }
  1812. std::map<uint32_t, uint32_t> memberTagsById;
  1813. if (memberTags.is_array()) {
  1814. for (unsigned long i = 0; i < memberTags.size(); ++i) {
  1815. json& t = memberTags[i];
  1816. if ((t.is_array()) && (t.size() == 2))
  1817. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0], 0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1], 0ULL) & 0xffffffffULL);
  1818. }
  1819. }
  1820. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1821. for (unsigned long i = 0; i < tags.size(); ++i) {
  1822. json& t = tags[i];
  1823. if (t.is_object()) {
  1824. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"], 0) & 0xffffffffULL);
  1825. json& dfl = t["default"];
  1826. if ((dfl.is_number()) && (memberTagsById.find(id) == memberTagsById.end())) {
  1827. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl, 0) & 0xffffffffULL);
  1828. json mt = json::array();
  1829. mt.push_back(id);
  1830. mt.push_back(dfl);
  1831. memberTags.push_back(mt); // add default to member tags if not present
  1832. }
  1833. }
  1834. }
  1835. }
  1836. for (std::map<uint32_t, uint32_t>::const_iterator t(memberTagsById.begin()); t != memberTagsById.end(); ++t) {
  1837. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1838. break;
  1839. nc->tags[nc->tagCount] = Tag(nwid, now, identity.address(), t->first, t->second);
  1840. if (nc->tags[nc->tagCount].sign(_signingId))
  1841. ++nc->tagCount;
  1842. }
  1843. }
  1844. if (routes.is_array()) {
  1845. for (unsigned long i = 0; i < routes.size(); ++i) {
  1846. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1847. break;
  1848. json& route = routes[i];
  1849. json& target = route["target"];
  1850. json& via = route["via"];
  1851. if (target.is_string()) {
  1852. const InetAddress t(target.get<std::string>().c_str());
  1853. InetAddress v;
  1854. if (via.is_string())
  1855. v.fromString(via.get<std::string>().c_str());
  1856. if ((t.ss_family == AF_INET) || (t.ss_family == AF_INET6)) {
  1857. ZT_VirtualNetworkRoute* r = &(nc->routes[nc->routeCount]);
  1858. *(reinterpret_cast<InetAddress*>(&(r->target))) = t;
  1859. if (v.ss_family == t.ss_family)
  1860. *(reinterpret_cast<InetAddress*>(&(r->via))) = v;
  1861. ++nc->routeCount;
  1862. }
  1863. }
  1864. }
  1865. }
  1866. if (relays.is_array()) {
  1867. for (unsigned long i = 0; i < relays.size(); ++i) {
  1868. Address relay(Address(Utils::hexStrToU64(OSUtils::jsonString(relays[i], "0").c_str()) & 0xffffffffffULL));
  1869. if (! relay.isReserved()) {
  1870. nc->addSpecialist(relay, ZT_NETWORKCONFIG_SPECIALIST_TYPE_NETWORK_RELAY);
  1871. }
  1872. }
  1873. }
  1874. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"], false);
  1875. if ((v6AssignMode.is_object()) && (! noAutoAssignIps)) {
  1876. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"], false)) && (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1877. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid, identity.address().toInt());
  1878. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1879. }
  1880. if ((OSUtils::jsonBool(v6AssignMode["6plane"], false)) && (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1881. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid, identity.address().toInt());
  1882. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1883. }
  1884. }
  1885. bool haveManagedIpv4AutoAssignment = false;
  1886. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1887. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1888. if (ipAssignments.is_array()) {
  1889. for (unsigned long i = 0; i < ipAssignments.size(); ++i) {
  1890. if (ipAssignments[i].is_string()) {
  1891. const std::string ips = ipAssignments[i];
  1892. InetAddress ip(ips.c_str());
  1893. int routedNetmaskBits = -1;
  1894. for (unsigned int rk = 0; rk < nc->routeCount; ++rk) {
  1895. if (reinterpret_cast<const InetAddress*>(&(nc->routes[rk].target))->containsAddress(ip)) {
  1896. const int nb = (int)(reinterpret_cast<const InetAddress*>(&(nc->routes[rk].target))->netmaskBits());
  1897. if (nb > routedNetmaskBits)
  1898. routedNetmaskBits = nb;
  1899. }
  1900. }
  1901. if (routedNetmaskBits >= 0) {
  1902. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1903. ip.setPort(routedNetmaskBits);
  1904. nc->staticIps[nc->staticIpCount++] = ip;
  1905. }
  1906. if (ip.ss_family == AF_INET)
  1907. haveManagedIpv4AutoAssignment = true;
  1908. else if (ip.ss_family == AF_INET6)
  1909. haveManagedIpv6AutoAssignment = true;
  1910. }
  1911. }
  1912. }
  1913. }
  1914. else {
  1915. ipAssignments = json::array();
  1916. }
  1917. if ((ipAssignmentPools.is_array()) && ((v6AssignMode.is_object()) && (OSUtils::jsonBool(v6AssignMode["zt"], false))) && (! haveManagedIpv6AutoAssignment) && (! noAutoAssignIps)) {
  1918. for (unsigned long p = 0; ((p < ipAssignmentPools.size()) && (! haveManagedIpv6AutoAssignment)); ++p) {
  1919. json& pool = ipAssignmentPools[p];
  1920. if (pool.is_object()) {
  1921. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"], "").c_str());
  1922. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"], "").c_str());
  1923. if ((ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6)) {
  1924. uint64_t s[2], e[2], x[2], xx[2];
  1925. memcpy(s, ipRangeStart.rawIpData(), 16);
  1926. memcpy(e, ipRangeEnd.rawIpData(), 16);
  1927. s[0] = Utils::ntoh(s[0]);
  1928. s[1] = Utils::ntoh(s[1]);
  1929. e[0] = Utils::ntoh(e[0]);
  1930. e[1] = Utils::ntoh(e[1]);
  1931. x[0] = s[0];
  1932. x[1] = s[1];
  1933. for (unsigned int trialCount = 0; trialCount < 1000; ++trialCount) {
  1934. if ((trialCount == 0) && (e[1] > s[1]) && ((e[1] - s[1]) >= 0xffffffffffULL)) {
  1935. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1936. xx[0] = Utils::hton(x[0]);
  1937. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1938. }
  1939. else {
  1940. // Otherwise pick random addresses -- this technically doesn't explore the whole range if the lower 64 bit range is >= 1 but that won't matter since that would be huge anyway
  1941. Utils::getSecureRandom((void*)xx, 16);
  1942. if ((e[0] > s[0]))
  1943. xx[0] %= (e[0] - s[0]);
  1944. else
  1945. xx[0] = 0;
  1946. if ((e[1] > s[1]))
  1947. xx[1] %= (e[1] - s[1]);
  1948. else
  1949. xx[1] = 0;
  1950. xx[0] = Utils::hton(x[0] + xx[0]);
  1951. xx[1] = Utils::hton(x[1] + xx[1]);
  1952. }
  1953. InetAddress ip6((const void*)xx, 16, 0);
  1954. // Check if this IP is within a local-to-Ethernet routed network
  1955. int routedNetmaskBits = 0;
  1956. for (unsigned int rk = 0; rk < nc->routeCount; ++rk) {
  1957. if ((! nc->routes[rk].via.ss_family) && (nc->routes[rk].target.ss_family == AF_INET6) && (reinterpret_cast<const InetAddress*>(&(nc->routes[rk].target))->containsAddress(ip6)))
  1958. routedNetmaskBits = reinterpret_cast<const InetAddress*>(&(nc->routes[rk].target))->netmaskBits();
  1959. }
  1960. // If it's routed, then try to claim and assign it and if successful end loop
  1961. if ((routedNetmaskBits > 0) && (! std::binary_search(ns.allocatedIps.begin(), ns.allocatedIps.end(), ip6))) {
  1962. char tmpip[64];
  1963. const std::string ipStr(ip6.toIpString(tmpip));
  1964. if (std::find(ipAssignments.begin(), ipAssignments.end(), ipStr) == ipAssignments.end()) {
  1965. ipAssignments.push_back(ipStr);
  1966. member["ipAssignments"] = ipAssignments;
  1967. ip6.setPort((unsigned int)routedNetmaskBits);
  1968. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1969. nc->staticIps[nc->staticIpCount++] = ip6;
  1970. haveManagedIpv6AutoAssignment = true;
  1971. break;
  1972. }
  1973. }
  1974. }
  1975. }
  1976. }
  1977. }
  1978. }
  1979. if ((ipAssignmentPools.is_array()) && ((v4AssignMode.is_object()) && (OSUtils::jsonBool(v4AssignMode["zt"], false))) && (! haveManagedIpv4AutoAssignment) && (! noAutoAssignIps)) {
  1980. for (unsigned long p = 0; ((p < ipAssignmentPools.size()) && (! haveManagedIpv4AutoAssignment)); ++p) {
  1981. json& pool = ipAssignmentPools[p];
  1982. if (pool.is_object()) {
  1983. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"], "").c_str());
  1984. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"], "").c_str());
  1985. if ((ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET)) {
  1986. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in*>(&ipRangeStartIA)->sin_addr.s_addr));
  1987. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in*>(&ipRangeEndIA)->sin_addr.s_addr));
  1988. if ((ipRangeEnd < ipRangeStart) || (ipRangeStart == 0))
  1989. continue;
  1990. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1991. // Start with the LSB of the member's address
  1992. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1993. for (uint32_t k = ipRangeStart, trialCount = 0; ((k <= ipRangeEnd) && (trialCount < 1000)); ++k, ++trialCount) {
  1994. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1995. ++ipTrialCounter;
  1996. if ((ip & 0x000000ff) == 0x000000ff) {
  1997. continue; // don't allow addresses that end in .255
  1998. }
  1999. // Check if this IP is within a local-to-Ethernet routed network
  2000. int routedNetmaskBits = -1;
  2001. for (unsigned int rk = 0; rk < nc->routeCount; ++rk) {
  2002. if (nc->routes[rk].target.ss_family == AF_INET) {
  2003. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in*>(&(nc->routes[rk].target))->sin_addr.s_addr));
  2004. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in*>(&(nc->routes[rk].target))->sin_port));
  2005. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  2006. routedNetmaskBits = targetBits;
  2007. break;
  2008. }
  2009. }
  2010. }
  2011. // If it's routed, then try to claim and assign it and if successful end loop
  2012. const InetAddress ip4(Utils::hton(ip), 0);
  2013. if ((routedNetmaskBits > 0) && (! std::binary_search(ns.allocatedIps.begin(), ns.allocatedIps.end(), ip4))) {
  2014. char tmpip[64];
  2015. const std::string ipStr(ip4.toIpString(tmpip));
  2016. if (std::find(ipAssignments.begin(), ipAssignments.end(), ipStr) == ipAssignments.end()) {
  2017. ipAssignments.push_back(ipStr);
  2018. member["ipAssignments"] = ipAssignments;
  2019. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  2020. struct sockaddr_in* const v4ip = reinterpret_cast<struct sockaddr_in*>(&(nc->staticIps[nc->staticIpCount++]));
  2021. v4ip->sin_family = AF_INET;
  2022. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  2023. v4ip->sin_addr.s_addr = Utils::hton(ip);
  2024. }
  2025. haveManagedIpv4AutoAssignment = true;
  2026. break;
  2027. }
  2028. }
  2029. }
  2030. }
  2031. }
  2032. }
  2033. }
  2034. if (dns.is_object()) {
  2035. std::string domain = OSUtils::jsonString(dns["domain"], "");
  2036. memcpy(nc->dns.domain, domain.c_str(), domain.size());
  2037. json& addrArray = dns["servers"];
  2038. if (addrArray.is_array()) {
  2039. for (unsigned int j = 0; j < addrArray.size() && j < ZT_MAX_DNS_SERVERS; ++j) {
  2040. json& addr = addrArray[j];
  2041. nc->dns.server_addr[j] = InetAddress(OSUtils::jsonString(addr, "").c_str());
  2042. }
  2043. }
  2044. }
  2045. else {
  2046. dns = json::object();
  2047. }
  2048. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  2049. b8.stop();
  2050. #endif
  2051. // Issue a certificate of ownership for all static IPs
  2052. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  2053. auto b9 = _issue_certificate.Add({ { "thread", threadID } });
  2054. auto c9 = _issue_certificate_count.Add({ { "thread", threadID } });
  2055. c9++;
  2056. b9.start();
  2057. #endif
  2058. if (nc->staticIpCount) {
  2059. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid, now, identity.address(), 1);
  2060. for (unsigned int i = 0; i < nc->staticIpCount; ++i) {
  2061. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  2062. }
  2063. nc->certificatesOfOwnership[0].sign(_signingId);
  2064. nc->certificateOfOwnershipCount = 1;
  2065. }
  2066. CertificateOfMembership com(now, credentialtmd, nwid, identity);
  2067. if (com.sign(_signingId)) {
  2068. nc->com = com;
  2069. }
  2070. else {
  2071. _sender->ncSendError(nwid, requestPacketId, identity.address(), NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR, nullptr, 0);
  2072. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  2073. b9.stop();
  2074. #endif
  2075. return;
  2076. }
  2077. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  2078. b9.stop();
  2079. auto b10 = _save_member.Add({ { "thread", threadID } });
  2080. auto c10 = _save_member_count.Add({ { "thread", threadID } });
  2081. c10++;
  2082. b10.start();
  2083. #endif
  2084. DB::cleanMember(member);
  2085. _db.save(member, true);
  2086. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  2087. b10.stop();
  2088. auto b11 = _send_netconf.Add({ { "thread", threadID } });
  2089. auto c11 = _send_netconf_count.Add({ { "thread", threadID } });
  2090. c11++;
  2091. b11.start();
  2092. #endif
  2093. _sender->ncSendConfig(nwid, requestPacketId, identity.address(), *(nc.get()), metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION, 0) < 6);
  2094. #ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
  2095. b11.stop();
  2096. #endif
  2097. }
  2098. void EmbeddedNetworkController::_startThreads()
  2099. {
  2100. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  2101. auto tracer = provider->GetTracer("embedded_network_controller");
  2102. auto span = tracer->StartSpan("embedded_network_controller::_startThreads");
  2103. auto scope = tracer->WithActiveSpan(span);
  2104. std::lock_guard<std::mutex> l(_threads_l);
  2105. if (! _threads.empty()) {
  2106. return;
  2107. }
  2108. const long hwc = std::max((long)std::thread::hardware_concurrency(), (long)1);
  2109. for (long t = 0; t < hwc; ++t) {
  2110. _threads.emplace_back([this]() {
  2111. Metrics::network_config_request_threads++;
  2112. for (;;) {
  2113. _RQEntry* qe = (_RQEntry*)0;
  2114. Metrics::network_config_request_queue_size = _queue.size();
  2115. auto timedWaitResult = _queue.get(qe, 1000);
  2116. if (timedWaitResult == BlockingQueue<_RQEntry*>::STOP) {
  2117. break;
  2118. }
  2119. else if (timedWaitResult == BlockingQueue<_RQEntry*>::OK) {
  2120. if (qe) {
  2121. try {
  2122. _request(qe->nwid, qe->fromAddr, qe->requestPacketId, qe->identity, qe->metaData);
  2123. }
  2124. catch (std::exception& e) {
  2125. fprintf(stderr, "ERROR: exception in controller request handling thread: %s" ZT_EOL_S, e.what());
  2126. }
  2127. catch (...) {
  2128. fprintf(stderr, "ERROR: exception in controller request handling thread: unknown exception" ZT_EOL_S);
  2129. }
  2130. delete qe;
  2131. qe = nullptr;
  2132. }
  2133. }
  2134. }
  2135. Metrics::network_config_request_threads--;
  2136. });
  2137. }
  2138. }
  2139. void EmbeddedNetworkController::_ssoExpiryThread()
  2140. {
  2141. while (_ssoExpiryRunning) {
  2142. auto provider = opentelemetry::trace::Provider::GetTracerProvider();
  2143. auto tracer = provider->GetTracer("embedded_network_controller");
  2144. auto span = tracer->StartSpan("embedded_network_controller::_ssoExpiryThread");
  2145. auto scope = tracer->WithActiveSpan(span);
  2146. std::vector<_MemberStatusKey> expired;
  2147. nlohmann::json network, member;
  2148. int64_t now = OSUtils::now();
  2149. {
  2150. std::lock_guard<std::mutex> l(_expiringSoon_l);
  2151. for (auto s = _expiringSoon.begin(); s != _expiringSoon.end();) {
  2152. Metrics::sso_expiration_checks++;
  2153. const int64_t when = s->first;
  2154. if (when <= now) {
  2155. // The user may have re-authorized, so we must actually look it up and check.
  2156. network.clear();
  2157. member.clear();
  2158. if (_db.get(s->second.networkId, network, s->second.nodeId, member)) {
  2159. int64_t authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  2160. if (authenticationExpiryTime <= now) {
  2161. expired.push_back(s->second);
  2162. }
  2163. }
  2164. s = _expiringSoon.erase(s);
  2165. }
  2166. else {
  2167. // Don't bother going further into the future than necessary.
  2168. break;
  2169. }
  2170. }
  2171. }
  2172. for (auto e = expired.begin(); e != expired.end(); ++e) {
  2173. Metrics::sso_member_deauth++;
  2174. onNetworkMemberDeauthorize(nullptr, e->networkId, e->nodeId);
  2175. }
  2176. span->End();
  2177. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2178. }
  2179. }
  2180. } // namespace ZeroTier