2
0

EmbeddedNetworkController.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdint.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <time.h>
  18. #ifndef _WIN32
  19. #include <sys/time.h>
  20. #endif
  21. #include <sys/types.h>
  22. #include <algorithm>
  23. #include <utility>
  24. #include <stdexcept>
  25. #include <map>
  26. #include <thread>
  27. #include <memory>
  28. #include <iomanip>
  29. #include <sstream>
  30. #include <cctype>
  31. #include "../include/ZeroTierOne.h"
  32. #include "../version.h"
  33. #include "EmbeddedNetworkController.hpp"
  34. #include "LFDB.hpp"
  35. #include "FileDB.hpp"
  36. #ifdef ZT_CONTROLLER_USE_LIBPQ
  37. #include "PostgreSQL.hpp"
  38. #endif
  39. #include "../node/Node.hpp"
  40. #include "../node/CertificateOfMembership.hpp"
  41. #include "../node/NetworkConfig.hpp"
  42. #include "../node/Dictionary.hpp"
  43. #include "../node/MAC.hpp"
  44. using json = nlohmann::json;
  45. // API version reported via JSON control plane
  46. #define ZT_NETCONF_CONTROLLER_API_VERSION 4
  47. // Min duration between requests for an address/nwid combo to prevent floods
  48. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  49. // Global maximum size of arrays in JSON objects
  50. #define ZT_CONTROLLER_MAX_ARRAY_SIZE 16384
  51. namespace ZeroTier {
  52. namespace {
  53. static json _renderRule(ZT_VirtualNetworkRule &rule)
  54. {
  55. char tmp[128];
  56. json r = json::object();
  57. const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rule.t & 0x3f);
  58. switch(rt) {
  59. case ZT_NETWORK_RULE_ACTION_DROP:
  60. r["type"] = "ACTION_DROP";
  61. break;
  62. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  63. r["type"] = "ACTION_ACCEPT";
  64. break;
  65. case ZT_NETWORK_RULE_ACTION_TEE:
  66. r["type"] = "ACTION_TEE";
  67. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  68. r["flags"] = (unsigned int)rule.v.fwd.flags;
  69. r["length"] = (unsigned int)rule.v.fwd.length;
  70. break;
  71. case ZT_NETWORK_RULE_ACTION_WATCH:
  72. r["type"] = "ACTION_WATCH";
  73. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  74. r["flags"] = (unsigned int)rule.v.fwd.flags;
  75. r["length"] = (unsigned int)rule.v.fwd.length;
  76. break;
  77. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  78. r["type"] = "ACTION_REDIRECT";
  79. r["address"] = Address(rule.v.fwd.address).toString(tmp);
  80. r["flags"] = (unsigned int)rule.v.fwd.flags;
  81. break;
  82. case ZT_NETWORK_RULE_ACTION_BREAK:
  83. r["type"] = "ACTION_BREAK";
  84. break;
  85. default:
  86. break;
  87. }
  88. if (r.empty()) {
  89. switch(rt) {
  90. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  91. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  92. r["zt"] = Address(rule.v.zt).toString(tmp);
  93. break;
  94. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  95. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  96. r["zt"] = Address(rule.v.zt).toString(tmp);
  97. break;
  98. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  99. r["type"] = "MATCH_VLAN_ID";
  100. r["vlanId"] = (unsigned int)rule.v.vlanId;
  101. break;
  102. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  103. r["type"] = "MATCH_VLAN_PCP";
  104. r["vlanPcp"] = (unsigned int)rule.v.vlanPcp;
  105. break;
  106. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  107. r["type"] = "MATCH_VLAN_DEI";
  108. r["vlanDei"] = (unsigned int)rule.v.vlanDei;
  109. break;
  110. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  111. r["type"] = "MATCH_MAC_SOURCE";
  112. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  113. r["mac"] = tmp;
  114. break;
  115. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  116. r["type"] = "MATCH_MAC_DEST";
  117. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(unsigned int)rule.v.mac[0],(unsigned int)rule.v.mac[1],(unsigned int)rule.v.mac[2],(unsigned int)rule.v.mac[3],(unsigned int)rule.v.mac[4],(unsigned int)rule.v.mac[5]);
  118. r["mac"] = tmp;
  119. break;
  120. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  121. r["type"] = "MATCH_IPV4_SOURCE";
  122. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString(tmp);
  123. break;
  124. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  125. r["type"] = "MATCH_IPV4_DEST";
  126. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString(tmp);
  127. break;
  128. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  129. r["type"] = "MATCH_IPV6_SOURCE";
  130. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString(tmp);
  131. break;
  132. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  133. r["type"] = "MATCH_IPV6_DEST";
  134. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString(tmp);
  135. break;
  136. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  137. r["type"] = "MATCH_IP_TOS";
  138. r["mask"] = (unsigned int)rule.v.ipTos.mask;
  139. r["start"] = (unsigned int)rule.v.ipTos.value[0];
  140. r["end"] = (unsigned int)rule.v.ipTos.value[1];
  141. break;
  142. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  143. r["type"] = "MATCH_IP_PROTOCOL";
  144. r["ipProtocol"] = (unsigned int)rule.v.ipProtocol;
  145. break;
  146. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  147. r["type"] = "MATCH_ETHERTYPE";
  148. r["etherType"] = (unsigned int)rule.v.etherType;
  149. break;
  150. case ZT_NETWORK_RULE_MATCH_ICMP:
  151. r["type"] = "MATCH_ICMP";
  152. r["icmpType"] = (unsigned int)rule.v.icmp.type;
  153. if ((rule.v.icmp.flags & 0x01) != 0)
  154. r["icmpCode"] = (unsigned int)rule.v.icmp.code;
  155. else r["icmpCode"] = json();
  156. break;
  157. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  158. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  159. r["start"] = (unsigned int)rule.v.port[0];
  160. r["end"] = (unsigned int)rule.v.port[1];
  161. break;
  162. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  163. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  164. r["start"] = (unsigned int)rule.v.port[0];
  165. r["end"] = (unsigned int)rule.v.port[1];
  166. break;
  167. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  168. r["type"] = "MATCH_CHARACTERISTICS";
  169. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics);
  170. r["mask"] = tmp;
  171. break;
  172. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  173. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  174. r["start"] = (unsigned int)rule.v.frameSize[0];
  175. r["end"] = (unsigned int)rule.v.frameSize[1];
  176. break;
  177. case ZT_NETWORK_RULE_MATCH_RANDOM:
  178. r["type"] = "MATCH_RANDOM";
  179. r["probability"] = (unsigned long)rule.v.randomProbability;
  180. break;
  181. case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
  182. r["type"] = "MATCH_TAGS_DIFFERENCE";
  183. r["id"] = rule.v.tag.id;
  184. r["value"] = rule.v.tag.value;
  185. break;
  186. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  187. r["type"] = "MATCH_TAGS_BITWISE_AND";
  188. r["id"] = rule.v.tag.id;
  189. r["value"] = rule.v.tag.value;
  190. break;
  191. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  192. r["type"] = "MATCH_TAGS_BITWISE_OR";
  193. r["id"] = rule.v.tag.id;
  194. r["value"] = rule.v.tag.value;
  195. break;
  196. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  197. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  198. r["id"] = rule.v.tag.id;
  199. r["value"] = rule.v.tag.value;
  200. break;
  201. case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL:
  202. r["type"] = "MATCH_TAGS_EQUAL";
  203. r["id"] = rule.v.tag.id;
  204. r["value"] = rule.v.tag.value;
  205. break;
  206. case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
  207. r["type"] = "MATCH_TAG_SENDER";
  208. r["id"] = rule.v.tag.id;
  209. r["value"] = rule.v.tag.value;
  210. break;
  211. case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER:
  212. r["type"] = "MATCH_TAG_RECEIVER";
  213. r["id"] = rule.v.tag.id;
  214. r["value"] = rule.v.tag.value;
  215. break;
  216. case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE:
  217. r["type"] = "INTEGER_RANGE";
  218. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start);
  219. r["start"] = tmp;
  220. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%.16llx",rule.v.intRange.start + (uint64_t)rule.v.intRange.end);
  221. r["end"] = tmp;
  222. r["idx"] = rule.v.intRange.idx;
  223. r["little"] = ((rule.v.intRange.format & 0x80) != 0);
  224. r["bits"] = (rule.v.intRange.format & 63) + 1;
  225. break;
  226. default:
  227. break;
  228. }
  229. if (!r.empty()) {
  230. r["not"] = ((rule.t & 0x80) != 0);
  231. r["or"] = ((rule.t & 0x40) != 0);
  232. }
  233. }
  234. return r;
  235. }
  236. static bool _parseRule(json &r,ZT_VirtualNetworkRule &rule)
  237. {
  238. if (!r.is_object())
  239. return false;
  240. const std::string t(OSUtils::jsonString(r["type"],""));
  241. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  242. if (OSUtils::jsonBool(r["not"],false))
  243. rule.t = 0x80;
  244. else rule.t = 0x00;
  245. if (OSUtils::jsonBool(r["or"],false))
  246. rule.t |= 0x40;
  247. bool tag = false;
  248. if (t == "ACTION_DROP") {
  249. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  250. return true;
  251. } else if (t == "ACTION_ACCEPT") {
  252. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  253. return true;
  254. } else if (t == "ACTION_TEE") {
  255. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  256. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  257. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  258. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  259. return true;
  260. } else if (t == "ACTION_WATCH") {
  261. rule.t |= ZT_NETWORK_RULE_ACTION_WATCH;
  262. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  263. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  264. rule.v.fwd.length = (uint16_t)(OSUtils::jsonInt(r["length"],0ULL) & 0xffffULL);
  265. return true;
  266. } else if (t == "ACTION_REDIRECT") {
  267. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  268. rule.v.fwd.address = Utils::hexStrToU64(OSUtils::jsonString(r["address"],"0").c_str()) & 0xffffffffffULL;
  269. rule.v.fwd.flags = (uint32_t)(OSUtils::jsonInt(r["flags"],0ULL) & 0xffffffffULL);
  270. return true;
  271. } else if (t == "ACTION_BREAK") {
  272. rule.t |= ZT_NETWORK_RULE_ACTION_BREAK;
  273. return true;
  274. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  275. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  276. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  277. return true;
  278. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  279. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  280. rule.v.zt = Utils::hexStrToU64(OSUtils::jsonString(r["zt"],"0").c_str()) & 0xffffffffffULL;
  281. return true;
  282. } else if (t == "MATCH_VLAN_ID") {
  283. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  284. rule.v.vlanId = (uint16_t)(OSUtils::jsonInt(r["vlanId"],0ULL) & 0xffffULL);
  285. return true;
  286. } else if (t == "MATCH_VLAN_PCP") {
  287. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  288. rule.v.vlanPcp = (uint8_t)(OSUtils::jsonInt(r["vlanPcp"],0ULL) & 0xffULL);
  289. return true;
  290. } else if (t == "MATCH_VLAN_DEI") {
  291. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  292. rule.v.vlanDei = (uint8_t)(OSUtils::jsonInt(r["vlanDei"],0ULL) & 0xffULL);
  293. return true;
  294. } else if (t == "MATCH_MAC_SOURCE") {
  295. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  296. const std::string mac(OSUtils::jsonString(r["mac"],"0"));
  297. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  298. return true;
  299. } else if (t == "MATCH_MAC_DEST") {
  300. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  301. const std::string mac(OSUtils::jsonString(r["mac"],"0"));
  302. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  303. return true;
  304. } else if (t == "MATCH_IPV4_SOURCE") {
  305. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  306. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  307. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  308. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  309. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  310. return true;
  311. } else if (t == "MATCH_IPV4_DEST") {
  312. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  313. InetAddress ip(OSUtils::jsonString(r["ip"],"0.0.0.0").c_str());
  314. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  315. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  316. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  317. return true;
  318. } else if (t == "MATCH_IPV6_SOURCE") {
  319. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  320. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  321. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  322. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  323. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  324. return true;
  325. } else if (t == "MATCH_IPV6_DEST") {
  326. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  327. InetAddress ip(OSUtils::jsonString(r["ip"],"::0").c_str());
  328. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  329. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  330. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  331. return true;
  332. } else if (t == "MATCH_IP_TOS") {
  333. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  334. rule.v.ipTos.mask = (uint8_t)(OSUtils::jsonInt(r["mask"],0ULL) & 0xffULL);
  335. rule.v.ipTos.value[0] = (uint8_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffULL);
  336. rule.v.ipTos.value[1] = (uint8_t)(OSUtils::jsonInt(r["end"],0ULL) & 0xffULL);
  337. return true;
  338. } else if (t == "MATCH_IP_PROTOCOL") {
  339. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  340. rule.v.ipProtocol = (uint8_t)(OSUtils::jsonInt(r["ipProtocol"],0ULL) & 0xffULL);
  341. return true;
  342. } else if (t == "MATCH_ETHERTYPE") {
  343. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  344. rule.v.etherType = (uint16_t)(OSUtils::jsonInt(r["etherType"],0ULL) & 0xffffULL);
  345. return true;
  346. } else if (t == "MATCH_ICMP") {
  347. rule.t |= ZT_NETWORK_RULE_MATCH_ICMP;
  348. rule.v.icmp.type = (uint8_t)(OSUtils::jsonInt(r["icmpType"],0ULL) & 0xffULL);
  349. json &code = r["icmpCode"];
  350. if (code.is_null()) {
  351. rule.v.icmp.code = 0;
  352. rule.v.icmp.flags = 0x00;
  353. } else {
  354. rule.v.icmp.code = (uint8_t)(OSUtils::jsonInt(code,0ULL) & 0xffULL);
  355. rule.v.icmp.flags = 0x01;
  356. }
  357. return true;
  358. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  359. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  360. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  361. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  362. return true;
  363. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  364. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  365. rule.v.port[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  366. rule.v.port[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  367. return true;
  368. } else if (t == "MATCH_CHARACTERISTICS") {
  369. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  370. if (r.count("mask")) {
  371. json &v = r["mask"];
  372. if (v.is_number()) {
  373. rule.v.characteristics = v;
  374. } else {
  375. std::string tmp = v;
  376. rule.v.characteristics = Utils::hexStrToU64(tmp.c_str());
  377. }
  378. }
  379. return true;
  380. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  381. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  382. rule.v.frameSize[0] = (uint16_t)(OSUtils::jsonInt(r["start"],0ULL) & 0xffffULL);
  383. rule.v.frameSize[1] = (uint16_t)(OSUtils::jsonInt(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  384. return true;
  385. } else if (t == "MATCH_RANDOM") {
  386. rule.t |= ZT_NETWORK_RULE_MATCH_RANDOM;
  387. rule.v.randomProbability = (uint32_t)(OSUtils::jsonInt(r["probability"],0ULL) & 0xffffffffULL);
  388. return true;
  389. } else if (t == "MATCH_TAGS_DIFFERENCE") {
  390. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE;
  391. tag = true;
  392. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  393. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  394. tag = true;
  395. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  396. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  397. tag = true;
  398. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  399. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  400. tag = true;
  401. } else if (t == "MATCH_TAGS_EQUAL") {
  402. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_EQUAL;
  403. tag = true;
  404. } else if (t == "MATCH_TAG_SENDER") {
  405. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_SENDER;
  406. tag = true;
  407. } else if (t == "MATCH_TAG_RECEIVER") {
  408. rule.t |= ZT_NETWORK_RULE_MATCH_TAG_RECEIVER;
  409. tag = true;
  410. } else if (t == "INTEGER_RANGE") {
  411. json &s = r["start"];
  412. if (s.is_string()) {
  413. std::string tmp = s;
  414. rule.v.intRange.start = Utils::hexStrToU64(tmp.c_str());
  415. } else {
  416. rule.v.intRange.start = OSUtils::jsonInt(s,0ULL);
  417. }
  418. json &e = r["end"];
  419. if (e.is_string()) {
  420. std::string tmp = e;
  421. rule.v.intRange.end = (uint32_t)(Utils::hexStrToU64(tmp.c_str()) - rule.v.intRange.start);
  422. } else {
  423. rule.v.intRange.end = (uint32_t)(OSUtils::jsonInt(e,0ULL) - rule.v.intRange.start);
  424. }
  425. rule.v.intRange.idx = (uint16_t)OSUtils::jsonInt(r["idx"],0ULL);
  426. rule.v.intRange.format = (OSUtils::jsonBool(r["little"],false)) ? 0x80 : 0x00;
  427. rule.v.intRange.format |= (uint8_t)((OSUtils::jsonInt(r["bits"],1ULL) - 1) & 63);
  428. }
  429. if (tag) {
  430. rule.v.tag.id = (uint32_t)(OSUtils::jsonInt(r["id"],0ULL) & 0xffffffffULL);
  431. rule.v.tag.value = (uint32_t)(OSUtils::jsonInt(r["value"],0ULL) & 0xffffffffULL);
  432. return true;
  433. }
  434. return false;
  435. }
  436. } // anonymous namespace
  437. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *ztPath,const char *dbPath, int listenPort, RedisConfig *rc) :
  438. _startTime(OSUtils::now()),
  439. _listenPort(listenPort),
  440. _node(node),
  441. _ztPath(ztPath),
  442. _path(dbPath),
  443. _sender((NetworkController::Sender *)0),
  444. _db(this),
  445. _rc(rc)
  446. {
  447. }
  448. EmbeddedNetworkController::~EmbeddedNetworkController()
  449. {
  450. std::lock_guard<std::mutex> l(_threads_l);
  451. _queue.stop();
  452. for(auto t=_threads.begin();t!=_threads.end();++t)
  453. t->join();
  454. }
  455. void EmbeddedNetworkController::setSSORedirectURL(const std::string &url) {
  456. _ssoRedirectURL = url;
  457. }
  458. void EmbeddedNetworkController::init(const Identity &signingId,Sender *sender)
  459. {
  460. char tmp[64];
  461. _signingId = signingId;
  462. _sender = sender;
  463. _signingIdAddressString = signingId.address().toString(tmp);
  464. #ifdef ZT_CONTROLLER_USE_LIBPQ
  465. if ((_path.length() > 9)&&(_path.substr(0,9) == "postgres:")) {
  466. _db.addDB(std::shared_ptr<DB>(new PostgreSQL(_signingId,_path.substr(9).c_str(), _listenPort, _rc)));
  467. } else {
  468. #endif
  469. _db.addDB(std::shared_ptr<DB>(new FileDB(_path.c_str())));
  470. #ifdef ZT_CONTROLLER_USE_LIBPQ
  471. }
  472. #endif
  473. std::string lfJSON;
  474. OSUtils::readFile((_ztPath + ZT_PATH_SEPARATOR_S "local.conf").c_str(),lfJSON);
  475. if (lfJSON.length() > 0) {
  476. nlohmann::json lfConfig(OSUtils::jsonParse(lfJSON));
  477. nlohmann::json &settings = lfConfig["settings"];
  478. if (settings.is_object()) {
  479. nlohmann::json &controllerDb = settings["controllerDb"];
  480. if (controllerDb.is_object()) {
  481. std::string type = controllerDb["type"];
  482. if (type == "lf") {
  483. std::string lfOwner = controllerDb["owner"];
  484. std::string lfHost = controllerDb["host"];
  485. int lfPort = controllerDb["port"];
  486. bool storeOnlineState = controllerDb["storeOnlineState"];
  487. if ((lfOwner.length())&&(lfHost.length())&&(lfPort > 0)&&(lfPort < 65536)) {
  488. std::size_t pubHdrLoc = lfOwner.find("Public: ");
  489. if ((pubHdrLoc > 0)&&((pubHdrLoc + 8) < lfOwner.length())) {
  490. std::string lfOwnerPublic = lfOwner.substr(pubHdrLoc + 8);
  491. std::size_t pubHdrEnd = lfOwnerPublic.find_first_of("\n\r\t ");
  492. if (pubHdrEnd != std::string::npos) {
  493. lfOwnerPublic = lfOwnerPublic.substr(0,pubHdrEnd);
  494. _db.addDB(std::shared_ptr<DB>(new LFDB(_signingId,_path.c_str(),lfOwner.c_str(),lfOwnerPublic.c_str(),lfHost.c_str(),lfPort,storeOnlineState)));
  495. }
  496. }
  497. }
  498. }
  499. }
  500. }
  501. }
  502. _db.waitForReady();
  503. }
  504. void EmbeddedNetworkController::request(
  505. uint64_t nwid,
  506. const InetAddress &fromAddr,
  507. uint64_t requestPacketId,
  508. const Identity &identity,
  509. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  510. {
  511. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  512. return;
  513. _startThreads();
  514. _RQEntry *qe = new _RQEntry;
  515. qe->nwid = nwid;
  516. qe->requestPacketId = requestPacketId;
  517. qe->fromAddr = fromAddr;
  518. qe->identity = identity;
  519. qe->metaData = metaData;
  520. qe->type = _RQEntry::RQENTRY_TYPE_REQUEST;
  521. _queue.post(qe);
  522. }
  523. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  524. const std::vector<std::string> &path,
  525. const std::map<std::string,std::string> &urlArgs,
  526. const std::map<std::string,std::string> &headers,
  527. const std::string &body,
  528. std::string &responseBody,
  529. std::string &responseContentType)
  530. {
  531. if ((!path.empty())&&(path[0] == "network")) {
  532. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  533. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  534. json network;
  535. if (!_db.get(nwid,network))
  536. return 404;
  537. if (path.size() >= 3) {
  538. if (path[2] == "member") {
  539. if (path.size() >= 4) {
  540. // Get member
  541. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  542. json member;
  543. if (!_db.get(nwid,network,address,member))
  544. return 404;
  545. responseBody = OSUtils::jsonDump(member);
  546. responseContentType = "application/json";
  547. } else {
  548. // List members and their revisions
  549. responseBody = "{";
  550. std::vector<json> members;
  551. if (_db.get(nwid,network,members)) {
  552. responseBody.reserve((members.size() + 2) * 32);
  553. std::string mid;
  554. for(auto member=members.begin();member!=members.end();++member) {
  555. mid = OSUtils::jsonString((*member)["id"], "");
  556. char tmp[128];
  557. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s\"%s\":%llu",(responseBody.length() > 1) ? "," : "",mid.c_str(),(unsigned long long)OSUtils::jsonInt((*member)["revision"],0));
  558. responseBody.append(tmp);
  559. }
  560. }
  561. responseBody.push_back('}');
  562. responseContentType = "application/json";
  563. }
  564. return 200;
  565. } // else 404
  566. } else {
  567. // Get network
  568. responseBody = OSUtils::jsonDump(network);
  569. responseContentType = "application/json";
  570. return 200;
  571. }
  572. } else if (path.size() == 1) {
  573. // List networks
  574. std::set<uint64_t> networkIds;
  575. _db.networks(networkIds);
  576. char tmp[64];
  577. responseBody = "[";
  578. responseBody.reserve((networkIds.size() + 1) * 24);
  579. for(std::set<uint64_t>::const_iterator i(networkIds.begin());i!=networkIds.end();++i) {
  580. if (responseBody.length() > 1)
  581. responseBody.push_back(',');
  582. OSUtils::ztsnprintf(tmp,sizeof(tmp),"\"%.16llx\"",(unsigned long long)*i);
  583. responseBody.append(tmp);
  584. }
  585. responseBody.push_back(']');
  586. responseContentType = "application/json";
  587. return 200;
  588. } // else 404
  589. } else {
  590. // Controller status
  591. char tmp[4096];
  592. const bool dbOk = _db.isReady();
  593. OSUtils::ztsnprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu,\n\t\"databaseReady\": %s\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now(),dbOk ? "true" : "false");
  594. responseBody = tmp;
  595. responseContentType = "application/json";
  596. return dbOk ? 200 : 503;
  597. }
  598. return 404;
  599. }
  600. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  601. const std::vector<std::string> &path,
  602. const std::map<std::string,std::string> &urlArgs,
  603. const std::map<std::string,std::string> &headers,
  604. const std::string &body,
  605. std::string &responseBody,
  606. std::string &responseContentType)
  607. {
  608. if (path.empty())
  609. return 404;
  610. json b;
  611. try {
  612. b = OSUtils::jsonParse(body);
  613. if (!b.is_object()) {
  614. responseBody = "{ \"message\": \"body is not a JSON object\" }";
  615. responseContentType = "application/json";
  616. return 400;
  617. }
  618. } catch ( ... ) {
  619. responseBody = "{ \"message\": \"body JSON is invalid\" }";
  620. responseContentType = "application/json";
  621. return 400;
  622. }
  623. const int64_t now = OSUtils::now();
  624. if (path[0] == "network") {
  625. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  626. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  627. char nwids[24];
  628. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  629. if (path.size() >= 3) {
  630. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  631. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  632. char addrs[24];
  633. OSUtils::ztsnprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  634. json member,network;
  635. _db.get(nwid,network,address,member);
  636. DB::initMember(member);
  637. try {
  638. if (b.count("activeBridge")) member["activeBridge"] = OSUtils::jsonBool(b["activeBridge"], false);
  639. if (b.count("noAutoAssignIps")) member["noAutoAssignIps"] = OSUtils::jsonBool(b["noAutoAssignIps"], false);
  640. if (b.count("authenticationExpiryTime")) member["authenticationExpiryTime"] = (uint64_t)OSUtils::jsonInt(b["authenticationExpiryTime"], 0ULL);
  641. if (b.count("authenticationURL")) member["authenticationURL"] = OSUtils::jsonString(b["authenticationURL"], "");
  642. if (b.count("remoteTraceTarget")) {
  643. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  644. if (rtt.length() == 10) {
  645. member["remoteTraceTarget"] = rtt;
  646. } else {
  647. member["remoteTraceTarget"] = json();
  648. }
  649. }
  650. if (b.count("remoteTraceLevel")) member["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  651. if (b.count("authorized")) {
  652. const bool newAuth = OSUtils::jsonBool(b["authorized"],false);
  653. if (newAuth != OSUtils::jsonBool(member["authorized"],false)) {
  654. member["authorized"] = newAuth;
  655. member[((newAuth) ? "lastAuthorizedTime" : "lastDeauthorizedTime")] = now;
  656. if (newAuth) {
  657. member["lastAuthorizedCredentialType"] = "api";
  658. member["lastAuthorizedCredential"] = json();
  659. }
  660. }
  661. }
  662. if (b.count("ipAssignments")) {
  663. json &ipa = b["ipAssignments"];
  664. if (ipa.is_array()) {
  665. json mipa(json::array());
  666. for(unsigned long i=0;i<ipa.size();++i) {
  667. std::string ips = ipa[i];
  668. InetAddress ip(ips.c_str());
  669. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  670. char tmpip[64];
  671. mipa.push_back(ip.toIpString(tmpip));
  672. if (mipa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  673. break;
  674. }
  675. }
  676. member["ipAssignments"] = mipa;
  677. }
  678. }
  679. if (b.count("tags")) {
  680. json &tags = b["tags"];
  681. if (tags.is_array()) {
  682. std::map<uint64_t,uint64_t> mtags;
  683. for(unsigned long i=0;i<tags.size();++i) {
  684. json &tag = tags[i];
  685. if ((tag.is_array())&&(tag.size() == 2))
  686. mtags[OSUtils::jsonInt(tag[0],0ULL) & 0xffffffffULL] = OSUtils::jsonInt(tag[1],0ULL) & 0xffffffffULL;
  687. }
  688. json mtagsa = json::array();
  689. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  690. json ta = json::array();
  691. ta.push_back(t->first);
  692. ta.push_back(t->second);
  693. mtagsa.push_back(ta);
  694. if (mtagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  695. break;
  696. }
  697. member["tags"] = mtagsa;
  698. }
  699. }
  700. if (b.count("capabilities")) {
  701. json &capabilities = b["capabilities"];
  702. if (capabilities.is_array()) {
  703. json mcaps = json::array();
  704. for(unsigned long i=0;i<capabilities.size();++i) {
  705. mcaps.push_back(OSUtils::jsonInt(capabilities[i],0ULL));
  706. if (mcaps.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  707. break;
  708. }
  709. std::sort(mcaps.begin(),mcaps.end());
  710. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  711. member["capabilities"] = mcaps;
  712. }
  713. }
  714. } catch ( ... ) {
  715. responseBody = "{ \"message\": \"exception while processing parameters in JSON body\" }";
  716. responseContentType = "application/json";
  717. return 400;
  718. }
  719. member["id"] = addrs;
  720. member["address"] = addrs; // legacy
  721. member["nwid"] = nwids;
  722. DB::cleanMember(member);
  723. _db.save(member,true);
  724. responseBody = OSUtils::jsonDump(member);
  725. responseContentType = "application/json";
  726. return 200;
  727. } // else 404
  728. } else {
  729. // POST to network ID
  730. // Magic ID ending with ______ picks a random unused network ID
  731. if (path[1].substr(10) == "______") {
  732. nwid = 0;
  733. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  734. uint64_t nwidPostfix = 0;
  735. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  736. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  737. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  738. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  739. if (!_db.hasNetwork(tryNwid)) {
  740. nwid = tryNwid;
  741. break;
  742. }
  743. }
  744. if (!nwid)
  745. return 503;
  746. }
  747. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  748. json network;
  749. _db.get(nwid,network);
  750. DB::initNetwork(network);
  751. try {
  752. if (b.count("name")) network["name"] = OSUtils::jsonString(b["name"],"");
  753. if (b.count("private")) network["private"] = OSUtils::jsonBool(b["private"],true);
  754. if (b.count("enableBroadcast")) network["enableBroadcast"] = OSUtils::jsonBool(b["enableBroadcast"],false);
  755. if (b.count("multicastLimit")) network["multicastLimit"] = OSUtils::jsonInt(b["multicastLimit"],32ULL);
  756. if (b.count("mtu")) 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);
  757. if (b.count("remoteTraceTarget")) {
  758. const std::string rtt(OSUtils::jsonString(b["remoteTraceTarget"],""));
  759. if (rtt.length() == 10) {
  760. network["remoteTraceTarget"] = rtt;
  761. } else {
  762. network["remoteTraceTarget"] = json();
  763. }
  764. }
  765. if (b.count("remoteTraceLevel")) network["remoteTraceLevel"] = OSUtils::jsonInt(b["remoteTraceLevel"],0ULL);
  766. if (b.count("v4AssignMode")) {
  767. json nv4m;
  768. json &v4m = b["v4AssignMode"];
  769. if (v4m.is_string()) { // backward compatibility
  770. nv4m["zt"] = (OSUtils::jsonString(v4m,"") == "zt");
  771. } else if (v4m.is_object()) {
  772. nv4m["zt"] = OSUtils::jsonBool(v4m["zt"],false);
  773. } else nv4m["zt"] = false;
  774. network["v4AssignMode"] = nv4m;
  775. }
  776. if (b.count("v6AssignMode")) {
  777. json nv6m;
  778. json &v6m = b["v6AssignMode"];
  779. if (!nv6m.is_object()) nv6m = json::object();
  780. if (v6m.is_string()) { // backward compatibility
  781. std::vector<std::string> v6ms(OSUtils::split(OSUtils::jsonString(v6m,"").c_str(),",","",""));
  782. std::sort(v6ms.begin(),v6ms.end());
  783. v6ms.erase(std::unique(v6ms.begin(),v6ms.end()),v6ms.end());
  784. nv6m["rfc4193"] = false;
  785. nv6m["zt"] = false;
  786. nv6m["6plane"] = false;
  787. for(std::vector<std::string>::iterator i(v6ms.begin());i!=v6ms.end();++i) {
  788. if (*i == "rfc4193")
  789. nv6m["rfc4193"] = true;
  790. else if (*i == "zt")
  791. nv6m["zt"] = true;
  792. else if (*i == "6plane")
  793. nv6m["6plane"] = true;
  794. }
  795. } else if (v6m.is_object()) {
  796. if (v6m.count("rfc4193")) nv6m["rfc4193"] = OSUtils::jsonBool(v6m["rfc4193"],false);
  797. if (v6m.count("zt")) nv6m["zt"] = OSUtils::jsonBool(v6m["zt"],false);
  798. if (v6m.count("6plane")) nv6m["6plane"] = OSUtils::jsonBool(v6m["6plane"],false);
  799. } else {
  800. nv6m["rfc4193"] = false;
  801. nv6m["zt"] = false;
  802. nv6m["6plane"] = false;
  803. }
  804. network["v6AssignMode"] = nv6m;
  805. }
  806. if (b.count("routes")) {
  807. json &rts = b["routes"];
  808. if (rts.is_array()) {
  809. json nrts = json::array();
  810. for(unsigned long i=0;i<rts.size();++i) {
  811. json &rt = rts[i];
  812. if (rt.is_object()) {
  813. json &target = rt["target"];
  814. json &via = rt["via"];
  815. if (target.is_string()) {
  816. InetAddress t(target.get<std::string>().c_str());
  817. InetAddress v;
  818. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  819. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.netmaskBitsValid()) ) {
  820. json tmp;
  821. char tmp2[64];
  822. tmp["target"] = t.toString(tmp2);
  823. if (v.ss_family == t.ss_family)
  824. tmp["via"] = v.toIpString(tmp2);
  825. else tmp["via"] = json();
  826. nrts.push_back(tmp);
  827. if (nrts.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  828. break;
  829. }
  830. }
  831. }
  832. }
  833. network["routes"] = nrts;
  834. }
  835. }
  836. if (b.count("ipAssignmentPools")) {
  837. json &ipp = b["ipAssignmentPools"];
  838. if (ipp.is_array()) {
  839. json nipp = json::array();
  840. for(unsigned long i=0;i<ipp.size();++i) {
  841. json &ip = ipp[i];
  842. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  843. InetAddress f(OSUtils::jsonString(ip["ipRangeStart"],"").c_str());
  844. InetAddress t(OSUtils::jsonString(ip["ipRangeEnd"],"").c_str());
  845. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  846. json tmp = json::object();
  847. char tmp2[64];
  848. tmp["ipRangeStart"] = f.toIpString(tmp2);
  849. tmp["ipRangeEnd"] = t.toIpString(tmp2);
  850. nipp.push_back(tmp);
  851. if (nipp.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  852. break;
  853. }
  854. }
  855. }
  856. network["ipAssignmentPools"] = nipp;
  857. }
  858. }
  859. if (b.count("rules")) {
  860. json &rules = b["rules"];
  861. if (rules.is_array()) {
  862. json nrules = json::array();
  863. for(unsigned long i=0;i<rules.size();++i) {
  864. json &rule = rules[i];
  865. if (rule.is_object()) {
  866. ZT_VirtualNetworkRule ztr;
  867. if (_parseRule(rule,ztr)) {
  868. nrules.push_back(_renderRule(ztr));
  869. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  870. break;
  871. }
  872. }
  873. }
  874. network["rules"] = nrules;
  875. }
  876. }
  877. if (b.count("authTokens")) {
  878. json &authTokens = b["authTokens"];
  879. if (authTokens.is_object()) {
  880. json nat;
  881. for(json::iterator t(authTokens.begin());t!=authTokens.end();++t) {
  882. if ((t.value().is_number())&&(t.value() >= 0))
  883. nat[t.key()] = t.value();
  884. }
  885. network["authTokens"] = nat;
  886. } else {
  887. network["authTokens"] = {{}};
  888. }
  889. }
  890. if (b.count("capabilities")) {
  891. json &capabilities = b["capabilities"];
  892. if (capabilities.is_array()) {
  893. std::map< uint64_t,json > ncaps;
  894. for(unsigned long i=0;i<capabilities.size();++i) {
  895. json &cap = capabilities[i];
  896. if (cap.is_object()) {
  897. json ncap = json::object();
  898. const uint64_t capId = OSUtils::jsonInt(cap["id"],0ULL);
  899. ncap["id"] = capId;
  900. ncap["default"] = OSUtils::jsonBool(cap["default"],false);
  901. json &rules = cap["rules"];
  902. json nrules = json::array();
  903. if (rules.is_array()) {
  904. for(unsigned long i=0;i<rules.size();++i) {
  905. json &rule = rules[i];
  906. if (rule.is_object()) {
  907. ZT_VirtualNetworkRule ztr;
  908. if (_parseRule(rule,ztr)) {
  909. nrules.push_back(_renderRule(ztr));
  910. if (nrules.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  911. break;
  912. }
  913. }
  914. }
  915. }
  916. ncap["rules"] = nrules;
  917. ncaps[capId] = ncap;
  918. }
  919. }
  920. json ncapsa = json::array();
  921. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c) {
  922. ncapsa.push_back(c->second);
  923. if (ncapsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  924. break;
  925. }
  926. network["capabilities"] = ncapsa;
  927. }
  928. }
  929. if (b.count("tags")) {
  930. json &tags = b["tags"];
  931. if (tags.is_array()) {
  932. std::map< uint64_t,json > ntags;
  933. for(unsigned long i=0;i<tags.size();++i) {
  934. json &tag = tags[i];
  935. if (tag.is_object()) {
  936. json ntag = json::object();
  937. const uint64_t tagId = OSUtils::jsonInt(tag["id"],0ULL);
  938. ntag["id"] = tagId;
  939. json &dfl = tag["default"];
  940. if (dfl.is_null())
  941. ntag["default"] = dfl;
  942. else ntag["default"] = OSUtils::jsonInt(dfl,0ULL);
  943. ntags[tagId] = ntag;
  944. }
  945. }
  946. json ntagsa = json::array();
  947. for(std::map< uint64_t,json >::iterator t(ntags.begin());t!=ntags.end();++t) {
  948. ntagsa.push_back(t->second);
  949. if (ntagsa.size() >= ZT_CONTROLLER_MAX_ARRAY_SIZE)
  950. break;
  951. }
  952. network["tags"] = ntagsa;
  953. }
  954. }
  955. if (b.count("dns")) {
  956. json &dns = b["dns"];
  957. if (dns.is_object()) {
  958. json nd;
  959. nd["domain"] = dns["domain"];
  960. json &srv = dns["servers"];
  961. if (srv.is_array()) {
  962. json ns = json::array();
  963. for(unsigned int i=0;i<srv.size();++i) {
  964. ns.push_back(srv[i]);
  965. }
  966. nd["servers"] = ns;
  967. }
  968. network["dns"] = nd;
  969. }
  970. }
  971. } catch ( ... ) {
  972. responseBody = "{ \"message\": \"exception occurred while parsing body variables\" }";
  973. responseContentType = "application/json";
  974. return 400;
  975. }
  976. network["id"] = nwids;
  977. network["nwid"] = nwids; // legacy
  978. DB::cleanNetwork(network);
  979. _db.save(network,true);
  980. responseBody = OSUtils::jsonDump(network);
  981. responseContentType = "application/json";
  982. return 200;
  983. } // else 404
  984. } // else 404
  985. }
  986. return 404;
  987. }
  988. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  989. const std::vector<std::string> &path,
  990. const std::map<std::string,std::string> &urlArgs,
  991. const std::map<std::string,std::string> &headers,
  992. const std::string &body,
  993. std::string &responseBody,
  994. std::string &responseContentType)
  995. {
  996. if (path.empty())
  997. return 404;
  998. if (path[0] == "network") {
  999. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1000. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1001. if (path.size() >= 3) {
  1002. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1003. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1004. json network,member;
  1005. _db.get(nwid,network,address,member);
  1006. _db.eraseMember(nwid, address);
  1007. {
  1008. std::lock_guard<std::mutex> l(_memberStatus_l);
  1009. _memberStatus.erase(_MemberStatusKey(nwid,address));
  1010. }
  1011. if (!member.size())
  1012. return 404;
  1013. responseBody = OSUtils::jsonDump(member);
  1014. responseContentType = "application/json";
  1015. return 200;
  1016. }
  1017. } else {
  1018. json network;
  1019. _db.get(nwid,network);
  1020. _db.eraseNetwork(nwid);
  1021. {
  1022. std::lock_guard<std::mutex> l(_memberStatus_l);
  1023. for(auto i=_memberStatus.begin();i!=_memberStatus.end();) {
  1024. if (i->first.networkId == nwid)
  1025. _memberStatus.erase(i++);
  1026. else ++i;
  1027. }
  1028. }
  1029. if (!network.size())
  1030. return 404;
  1031. responseBody = OSUtils::jsonDump(network);
  1032. responseContentType = "application/json";
  1033. return 200;
  1034. }
  1035. } // else 404
  1036. } // else 404
  1037. return 404;
  1038. }
  1039. void EmbeddedNetworkController::handleRemoteTrace(const ZT_RemoteTrace &rt)
  1040. {
  1041. static volatile unsigned long idCounter = 0;
  1042. char id[128],tmp[128];
  1043. std::string k,v;
  1044. try {
  1045. // Convert Dictionary into JSON object
  1046. json d;
  1047. char *saveptr = (char *)0;
  1048. for(char *l=Utils::stok(rt.data,"\n",&saveptr);(l);l=Utils::stok((char *)0,"\n",&saveptr)) {
  1049. char *eq = strchr(l,'=');
  1050. if (eq > l) {
  1051. k.assign(l,(unsigned long)(eq - l));
  1052. v.clear();
  1053. ++eq;
  1054. while (*eq) {
  1055. if (*eq == '\\') {
  1056. ++eq;
  1057. if (*eq) {
  1058. switch(*eq) {
  1059. case 'r': v.push_back('\r'); break;
  1060. case 'n': v.push_back('\n'); break;
  1061. case '0': v.push_back((char)0); break;
  1062. case 'e': v.push_back('='); break;
  1063. default: v.push_back(*eq); break;
  1064. }
  1065. ++eq;
  1066. }
  1067. } else {
  1068. v.push_back(*(eq++));
  1069. }
  1070. }
  1071. if ((k.length() > 0)&&(v.length() > 0))
  1072. d[k] = v;
  1073. }
  1074. }
  1075. const int64_t now = OSUtils::now();
  1076. OSUtils::ztsnprintf(id,sizeof(id),"%.10llx-%.16llx-%.10llx-%.4x",_signingId.address().toInt(),now,rt.origin,(unsigned int)(idCounter++ & 0xffff));
  1077. d["id"] = id;
  1078. d["objtype"] = "trace";
  1079. d["ts"] = now;
  1080. d["nodeId"] = Utils::hex10(rt.origin,tmp);
  1081. _db.save(d,true);
  1082. } catch ( ... ) {
  1083. // drop invalid trace messages if an error occurs
  1084. }
  1085. }
  1086. void EmbeddedNetworkController::onNetworkUpdate(const void *db,uint64_t networkId,const nlohmann::json &network)
  1087. {
  1088. // Send an update to all members of the network that are online
  1089. const int64_t now = OSUtils::now();
  1090. std::lock_guard<std::mutex> l(_memberStatus_l);
  1091. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1092. if ((i->first.networkId == networkId)&&(i->second.online(now))&&(i->second.lastRequestMetaData))
  1093. request(networkId,InetAddress(),0,i->second.identity,i->second.lastRequestMetaData);
  1094. }
  1095. }
  1096. void EmbeddedNetworkController::onNetworkMemberUpdate(const void *db,uint64_t networkId,uint64_t memberId,const nlohmann::json &member)
  1097. {
  1098. // Push update to member if online
  1099. try {
  1100. std::lock_guard<std::mutex> l(_memberStatus_l);
  1101. _MemberStatus &ms = _memberStatus[_MemberStatusKey(networkId,memberId)];
  1102. if ((ms.online(OSUtils::now()))&&(ms.lastRequestMetaData))
  1103. request(networkId,InetAddress(),0,ms.identity,ms.lastRequestMetaData);
  1104. } catch ( ... ) {}
  1105. }
  1106. void EmbeddedNetworkController::onNetworkMemberDeauthorize(const void *db,uint64_t networkId,uint64_t memberId)
  1107. {
  1108. const int64_t now = OSUtils::now();
  1109. Revocation rev((uint32_t)_node->prng(),networkId,0,now,ZT_REVOCATION_FLAG_FAST_PROPAGATE,Address(memberId),Revocation::CREDENTIAL_TYPE_COM);
  1110. rev.sign(_signingId);
  1111. {
  1112. std::lock_guard<std::mutex> l(_memberStatus_l);
  1113. for(auto i=_memberStatus.begin();i!=_memberStatus.end();++i) {
  1114. if ((i->first.networkId == networkId)&&(i->second.online(now)))
  1115. _node->ncSendRevocation(Address(i->first.nodeId),rev);
  1116. }
  1117. }
  1118. }
  1119. void EmbeddedNetworkController::_request(
  1120. uint64_t nwid,
  1121. const InetAddress &fromAddr,
  1122. uint64_t requestPacketId,
  1123. const Identity &identity,
  1124. const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData)
  1125. {
  1126. char nwids[24];
  1127. DB::NetworkSummaryInfo ns;
  1128. json network,member;
  1129. if (((!_signingId)||(!_signingId.hasPrivate()))||(_signingId.address().toInt() != (nwid >> 24))||(!_sender))
  1130. return;
  1131. const int64_t now = OSUtils::now();
  1132. if (requestPacketId) {
  1133. std::lock_guard<std::mutex> l(_memberStatus_l);
  1134. _MemberStatus &ms = _memberStatus[_MemberStatusKey(nwid,identity.address().toInt())];
  1135. if ((now - ms.lastRequestTime) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  1136. return;
  1137. ms.lastRequestTime = now;
  1138. }
  1139. _db.nodeIsOnline(nwid,identity.address().toInt(),fromAddr);
  1140. Utils::hex(nwid,nwids);
  1141. _db.get(nwid,network,identity.address().toInt(),member,ns);
  1142. if ((!network.is_object())||(network.empty())) {
  1143. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_OBJECT_NOT_FOUND, nullptr, 0);
  1144. return;
  1145. }
  1146. const bool newMember = ((!member.is_object())||(member.empty()));
  1147. DB::initMember(member);
  1148. _MemberStatusKey msk(nwid,identity.address().toInt());
  1149. {
  1150. const std::string haveIdStr(OSUtils::jsonString(member["identity"],""));
  1151. if (haveIdStr.length() > 0) {
  1152. // If we already know this member's identity perform a full compare. This prevents
  1153. // a "collision" from being able to auth onto our network in place of an already
  1154. // known member.
  1155. try {
  1156. if (Identity(haveIdStr.c_str()) != identity) {
  1157. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1158. return;
  1159. }
  1160. } catch ( ... ) {
  1161. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1162. return;
  1163. }
  1164. } else {
  1165. // If we do not yet know this member's identity, learn it.
  1166. char idtmp[1024];
  1167. member["identity"] = identity.toString(false,idtmp);
  1168. }
  1169. }
  1170. // These are always the same, but make sure they are set
  1171. {
  1172. char tmpid[128];
  1173. const std::string addrs(identity.address().toString(tmpid));
  1174. member["id"] = addrs;
  1175. member["address"] = addrs;
  1176. member["nwid"] = nwids;
  1177. }
  1178. // Determine whether and how member is authorized
  1179. bool authorized = false;
  1180. bool autoAuthorized = false;
  1181. json autoAuthCredentialType,autoAuthCredential;
  1182. if (OSUtils::jsonBool(member["authorized"],false)) {
  1183. authorized = true;
  1184. } else if (!OSUtils::jsonBool(network["private"],true)) {
  1185. authorized = true;
  1186. autoAuthorized = true;
  1187. autoAuthCredentialType = "public";
  1188. } else {
  1189. char presentedAuth[512];
  1190. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH,presentedAuth,sizeof(presentedAuth)) > 0) {
  1191. presentedAuth[511] = (char)0; // sanity check
  1192. if ((strlen(presentedAuth) > 6)&&(!strncmp(presentedAuth,"token:",6))) {
  1193. const char *const presentedToken = presentedAuth + 6;
  1194. json authTokens(network["authTokens"]);
  1195. json &tokenExpires = authTokens[presentedToken];
  1196. if (tokenExpires.is_number()) {
  1197. if ((tokenExpires == 0)||(tokenExpires > now)) {
  1198. authorized = true;
  1199. autoAuthorized = true;
  1200. autoAuthCredentialType = "token";
  1201. autoAuthCredential = presentedToken;
  1202. }
  1203. }
  1204. }
  1205. }
  1206. }
  1207. // If we auto-authorized, update member record
  1208. if ((autoAuthorized)&&(authorized)) {
  1209. member["authorized"] = true;
  1210. member["lastAuthorizedTime"] = now;
  1211. member["lastAuthorizedCredentialType"] = autoAuthCredentialType;
  1212. member["lastAuthorizedCredential"] = autoAuthCredential;
  1213. }
  1214. // Should we check SSO Stuff?
  1215. // If network is configured with SSO, and the member is not marked exempt: yes
  1216. // Otherwise no, we use standard auth logic.
  1217. AuthInfo info;
  1218. int64_t authenticationExpiryTime = -1;
  1219. bool networkSSOEnabled = OSUtils::jsonBool(network["ssoEnabled"], false);
  1220. bool memberSSOExempt = OSUtils::jsonBool(member["ssoExempt"], false);
  1221. if (networkSSOEnabled && !memberSSOExempt) {
  1222. authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1223. info = _db.getSSOAuthInfo(member, _ssoRedirectURL);
  1224. assert(info.enabled == networkSSOEnabled);
  1225. if (authenticationExpiryTime <= now) {
  1226. if (info.version == 0) {
  1227. Dictionary<4096> authInfo;
  1228. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, (uint64_t)0ULL);
  1229. authInfo.add(ZT_AUTHINFO_DICT_KEY_AUTHENTICATION_URL, info.authenticationURL.c_str());
  1230. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1231. } else if (info.version == 1) {
  1232. Dictionary<8192> authInfo;
  1233. authInfo.add(ZT_AUTHINFO_DICT_KEY_VERSION, info.version);
  1234. authInfo.add(ZT_AUTHINFO_DICT_KEY_ISSUER_URL, info.issuerURL.c_str());
  1235. authInfo.add(ZT_AUTHINFO_DICT_KEY_CENTRAL_ENDPOINT_URL, info.centralAuthURL.c_str());
  1236. authInfo.add(ZT_AUTHINFO_DICT_KEY_NONCE, info.ssoNonce.c_str());
  1237. authInfo.add(ZT_AUTHINFO_DICT_KEY_STATE, info.ssoState.c_str());
  1238. authInfo.add(ZT_AUTHINFO_DICT_KEY_CLIENT_ID, info.ssoClientID.c_str());
  1239. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_AUTHENTICATION_REQUIRED, authInfo.data(), authInfo.sizeBytes());
  1240. }
  1241. DB::cleanMember(member);
  1242. _db.save(member,true);
  1243. return;
  1244. }
  1245. }
  1246. if (authorized) {
  1247. // Update version info and meta-data if authorized and if this is a genuine request
  1248. if (requestPacketId) {
  1249. const uint64_t vMajor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  1250. const uint64_t vMinor = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  1251. const uint64_t vRev = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  1252. const uint64_t vProto = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  1253. member["vMajor"] = vMajor;
  1254. member["vMinor"] = vMinor;
  1255. member["vRev"] = vRev;
  1256. member["vProto"] = vProto;
  1257. {
  1258. std::lock_guard<std::mutex> l(_memberStatus_l);
  1259. _MemberStatus &ms = _memberStatus[msk];
  1260. ms.authenticationExpiryTime = authenticationExpiryTime;
  1261. ms.vMajor = (int)vMajor;
  1262. ms.vMinor = (int)vMinor;
  1263. ms.vRev = (int)vRev;
  1264. ms.vProto = (int)vProto;
  1265. ms.lastRequestMetaData = metaData;
  1266. ms.identity = identity;
  1267. }
  1268. if (authenticationExpiryTime > 0) {
  1269. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1270. _expiringSoon.insert(std::pair<int64_t, _MemberStatusKey>(authenticationExpiryTime, msk));
  1271. }
  1272. }
  1273. } else {
  1274. // If they are not authorized, STOP!
  1275. DB::cleanMember(member);
  1276. _db.save(member,true);
  1277. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
  1278. return;
  1279. }
  1280. // -------------------------------------------------------------------------
  1281. // If we made it this far, they are authorized (and authenticated).
  1282. // -------------------------------------------------------------------------
  1283. // Default timeout: 15 minutes. Maximum: two hours. Can be specified by an optional field in the network config
  1284. // if something longer than 15 minutes is desired. Minimum is 5 minutes since shorter than that would be flaky.
  1285. int64_t credentialtmd = ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_DFL_MAX_DELTA;
  1286. if (network.contains("certificateTimeoutWindowSize")) {
  1287. credentialtmd = (int64_t)network["certificateTimeoutWindowSize"];
  1288. }
  1289. credentialtmd = std::max(std::min(credentialtmd, ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MAX_MAX_DELTA), ZT_NETWORKCONFIG_DEFAULT_CREDENTIAL_TIME_MIN_MAX_DELTA);
  1290. std::unique_ptr<NetworkConfig> nc(new NetworkConfig());
  1291. nc->networkId = nwid;
  1292. nc->type = OSUtils::jsonBool(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  1293. nc->timestamp = now;
  1294. nc->credentialTimeMaxDelta = credentialtmd;
  1295. nc->revision = OSUtils::jsonInt(network["revision"],0ULL);
  1296. nc->issuedTo = identity.address();
  1297. if (OSUtils::jsonBool(network["enableBroadcast"],true)) nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  1298. Utils::scopy(nc->name,sizeof(nc->name),OSUtils::jsonString(network["name"],"").c_str());
  1299. 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);
  1300. nc->multicastLimit = (unsigned int)OSUtils::jsonInt(network["multicastLimit"],32ULL);
  1301. nc->ssoEnabled = networkSSOEnabled; //OSUtils::jsonBool(network["ssoEnabled"], false);
  1302. nc->ssoVersion = info.version;
  1303. if (info.version == 0) {
  1304. nc->authenticationExpiryTime = OSUtils::jsonInt(member["authenticationExpiryTime"], 0LL);
  1305. if (!info.authenticationURL.empty()) {
  1306. Utils::scopy(nc->authenticationURL, sizeof(nc->authenticationURL), info.authenticationURL.c_str());
  1307. }
  1308. }
  1309. else if (info.version == 1) {
  1310. nc->authenticationExpiryTime = OSUtils::jsonInt(member["authenticationExpiryTime"], 0LL);
  1311. if (!info.authenticationURL.empty()) {
  1312. Utils::scopy(nc->authenticationURL, sizeof(nc->authenticationURL), info.authenticationURL.c_str());
  1313. }
  1314. if (!info.centralAuthURL.empty()) {
  1315. Utils::scopy(nc->centralAuthURL, sizeof(nc->centralAuthURL), info.centralAuthURL.c_str());
  1316. }
  1317. if (!info.issuerURL.empty()) {
  1318. fprintf(stderr, "copying issuerURL to nc: %s\n", info.issuerURL.c_str());
  1319. Utils::scopy(nc->issuerURL, sizeof(nc->issuerURL), info.issuerURL.c_str());
  1320. }
  1321. if (!info.ssoNonce.empty()) {
  1322. Utils::scopy(nc->ssoNonce, sizeof(nc->ssoNonce), info.ssoNonce.c_str());
  1323. }
  1324. if (!info.ssoState.empty()) {
  1325. Utils::scopy(nc->ssoState, sizeof(nc->ssoState), info.ssoState.c_str());
  1326. }
  1327. if (!info.ssoClientID.empty()) {
  1328. Utils::scopy(nc->ssoClientID, sizeof(nc->ssoClientID), info.ssoClientID.c_str());
  1329. }
  1330. }
  1331. std::string rtt(OSUtils::jsonString(member["remoteTraceTarget"],""));
  1332. if (rtt.length() == 10) {
  1333. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1334. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(member["remoteTraceLevel"],0ULL);
  1335. } else {
  1336. rtt = OSUtils::jsonString(network["remoteTraceTarget"],"");
  1337. if (rtt.length() == 10) {
  1338. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1339. } else {
  1340. nc->remoteTraceTarget.zero();
  1341. }
  1342. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(network["remoteTraceLevel"],0ULL);
  1343. }
  1344. for(std::vector<Address>::const_iterator ab(ns.activeBridges.begin());ab!=ns.activeBridges.end();++ab)
  1345. nc->addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1346. json &v4AssignMode = network["v4AssignMode"];
  1347. json &v6AssignMode = network["v6AssignMode"];
  1348. json &ipAssignmentPools = network["ipAssignmentPools"];
  1349. json &routes = network["routes"];
  1350. json &rules = network["rules"];
  1351. json &capabilities = network["capabilities"];
  1352. json &tags = network["tags"];
  1353. json &memberCapabilities = member["capabilities"];
  1354. json &memberTags = member["tags"];
  1355. json &dns = network["dns"];
  1356. //fprintf(stderr, "IP Assignment Pools for Network %s: %s\n", nwids, OSUtils::jsonDump(ipAssignmentPools, 2).c_str());
  1357. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  1358. // Old versions with no rules engine support get an allow everything rule.
  1359. // Since rules are enforced bidirectionally, newer versions *will* still
  1360. // enforce rules on the inbound side.
  1361. nc->ruleCount = 1;
  1362. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1363. } else {
  1364. if (rules.is_array()) {
  1365. for(unsigned long i=0;i<rules.size();++i) {
  1366. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1367. break;
  1368. if (_parseRule(rules[i],nc->rules[nc->ruleCount]))
  1369. ++nc->ruleCount;
  1370. }
  1371. }
  1372. std::map< uint64_t,json * > capsById;
  1373. if (!memberCapabilities.is_array())
  1374. memberCapabilities = json::array();
  1375. if (capabilities.is_array()) {
  1376. for(unsigned long i=0;i<capabilities.size();++i) {
  1377. json &cap = capabilities[i];
  1378. if (cap.is_object()) {
  1379. const uint64_t id = OSUtils::jsonInt(cap["id"],0ULL) & 0xffffffffULL;
  1380. capsById[id] = &cap;
  1381. if ((newMember)&&(OSUtils::jsonBool(cap["default"],false))) {
  1382. bool have = false;
  1383. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1384. if (id == (OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL)) {
  1385. have = true;
  1386. break;
  1387. }
  1388. }
  1389. if (!have)
  1390. memberCapabilities.push_back(id);
  1391. }
  1392. }
  1393. }
  1394. }
  1395. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1396. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL;
  1397. std::map< uint64_t,json * >::const_iterator ctmp = capsById.find(capId);
  1398. if (ctmp != capsById.end()) {
  1399. json *cap = ctmp->second;
  1400. if ((cap)&&(cap->is_object())&&(!cap->empty())) {
  1401. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1402. unsigned int caprc = 0;
  1403. json &caprj = (*cap)["rules"];
  1404. if ((caprj.is_array())&&(!caprj.empty())) {
  1405. for(unsigned long j=0;j<caprj.size();++j) {
  1406. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1407. break;
  1408. if (_parseRule(caprj[j],capr[caprc]))
  1409. ++caprc;
  1410. }
  1411. }
  1412. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  1413. if (nc->capabilities[nc->capabilityCount].sign(_signingId,identity.address()))
  1414. ++nc->capabilityCount;
  1415. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1416. break;
  1417. }
  1418. }
  1419. }
  1420. std::map< uint32_t,uint32_t > memberTagsById;
  1421. if (memberTags.is_array()) {
  1422. for(unsigned long i=0;i<memberTags.size();++i) {
  1423. json &t = memberTags[i];
  1424. if ((t.is_array())&&(t.size() == 2))
  1425. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1],0ULL) & 0xffffffffULL);
  1426. }
  1427. }
  1428. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1429. for(unsigned long i=0;i<tags.size();++i) {
  1430. json &t = tags[i];
  1431. if (t.is_object()) {
  1432. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"],0) & 0xffffffffULL);
  1433. json &dfl = t["default"];
  1434. if ((dfl.is_number())&&(memberTagsById.find(id) == memberTagsById.end())) {
  1435. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl,0) & 0xffffffffULL);
  1436. json mt = json::array();
  1437. mt.push_back(id);
  1438. mt.push_back(dfl);
  1439. memberTags.push_back(mt); // add default to member tags if not present
  1440. }
  1441. }
  1442. }
  1443. }
  1444. for(std::map< uint32_t,uint32_t >::const_iterator t(memberTagsById.begin());t!=memberTagsById.end();++t) {
  1445. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1446. break;
  1447. nc->tags[nc->tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  1448. if (nc->tags[nc->tagCount].sign(_signingId))
  1449. ++nc->tagCount;
  1450. }
  1451. }
  1452. if (routes.is_array()) {
  1453. for(unsigned long i=0;i<routes.size();++i) {
  1454. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1455. break;
  1456. json &route = routes[i];
  1457. json &target = route["target"];
  1458. json &via = route["via"];
  1459. if (target.is_string()) {
  1460. const InetAddress t(target.get<std::string>().c_str());
  1461. InetAddress v;
  1462. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  1463. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  1464. ZT_VirtualNetworkRoute *r = &(nc->routes[nc->routeCount]);
  1465. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  1466. if (v.ss_family == t.ss_family)
  1467. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  1468. ++nc->routeCount;
  1469. }
  1470. }
  1471. }
  1472. }
  1473. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"],false);
  1474. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  1475. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1476. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  1477. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1478. }
  1479. if ((OSUtils::jsonBool(v6AssignMode["6plane"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1480. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  1481. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1482. }
  1483. }
  1484. bool haveManagedIpv4AutoAssignment = false;
  1485. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1486. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1487. if (ipAssignments.is_array()) {
  1488. for(unsigned long i=0;i<ipAssignments.size();++i) {
  1489. if (ipAssignments[i].is_string()) {
  1490. const std::string ips = ipAssignments[i];
  1491. InetAddress ip(ips.c_str());
  1492. int routedNetmaskBits = -1;
  1493. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1494. if (reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->containsAddress(ip)) {
  1495. const int nb = (int)(reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits());
  1496. if (nb > routedNetmaskBits)
  1497. routedNetmaskBits = nb;
  1498. }
  1499. }
  1500. if (routedNetmaskBits >= 0) {
  1501. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1502. ip.setPort(routedNetmaskBits);
  1503. nc->staticIps[nc->staticIpCount++] = ip;
  1504. }
  1505. if (ip.ss_family == AF_INET)
  1506. haveManagedIpv4AutoAssignment = true;
  1507. else if (ip.ss_family == AF_INET6)
  1508. haveManagedIpv6AutoAssignment = true;
  1509. }
  1510. }
  1511. }
  1512. } else {
  1513. ipAssignments = json::array();
  1514. }
  1515. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(OSUtils::jsonBool(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  1516. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  1517. json &pool = ipAssignmentPools[p];
  1518. if (pool.is_object()) {
  1519. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1520. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1521. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  1522. uint64_t s[2],e[2],x[2],xx[2];
  1523. memcpy(s,ipRangeStart.rawIpData(),16);
  1524. memcpy(e,ipRangeEnd.rawIpData(),16);
  1525. s[0] = Utils::ntoh(s[0]);
  1526. s[1] = Utils::ntoh(s[1]);
  1527. e[0] = Utils::ntoh(e[0]);
  1528. e[1] = Utils::ntoh(e[1]);
  1529. x[0] = s[0];
  1530. x[1] = s[1];
  1531. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  1532. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  1533. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1534. xx[0] = Utils::hton(x[0]);
  1535. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1536. } else {
  1537. // 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
  1538. Utils::getSecureRandom((void *)xx,16);
  1539. if ((e[0] > s[0]))
  1540. xx[0] %= (e[0] - s[0]);
  1541. else xx[0] = 0;
  1542. if ((e[1] > s[1]))
  1543. xx[1] %= (e[1] - s[1]);
  1544. else xx[1] = 0;
  1545. xx[0] = Utils::hton(x[0] + xx[0]);
  1546. xx[1] = Utils::hton(x[1] + xx[1]);
  1547. }
  1548. InetAddress ip6((const void *)xx,16,0);
  1549. // Check if this IP is within a local-to-Ethernet routed network
  1550. int routedNetmaskBits = 0;
  1551. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1552. 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)) )
  1553. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1554. }
  1555. // If it's routed, then try to claim and assign it and if successful end loop
  1556. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip6)) ) {
  1557. char tmpip[64];
  1558. const std::string ipStr(ip6.toIpString(tmpip));
  1559. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1560. ipAssignments.push_back(ipStr);
  1561. member["ipAssignments"] = ipAssignments;
  1562. ip6.setPort((unsigned int)routedNetmaskBits);
  1563. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1564. nc->staticIps[nc->staticIpCount++] = ip6;
  1565. haveManagedIpv6AutoAssignment = true;
  1566. break;
  1567. }
  1568. }
  1569. }
  1570. }
  1571. }
  1572. }
  1573. }
  1574. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(OSUtils::jsonBool(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  1575. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  1576. json &pool = ipAssignmentPools[p];
  1577. if (pool.is_object()) {
  1578. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1579. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1580. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  1581. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  1582. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  1583. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  1584. continue;
  1585. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1586. // Start with the LSB of the member's address
  1587. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1588. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  1589. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1590. ++ipTrialCounter;
  1591. if ((ip & 0x000000ff) == 0x000000ff) {
  1592. continue; // don't allow addresses that end in .255
  1593. }
  1594. // Check if this IP is within a local-to-Ethernet routed network
  1595. int routedNetmaskBits = -1;
  1596. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1597. if (nc->routes[rk].target.ss_family == AF_INET) {
  1598. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_addr.s_addr));
  1599. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_port));
  1600. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  1601. routedNetmaskBits = targetBits;
  1602. break;
  1603. }
  1604. }
  1605. }
  1606. // If it's routed, then try to claim and assign it and if successful end loop
  1607. const InetAddress ip4(Utils::hton(ip),0);
  1608. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip4)) ) {
  1609. char tmpip[64];
  1610. const std::string ipStr(ip4.toIpString(tmpip));
  1611. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1612. ipAssignments.push_back(ipStr);
  1613. member["ipAssignments"] = ipAssignments;
  1614. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1615. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc->staticIps[nc->staticIpCount++]));
  1616. v4ip->sin_family = AF_INET;
  1617. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  1618. v4ip->sin_addr.s_addr = Utils::hton(ip);
  1619. }
  1620. haveManagedIpv4AutoAssignment = true;
  1621. break;
  1622. }
  1623. }
  1624. }
  1625. }
  1626. }
  1627. }
  1628. }
  1629. if(dns.is_object()) {
  1630. std::string domain = OSUtils::jsonString(dns["domain"],"");
  1631. memcpy(nc->dns.domain, domain.c_str(), domain.size());
  1632. json &addrArray = dns["servers"];
  1633. if (addrArray.is_array()) {
  1634. for(unsigned int j = 0; j < addrArray.size() && j < ZT_MAX_DNS_SERVERS; ++j) {
  1635. json &addr = addrArray[j];
  1636. nc->dns.server_addr[j] = InetAddress(OSUtils::jsonString(addr,"").c_str());
  1637. }
  1638. }
  1639. } else {
  1640. dns = json::object();
  1641. }
  1642. // Issue a certificate of ownership for all static IPs
  1643. if (nc->staticIpCount) {
  1644. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
  1645. for(unsigned int i=0;i<nc->staticIpCount;++i)
  1646. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  1647. nc->certificatesOfOwnership[0].sign(_signingId);
  1648. nc->certificateOfOwnershipCount = 1;
  1649. }
  1650. CertificateOfMembership com(now,credentialtmd,nwid,identity);
  1651. if (com.sign(_signingId)) {
  1652. nc->com = com;
  1653. } else {
  1654. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR, nullptr, 0);
  1655. return;
  1656. }
  1657. DB::cleanMember(member);
  1658. _db.save(member,true);
  1659. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
  1660. }
  1661. void EmbeddedNetworkController::_startThreads()
  1662. {
  1663. std::lock_guard<std::mutex> l(_threads_l);
  1664. if (!_threads.empty())
  1665. return;
  1666. const long hwc = std::max((long)std::thread::hardware_concurrency(),(long)1);
  1667. for(long t=0;t<hwc;++t) {
  1668. _threads.emplace_back([this]() {
  1669. std::vector<_MemberStatusKey> expired;
  1670. nlohmann::json network, member;
  1671. for(;;) {
  1672. _RQEntry *qe = (_RQEntry *)0;
  1673. auto timedWaitResult = _queue.get(qe, 1000);
  1674. if (timedWaitResult == BlockingQueue<_RQEntry *>::STOP) {
  1675. break;
  1676. } else if (timedWaitResult == BlockingQueue<_RQEntry *>::OK) {
  1677. if (qe) {
  1678. try {
  1679. _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
  1680. } catch (std::exception &e) {
  1681. fprintf(stderr,"ERROR: exception in controller request handling thread: %s" ZT_EOL_S,e.what());
  1682. } catch ( ... ) {
  1683. fprintf(stderr,"ERROR: exception in controller request handling thread: unknown exception" ZT_EOL_S);
  1684. }
  1685. delete qe;
  1686. }
  1687. }
  1688. expired.clear();
  1689. int64_t now = OSUtils::now();
  1690. {
  1691. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1692. for(auto s=_expiringSoon.begin();s!=_expiringSoon.end();) {
  1693. const int64_t when = s->first;
  1694. if (when <= now) {
  1695. // The user may have re-authorized, so we must actually look it up and check.
  1696. network.clear();
  1697. member.clear();
  1698. if (_db.get(s->second.networkId, network, s->second.nodeId, member)) {
  1699. int64_t authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1700. if (authenticationExpiryTime <= now) {
  1701. expired.push_back(s->second);
  1702. }
  1703. }
  1704. _expiringSoon.erase(s++);
  1705. } else {
  1706. // Don't bother going further into the future than necessary.
  1707. break;
  1708. }
  1709. }
  1710. }
  1711. for(auto e=expired.begin();e!=expired.end();++e) {
  1712. onNetworkMemberDeauthorize(nullptr, e->networkId, e->nodeId);
  1713. }
  1714. }
  1715. });
  1716. }
  1717. }
  1718. } // namespace ZeroTier