2
0

EmbeddedNetworkController.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  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. #ifdef ZT_DEBUG
  1319. fprintf(stderr, "copying issuerURL to nc: %s\n", info.issuerURL.c_str());
  1320. #endif
  1321. Utils::scopy(nc->issuerURL, sizeof(nc->issuerURL), info.issuerURL.c_str());
  1322. }
  1323. if (!info.ssoNonce.empty()) {
  1324. Utils::scopy(nc->ssoNonce, sizeof(nc->ssoNonce), info.ssoNonce.c_str());
  1325. }
  1326. if (!info.ssoState.empty()) {
  1327. Utils::scopy(nc->ssoState, sizeof(nc->ssoState), info.ssoState.c_str());
  1328. }
  1329. if (!info.ssoClientID.empty()) {
  1330. Utils::scopy(nc->ssoClientID, sizeof(nc->ssoClientID), info.ssoClientID.c_str());
  1331. }
  1332. }
  1333. std::string rtt(OSUtils::jsonString(member["remoteTraceTarget"],""));
  1334. if (rtt.length() == 10) {
  1335. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1336. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(member["remoteTraceLevel"],0ULL);
  1337. } else {
  1338. rtt = OSUtils::jsonString(network["remoteTraceTarget"],"");
  1339. if (rtt.length() == 10) {
  1340. nc->remoteTraceTarget = Address(Utils::hexStrToU64(rtt.c_str()));
  1341. } else {
  1342. nc->remoteTraceTarget.zero();
  1343. }
  1344. nc->remoteTraceLevel = (Trace::Level)OSUtils::jsonInt(network["remoteTraceLevel"],0ULL);
  1345. }
  1346. for(std::vector<Address>::const_iterator ab(ns.activeBridges.begin());ab!=ns.activeBridges.end();++ab)
  1347. nc->addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  1348. json &v4AssignMode = network["v4AssignMode"];
  1349. json &v6AssignMode = network["v6AssignMode"];
  1350. json &ipAssignmentPools = network["ipAssignmentPools"];
  1351. json &routes = network["routes"];
  1352. json &rules = network["rules"];
  1353. json &capabilities = network["capabilities"];
  1354. json &tags = network["tags"];
  1355. json &memberCapabilities = member["capabilities"];
  1356. json &memberTags = member["tags"];
  1357. json &dns = network["dns"];
  1358. //fprintf(stderr, "IP Assignment Pools for Network %s: %s\n", nwids, OSUtils::jsonDump(ipAssignmentPools, 2).c_str());
  1359. if (metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_RULES_ENGINE_REV,0) <= 0) {
  1360. // Old versions with no rules engine support get an allow everything rule.
  1361. // Since rules are enforced bidirectionally, newer versions *will* still
  1362. // enforce rules on the inbound side.
  1363. nc->ruleCount = 1;
  1364. nc->rules[0].t = ZT_NETWORK_RULE_ACTION_ACCEPT;
  1365. } else {
  1366. if (rules.is_array()) {
  1367. for(unsigned long i=0;i<rules.size();++i) {
  1368. if (nc->ruleCount >= ZT_MAX_NETWORK_RULES)
  1369. break;
  1370. if (_parseRule(rules[i],nc->rules[nc->ruleCount]))
  1371. ++nc->ruleCount;
  1372. }
  1373. }
  1374. std::map< uint64_t,json * > capsById;
  1375. if (!memberCapabilities.is_array())
  1376. memberCapabilities = json::array();
  1377. if (capabilities.is_array()) {
  1378. for(unsigned long i=0;i<capabilities.size();++i) {
  1379. json &cap = capabilities[i];
  1380. if (cap.is_object()) {
  1381. const uint64_t id = OSUtils::jsonInt(cap["id"],0ULL) & 0xffffffffULL;
  1382. capsById[id] = &cap;
  1383. if ((newMember)&&(OSUtils::jsonBool(cap["default"],false))) {
  1384. bool have = false;
  1385. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1386. if (id == (OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL)) {
  1387. have = true;
  1388. break;
  1389. }
  1390. }
  1391. if (!have)
  1392. memberCapabilities.push_back(id);
  1393. }
  1394. }
  1395. }
  1396. }
  1397. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  1398. const uint64_t capId = OSUtils::jsonInt(memberCapabilities[i],0ULL) & 0xffffffffULL;
  1399. std::map< uint64_t,json * >::const_iterator ctmp = capsById.find(capId);
  1400. if (ctmp != capsById.end()) {
  1401. json *cap = ctmp->second;
  1402. if ((cap)&&(cap->is_object())&&(!cap->empty())) {
  1403. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  1404. unsigned int caprc = 0;
  1405. json &caprj = (*cap)["rules"];
  1406. if ((caprj.is_array())&&(!caprj.empty())) {
  1407. for(unsigned long j=0;j<caprj.size();++j) {
  1408. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  1409. break;
  1410. if (_parseRule(caprj[j],capr[caprc]))
  1411. ++caprc;
  1412. }
  1413. }
  1414. nc->capabilities[nc->capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  1415. if (nc->capabilities[nc->capabilityCount].sign(_signingId,identity.address()))
  1416. ++nc->capabilityCount;
  1417. if (nc->capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  1418. break;
  1419. }
  1420. }
  1421. }
  1422. std::map< uint32_t,uint32_t > memberTagsById;
  1423. if (memberTags.is_array()) {
  1424. for(unsigned long i=0;i<memberTags.size();++i) {
  1425. json &t = memberTags[i];
  1426. if ((t.is_array())&&(t.size() == 2))
  1427. memberTagsById[(uint32_t)(OSUtils::jsonInt(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(OSUtils::jsonInt(t[1],0ULL) & 0xffffffffULL);
  1428. }
  1429. }
  1430. if (tags.is_array()) { // check network tags array for defaults that are not present in member tags
  1431. for(unsigned long i=0;i<tags.size();++i) {
  1432. json &t = tags[i];
  1433. if (t.is_object()) {
  1434. const uint32_t id = (uint32_t)(OSUtils::jsonInt(t["id"],0) & 0xffffffffULL);
  1435. json &dfl = t["default"];
  1436. if ((dfl.is_number())&&(memberTagsById.find(id) == memberTagsById.end())) {
  1437. memberTagsById[id] = (uint32_t)(OSUtils::jsonInt(dfl,0) & 0xffffffffULL);
  1438. json mt = json::array();
  1439. mt.push_back(id);
  1440. mt.push_back(dfl);
  1441. memberTags.push_back(mt); // add default to member tags if not present
  1442. }
  1443. }
  1444. }
  1445. }
  1446. for(std::map< uint32_t,uint32_t >::const_iterator t(memberTagsById.begin());t!=memberTagsById.end();++t) {
  1447. if (nc->tagCount >= ZT_MAX_NETWORK_TAGS)
  1448. break;
  1449. nc->tags[nc->tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  1450. if (nc->tags[nc->tagCount].sign(_signingId))
  1451. ++nc->tagCount;
  1452. }
  1453. }
  1454. if (routes.is_array()) {
  1455. for(unsigned long i=0;i<routes.size();++i) {
  1456. if (nc->routeCount >= ZT_MAX_NETWORK_ROUTES)
  1457. break;
  1458. json &route = routes[i];
  1459. json &target = route["target"];
  1460. json &via = route["via"];
  1461. if (target.is_string()) {
  1462. const InetAddress t(target.get<std::string>().c_str());
  1463. InetAddress v;
  1464. if (via.is_string()) v.fromString(via.get<std::string>().c_str());
  1465. if ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) {
  1466. ZT_VirtualNetworkRoute *r = &(nc->routes[nc->routeCount]);
  1467. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  1468. if (v.ss_family == t.ss_family)
  1469. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  1470. ++nc->routeCount;
  1471. }
  1472. }
  1473. }
  1474. }
  1475. const bool noAutoAssignIps = OSUtils::jsonBool(member["noAutoAssignIps"],false);
  1476. if ((v6AssignMode.is_object())&&(!noAutoAssignIps)) {
  1477. if ((OSUtils::jsonBool(v6AssignMode["rfc4193"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1478. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  1479. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1480. }
  1481. if ((OSUtils::jsonBool(v6AssignMode["6plane"],false))&&(nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  1482. nc->staticIps[nc->staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  1483. nc->flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  1484. }
  1485. }
  1486. bool haveManagedIpv4AutoAssignment = false;
  1487. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  1488. json ipAssignments = member["ipAssignments"]; // we want to make a copy
  1489. if (ipAssignments.is_array()) {
  1490. for(unsigned long i=0;i<ipAssignments.size();++i) {
  1491. if (ipAssignments[i].is_string()) {
  1492. const std::string ips = ipAssignments[i];
  1493. InetAddress ip(ips.c_str());
  1494. int routedNetmaskBits = -1;
  1495. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1496. if (reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->containsAddress(ip)) {
  1497. const int nb = (int)(reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits());
  1498. if (nb > routedNetmaskBits)
  1499. routedNetmaskBits = nb;
  1500. }
  1501. }
  1502. if (routedNetmaskBits >= 0) {
  1503. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1504. ip.setPort(routedNetmaskBits);
  1505. nc->staticIps[nc->staticIpCount++] = ip;
  1506. }
  1507. if (ip.ss_family == AF_INET)
  1508. haveManagedIpv4AutoAssignment = true;
  1509. else if (ip.ss_family == AF_INET6)
  1510. haveManagedIpv6AutoAssignment = true;
  1511. }
  1512. }
  1513. }
  1514. } else {
  1515. ipAssignments = json::array();
  1516. }
  1517. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(OSUtils::jsonBool(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!noAutoAssignIps) ) {
  1518. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  1519. json &pool = ipAssignmentPools[p];
  1520. if (pool.is_object()) {
  1521. InetAddress ipRangeStart(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1522. InetAddress ipRangeEnd(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1523. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  1524. uint64_t s[2],e[2],x[2],xx[2];
  1525. memcpy(s,ipRangeStart.rawIpData(),16);
  1526. memcpy(e,ipRangeEnd.rawIpData(),16);
  1527. s[0] = Utils::ntoh(s[0]);
  1528. s[1] = Utils::ntoh(s[1]);
  1529. e[0] = Utils::ntoh(e[0]);
  1530. e[1] = Utils::ntoh(e[1]);
  1531. x[0] = s[0];
  1532. x[1] = s[1];
  1533. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  1534. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  1535. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  1536. xx[0] = Utils::hton(x[0]);
  1537. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  1538. } else {
  1539. // 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
  1540. Utils::getSecureRandom((void *)xx,16);
  1541. if ((e[0] > s[0]))
  1542. xx[0] %= (e[0] - s[0]);
  1543. else xx[0] = 0;
  1544. if ((e[1] > s[1]))
  1545. xx[1] %= (e[1] - s[1]);
  1546. else xx[1] = 0;
  1547. xx[0] = Utils::hton(x[0] + xx[0]);
  1548. xx[1] = Utils::hton(x[1] + xx[1]);
  1549. }
  1550. InetAddress ip6((const void *)xx,16,0);
  1551. // Check if this IP is within a local-to-Ethernet routed network
  1552. int routedNetmaskBits = 0;
  1553. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1554. 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)) )
  1555. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc->routes[rk].target))->netmaskBits();
  1556. }
  1557. // If it's routed, then try to claim and assign it and if successful end loop
  1558. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip6)) ) {
  1559. char tmpip[64];
  1560. const std::string ipStr(ip6.toIpString(tmpip));
  1561. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1562. ipAssignments.push_back(ipStr);
  1563. member["ipAssignments"] = ipAssignments;
  1564. ip6.setPort((unsigned int)routedNetmaskBits);
  1565. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  1566. nc->staticIps[nc->staticIpCount++] = ip6;
  1567. haveManagedIpv6AutoAssignment = true;
  1568. break;
  1569. }
  1570. }
  1571. }
  1572. }
  1573. }
  1574. }
  1575. }
  1576. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(OSUtils::jsonBool(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!noAutoAssignIps) ) {
  1577. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  1578. json &pool = ipAssignmentPools[p];
  1579. if (pool.is_object()) {
  1580. InetAddress ipRangeStartIA(OSUtils::jsonString(pool["ipRangeStart"],"").c_str());
  1581. InetAddress ipRangeEndIA(OSUtils::jsonString(pool["ipRangeEnd"],"").c_str());
  1582. if ( (ipRangeStartIA.ss_family == AF_INET) && (ipRangeEndIA.ss_family == AF_INET) ) {
  1583. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStartIA)->sin_addr.s_addr));
  1584. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEndIA)->sin_addr.s_addr));
  1585. if ((ipRangeEnd < ipRangeStart)||(ipRangeStart == 0))
  1586. continue;
  1587. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  1588. // Start with the LSB of the member's address
  1589. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  1590. for(uint32_t k=ipRangeStart,trialCount=0;((k<=ipRangeEnd)&&(trialCount < 1000));++k,++trialCount) {
  1591. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  1592. ++ipTrialCounter;
  1593. if ((ip & 0x000000ff) == 0x000000ff) {
  1594. continue; // don't allow addresses that end in .255
  1595. }
  1596. // Check if this IP is within a local-to-Ethernet routed network
  1597. int routedNetmaskBits = -1;
  1598. for(unsigned int rk=0;rk<nc->routeCount;++rk) {
  1599. if (nc->routes[rk].target.ss_family == AF_INET) {
  1600. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_addr.s_addr));
  1601. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc->routes[rk].target))->sin_port));
  1602. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  1603. routedNetmaskBits = targetBits;
  1604. break;
  1605. }
  1606. }
  1607. }
  1608. // If it's routed, then try to claim and assign it and if successful end loop
  1609. const InetAddress ip4(Utils::hton(ip),0);
  1610. if ( (routedNetmaskBits > 0) && (!std::binary_search(ns.allocatedIps.begin(),ns.allocatedIps.end(),ip4)) ) {
  1611. char tmpip[64];
  1612. const std::string ipStr(ip4.toIpString(tmpip));
  1613. if (std::find(ipAssignments.begin(),ipAssignments.end(),ipStr) == ipAssignments.end()) {
  1614. ipAssignments.push_back(ipStr);
  1615. member["ipAssignments"] = ipAssignments;
  1616. if (nc->staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  1617. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc->staticIps[nc->staticIpCount++]));
  1618. v4ip->sin_family = AF_INET;
  1619. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  1620. v4ip->sin_addr.s_addr = Utils::hton(ip);
  1621. }
  1622. haveManagedIpv4AutoAssignment = true;
  1623. break;
  1624. }
  1625. }
  1626. }
  1627. }
  1628. }
  1629. }
  1630. }
  1631. if(dns.is_object()) {
  1632. std::string domain = OSUtils::jsonString(dns["domain"],"");
  1633. memcpy(nc->dns.domain, domain.c_str(), domain.size());
  1634. json &addrArray = dns["servers"];
  1635. if (addrArray.is_array()) {
  1636. for(unsigned int j = 0; j < addrArray.size() && j < ZT_MAX_DNS_SERVERS; ++j) {
  1637. json &addr = addrArray[j];
  1638. nc->dns.server_addr[j] = InetAddress(OSUtils::jsonString(addr,"").c_str());
  1639. }
  1640. }
  1641. } else {
  1642. dns = json::object();
  1643. }
  1644. // Issue a certificate of ownership for all static IPs
  1645. if (nc->staticIpCount) {
  1646. nc->certificatesOfOwnership[0] = CertificateOfOwnership(nwid,now,identity.address(),1);
  1647. for(unsigned int i=0;i<nc->staticIpCount;++i)
  1648. nc->certificatesOfOwnership[0].addThing(nc->staticIps[i]);
  1649. nc->certificatesOfOwnership[0].sign(_signingId);
  1650. nc->certificateOfOwnershipCount = 1;
  1651. }
  1652. CertificateOfMembership com(now,credentialtmd,nwid,identity);
  1653. if (com.sign(_signingId)) {
  1654. nc->com = com;
  1655. } else {
  1656. _sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_INTERNAL_SERVER_ERROR, nullptr, 0);
  1657. return;
  1658. }
  1659. DB::cleanMember(member);
  1660. _db.save(member,true);
  1661. _sender->ncSendConfig(nwid,requestPacketId,identity.address(),*(nc.get()),metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_VERSION,0) < 6);
  1662. }
  1663. void EmbeddedNetworkController::_startThreads()
  1664. {
  1665. std::lock_guard<std::mutex> l(_threads_l);
  1666. if (!_threads.empty())
  1667. return;
  1668. const long hwc = std::max((long)std::thread::hardware_concurrency(),(long)1);
  1669. for(long t=0;t<hwc;++t) {
  1670. _threads.emplace_back([this]() {
  1671. std::vector<_MemberStatusKey> expired;
  1672. nlohmann::json network, member;
  1673. for(;;) {
  1674. _RQEntry *qe = (_RQEntry *)0;
  1675. auto timedWaitResult = _queue.get(qe, 1000);
  1676. if (timedWaitResult == BlockingQueue<_RQEntry *>::STOP) {
  1677. break;
  1678. } else if (timedWaitResult == BlockingQueue<_RQEntry *>::OK) {
  1679. if (qe) {
  1680. try {
  1681. _request(qe->nwid,qe->fromAddr,qe->requestPacketId,qe->identity,qe->metaData);
  1682. } catch (std::exception &e) {
  1683. fprintf(stderr,"ERROR: exception in controller request handling thread: %s" ZT_EOL_S,e.what());
  1684. } catch ( ... ) {
  1685. fprintf(stderr,"ERROR: exception in controller request handling thread: unknown exception" ZT_EOL_S);
  1686. }
  1687. delete qe;
  1688. }
  1689. }
  1690. expired.clear();
  1691. int64_t now = OSUtils::now();
  1692. {
  1693. std::lock_guard<std::mutex> l(_expiringSoon_l);
  1694. for(auto s=_expiringSoon.begin();s!=_expiringSoon.end();) {
  1695. const int64_t when = s->first;
  1696. if (when <= now) {
  1697. // The user may have re-authorized, so we must actually look it up and check.
  1698. network.clear();
  1699. member.clear();
  1700. if (_db.get(s->second.networkId, network, s->second.nodeId, member)) {
  1701. int64_t authenticationExpiryTime = (int64_t)OSUtils::jsonInt(member["authenticationExpiryTime"], 0);
  1702. if (authenticationExpiryTime <= now) {
  1703. expired.push_back(s->second);
  1704. }
  1705. }
  1706. _expiringSoon.erase(s++);
  1707. } else {
  1708. // Don't bother going further into the future than necessary.
  1709. break;
  1710. }
  1711. }
  1712. }
  1713. for(auto e=expired.begin();e!=expired.end();++e) {
  1714. onNetworkMemberDeauthorize(nullptr, e->networkId, e->nodeId);
  1715. }
  1716. }
  1717. });
  1718. }
  1719. }
  1720. } // namespace ZeroTier