EmbeddedNetworkController.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include <stdint.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <time.h>
  23. #include <sys/time.h>
  24. #include <sys/types.h>
  25. #include <algorithm>
  26. #include <utility>
  27. #include <stdexcept>
  28. #include <set>
  29. #include <map>
  30. #include "../include/ZeroTierOne.h"
  31. #include "../node/Constants.hpp"
  32. #include "EmbeddedNetworkController.hpp"
  33. #include "../node/Node.hpp"
  34. #include "../node/Utils.hpp"
  35. #include "../node/CertificateOfMembership.hpp"
  36. #include "../node/NetworkConfig.hpp"
  37. #include "../node/Dictionary.hpp"
  38. #include "../node/InetAddress.hpp"
  39. #include "../node/MAC.hpp"
  40. #include "../node/Address.hpp"
  41. using json = nlohmann::json;
  42. // API version reported via JSON control plane
  43. #define ZT_NETCONF_CONTROLLER_API_VERSION 3
  44. // Number of requests to remember in member history
  45. #define ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH 16
  46. // Min duration between requests for an address/nwid combo to prevent floods
  47. #define ZT_NETCONF_MIN_REQUEST_PERIOD 1000
  48. // Nodes are considered active if they've queried in less than this long
  49. #define ZT_NETCONF_NODE_ACTIVE_THRESHOLD ((ZT_NETWORK_AUTOCONF_DELAY * 2) + 5000)
  50. namespace ZeroTier {
  51. // Get JSON values as unsigned integers, strings, or booleans, doing type conversion if possible
  52. static uint64_t _jI(const json &jv,const uint64_t dfl)
  53. {
  54. if (jv.is_number()) {
  55. return (uint64_t)jv;
  56. } else if (jv.is_string()) {
  57. std::string s = jv;
  58. return Utils::strToU64(s.c_str());
  59. } else if (jv.is_boolean()) {
  60. return ((bool)jv ? 1ULL : 0ULL);
  61. }
  62. return dfl;
  63. }
  64. static bool _jB(const json &jv,const bool dfl)
  65. {
  66. if (jv.is_boolean()) {
  67. return (bool)jv;
  68. } else if (jv.is_number()) {
  69. return ((uint64_t)jv > 0ULL);
  70. } else if (jv.is_string()) {
  71. std::string s = jv;
  72. if (s.length() > 0) {
  73. switch(s[0]) {
  74. case 't':
  75. case 'T':
  76. case '1':
  77. return true;
  78. }
  79. }
  80. return false;
  81. }
  82. return dfl;
  83. }
  84. static std::string _jS(const json &jv,const char *dfl)
  85. {
  86. if (jv.is_string()) {
  87. return jv;
  88. } else if (jv.is_number()) {
  89. char tmp[64];
  90. Utils::snprintf(tmp,sizeof(tmp),"%llu",(uint64_t)jv);
  91. return tmp;
  92. } else if (jv.is_boolean()) {
  93. return ((bool)jv ? std::string("1") : std::string("0"));
  94. }
  95. return std::string((dfl) ? dfl : "");
  96. }
  97. static json _renderRule(ZT_VirtualNetworkRule &rule)
  98. {
  99. char tmp[128];
  100. json r = json::object();
  101. r["not"] = ((rule.t & 0x80) != 0);
  102. switch((rule.t) & 0x7f) {
  103. case ZT_NETWORK_RULE_ACTION_DROP:
  104. r["type"] = "ACTION_DROP";
  105. break;
  106. case ZT_NETWORK_RULE_ACTION_ACCEPT:
  107. r["type"] = "ACTION_ACCEPT";
  108. break;
  109. case ZT_NETWORK_RULE_ACTION_TEE:
  110. r["type"] = "ACTION_TEE";
  111. r["zt"] = Address(rule.v.zt).toString();
  112. break;
  113. case ZT_NETWORK_RULE_ACTION_REDIRECT:
  114. r["type"] = "ACTION_REDIRECT";
  115. r["zt"] = Address(rule.v.zt).toString();
  116. break;
  117. case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
  118. r["type"] = "MATCH_SOURCE_ZEROTIER_ADDRESS";
  119. r["zt"] = Address(rule.v.zt).toString();
  120. break;
  121. case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
  122. r["type"] = "MATCH_DEST_ZEROTIER_ADDRESS";
  123. r["zt"] = Address(rule.v.zt).toString();
  124. break;
  125. case ZT_NETWORK_RULE_MATCH_VLAN_ID:
  126. r["type"] = "MATCH_VLAN_ID";
  127. r["vlanId"] = (uint64_t)rule.v.vlanId;
  128. break;
  129. case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
  130. r["type"] = "MATCH_VLAN_PCP";
  131. r["vlanPcp"] = (uint64_t)rule.v.vlanPcp;
  132. break;
  133. case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
  134. r["type"] = "MATCH_VLAN_DEI";
  135. r["vlanDei"] = (uint64_t)rule.v.vlanDei;
  136. break;
  137. case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
  138. r["type"] = "MATCH_ETHERTYPE";
  139. r["etherType"] = (uint64_t)rule.v.etherType;
  140. break;
  141. case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
  142. r["type"] = "MATCH_MAC_SOURCE";
  143. Utils::snprintf(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]);
  144. r["mac"] = tmp;
  145. break;
  146. case ZT_NETWORK_RULE_MATCH_MAC_DEST:
  147. r["type"] = "MATCH_MAC_DEST";
  148. Utils::snprintf(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]);
  149. r["mac"] = tmp;
  150. break;
  151. case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
  152. r["type"] = "MATCH_IPV4_SOURCE";
  153. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  154. break;
  155. case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
  156. r["type"] = "MATCH_IPV4_DEST";
  157. r["ip"] = InetAddress(&(rule.v.ipv4.ip),4,(unsigned int)rule.v.ipv4.mask).toString();
  158. break;
  159. case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
  160. r["type"] = "MATCH_IPV6_SOURCE";
  161. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  162. break;
  163. case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
  164. r["type"] = "MATCH_IPV6_DEST";
  165. r["ip"] = InetAddress(rule.v.ipv6.ip,16,(unsigned int)rule.v.ipv6.mask).toString();
  166. break;
  167. case ZT_NETWORK_RULE_MATCH_IP_TOS:
  168. r["type"] = "MATCH_IP_TOS";
  169. r["ipTos"] = (uint64_t)rule.v.ipTos;
  170. break;
  171. case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
  172. r["type"] = "MATCH_IP_PROTOCOL";
  173. r["ipProtocol"] = (uint64_t)rule.v.ipProtocol;
  174. break;
  175. case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
  176. r["type"] = "MATCH_IP_SOURCE_PORT_RANGE";
  177. r["start"] = (uint64_t)rule.v.port[0];
  178. r["end"] = (uint64_t)rule.v.port[1];
  179. break;
  180. case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
  181. r["type"] = "MATCH_IP_DEST_PORT_RANGE";
  182. r["start"] = (uint64_t)rule.v.port[0];
  183. r["end"] = (uint64_t)rule.v.port[1];
  184. break;
  185. case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS:
  186. r["type"] = "MATCH_CHARACTERISTICS";
  187. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics[0]);
  188. r["mask"] = tmp;
  189. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",rule.v.characteristics[1]);
  190. r["value"] = tmp;
  191. break;
  192. case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
  193. r["type"] = "MATCH_FRAME_SIZE_RANGE";
  194. r["start"] = (uint64_t)rule.v.frameSize[0];
  195. r["end"] = (uint64_t)rule.v.frameSize[1];
  196. break;
  197. case ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS:
  198. r["type"] = "MATCH_TAGS_SAMENESS";
  199. r["id"] = (uint64_t)rule.v.tag.id;
  200. r["value"] = (uint64_t)rule.v.tag.value;
  201. break;
  202. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
  203. r["type"] = "MATCH_TAGS_BITWISE_AND";
  204. r["id"] = (uint64_t)rule.v.tag.id;
  205. r["value"] = (uint64_t)rule.v.tag.value;
  206. break;
  207. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
  208. r["type"] = "MATCH_TAGS_BITWISE_OR";
  209. r["id"] = (uint64_t)rule.v.tag.id;
  210. r["value"] = (uint64_t)rule.v.tag.value;
  211. break;
  212. case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
  213. r["type"] = "MATCH_TAGS_BITWISE_XOR";
  214. r["id"] = (uint64_t)rule.v.tag.id;
  215. r["value"] = (uint64_t)rule.v.tag.value;
  216. break;
  217. }
  218. return r;
  219. }
  220. static bool _parseRule(const json &r,ZT_VirtualNetworkRule &rule)
  221. {
  222. if (r.is_object())
  223. return false;
  224. std::string t = r["type"];
  225. memset(&rule,0,sizeof(ZT_VirtualNetworkRule));
  226. if (_jB(r["not"],false))
  227. rule.t = 0x80;
  228. else rule.t = 0x00;
  229. if (t == "ACTION_DROP") {
  230. rule.t |= ZT_NETWORK_RULE_ACTION_DROP;
  231. return true;
  232. } else if (t == "ACTION_ACCEPT") {
  233. rule.t |= ZT_NETWORK_RULE_ACTION_ACCEPT;
  234. return true;
  235. } else if (t == "ACTION_TEE") {
  236. rule.t |= ZT_NETWORK_RULE_ACTION_TEE;
  237. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  238. return true;
  239. } else if (t == "ACTION_REDIRECT") {
  240. rule.t |= ZT_NETWORK_RULE_ACTION_REDIRECT;
  241. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  242. return true;
  243. } else if (t == "MATCH_SOURCE_ZEROTIER_ADDRESS") {
  244. rule.t |= ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS;
  245. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  246. return true;
  247. } else if (t == "MATCH_DEST_ZEROTIER_ADDRESS") {
  248. rule.t |= ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS;
  249. rule.v.zt = Utils::hexStrToU64(_jS(r["zt"],"0").c_str()) & 0xffffffffffULL;
  250. return true;
  251. } else if (t == "MATCH_VLAN_ID") {
  252. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_ID;
  253. rule.v.vlanId = (uint16_t)(_jI(r["vlanId"],0ULL) & 0xffffULL);
  254. return true;
  255. } else if (t == "MATCH_VLAN_PCP") {
  256. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_PCP;
  257. rule.v.vlanPcp = (uint8_t)(_jI(r["vlanPcp"],0ULL) & 0xffULL);
  258. return true;
  259. } else if (t == "MATCH_VLAN_DEI") {
  260. rule.t |= ZT_NETWORK_RULE_MATCH_VLAN_DEI;
  261. rule.v.vlanDei = (uint8_t)(_jI(r["vlanDei"],0ULL) & 0xffULL);
  262. return true;
  263. } else if (t == "MATCH_ETHERTYPE") {
  264. rule.t |= ZT_NETWORK_RULE_MATCH_ETHERTYPE;
  265. rule.v.etherType = (uint16_t)(_jI(r["etherType"],0ULL) & 0xffffULL);
  266. return true;
  267. } else if (t == "MATCH_MAC_SOURCE") {
  268. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_SOURCE;
  269. const std::string mac(_jS(r["mac"],"0"));
  270. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  271. return true;
  272. } else if (t == "MATCH_MAC_DEST") {
  273. rule.t |= ZT_NETWORK_RULE_MATCH_MAC_DEST;
  274. const std::string mac(_jS(r["mac"],"0"));
  275. Utils::unhex(mac.c_str(),(unsigned int)mac.length(),rule.v.mac,6);
  276. return true;
  277. } else if (t == "MATCH_IPV4_SOURCE") {
  278. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_SOURCE;
  279. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  280. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  281. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  282. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  283. return true;
  284. } else if (t == "MATCH_IPV4_DEST") {
  285. rule.t |= ZT_NETWORK_RULE_MATCH_IPV4_DEST;
  286. InetAddress ip(_jS(r["ip"],"0.0.0.0"));
  287. rule.v.ipv4.ip = reinterpret_cast<struct sockaddr_in *>(&ip)->sin_addr.s_addr;
  288. rule.v.ipv4.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in *>(&ip)->sin_port) & 0xff;
  289. if (rule.v.ipv4.mask > 32) rule.v.ipv4.mask = 32;
  290. return true;
  291. } else if (t == "MATCH_IPV6_SOURCE") {
  292. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_SOURCE;
  293. InetAddress ip(_jS(r["ip"],"::0"));
  294. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  295. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  296. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  297. return true;
  298. } else if (t == "MATCH_IPV6_DEST") {
  299. rule.t |= ZT_NETWORK_RULE_MATCH_IPV6_DEST;
  300. InetAddress ip(_jS(r["ip"],"::0"));
  301. memcpy(rule.v.ipv6.ip,reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_addr.s6_addr,16);
  302. rule.v.ipv6.mask = Utils::ntoh(reinterpret_cast<struct sockaddr_in6 *>(&ip)->sin6_port) & 0xff;
  303. if (rule.v.ipv6.mask > 128) rule.v.ipv6.mask = 128;
  304. return true;
  305. } else if (t == "MATCH_IP_TOS") {
  306. rule.t |= ZT_NETWORK_RULE_MATCH_IP_TOS;
  307. rule.v.ipTos = (uint8_t)(_jI(r["ipTos"],0ULL) & 0xffULL);
  308. return true;
  309. } else if (t == "MATCH_IP_PROTOCOL") {
  310. rule.t |= ZT_NETWORK_RULE_MATCH_IP_PROTOCOL;
  311. rule.v.ipProtocol = (uint8_t)(_jI(r["ipProtocol"],0ULL) & 0xffULL);
  312. return true;
  313. } else if (t == "MATCH_IP_SOURCE_PORT_RANGE") {
  314. rule.t |= ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE;
  315. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  316. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  317. return true;
  318. } else if (t == "MATCH_IP_DEST_PORT_RANGE") {
  319. rule.t |= ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE;
  320. rule.v.port[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  321. rule.v.port[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.port[0]) & 0xffffULL);
  322. return true;
  323. } else if (t == "MATCH_CHARACTERISTICS") {
  324. rule.t |= ZT_NETWORK_RULE_MATCH_CHARACTERISTICS;
  325. if (r.count("mask")) {
  326. auto v = r["mask"];
  327. if (v.is_number()) {
  328. rule.v.characteristics[0] = v;
  329. } else {
  330. std::string tmp = v;
  331. rule.v.characteristics[0] = Utils::hexStrToU64(tmp.c_str());
  332. }
  333. }
  334. if (r.count("value")) {
  335. auto v = r["value"];
  336. if (v.is_number()) {
  337. rule.v.characteristics[1] = v;
  338. } else {
  339. std::string tmp = v;
  340. rule.v.characteristics[1] = Utils::hexStrToU64(tmp.c_str());
  341. }
  342. }
  343. return true;
  344. } else if (t == "MATCH_FRAME_SIZE_RANGE") {
  345. rule.t |= ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE;
  346. rule.v.frameSize[0] = (uint16_t)(_jI(r["start"],0ULL) & 0xffffULL);
  347. rule.v.frameSize[1] = (uint16_t)(_jI(r["end"],(uint64_t)rule.v.frameSize[0]) & 0xffffULL);
  348. return true;
  349. } else if (t == "MATCH_TAGS_SAMENESS") {
  350. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_SAMENESS;
  351. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  352. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  353. return true;
  354. } else if (t == "MATCH_TAGS_BITWISE_AND") {
  355. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND;
  356. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  357. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  358. return true;
  359. } else if (t == "MATCH_TAGS_BITWISE_OR") {
  360. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR;
  361. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  362. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  363. return true;
  364. } else if (t == "MATCH_TAGS_BITWISE_XOR") {
  365. rule.t |= ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR;
  366. rule.v.tag.id = (uint32_t)(_jI(r["id"],0ULL) & 0xffffffffULL);
  367. rule.v.tag.value = (uint32_t)(_jI(r["value"],0ULL) & 0xffffffffULL);
  368. return true;
  369. }
  370. return false;
  371. }
  372. EmbeddedNetworkController::EmbeddedNetworkController(Node *node,const char *dbPath) :
  373. _node(node),
  374. _path(dbPath)
  375. {
  376. OSUtils::mkdir(dbPath);
  377. OSUtils::lockDownFile(dbPath,true); // networks might contain auth tokens, etc., so restrict directory permissions
  378. }
  379. EmbeddedNetworkController::~EmbeddedNetworkController()
  380. {
  381. }
  382. NetworkController::ResultCode EmbeddedNetworkController::doNetworkConfigRequest(const InetAddress &fromAddr,const Identity &signingId,const Identity &identity,uint64_t nwid,const Dictionary<ZT_NETWORKCONFIG_METADATA_DICT_CAPACITY> &metaData,NetworkConfig &nc)
  383. {
  384. if (((!signingId)||(!signingId.hasPrivate()))||(signingId.address().toInt() != (nwid >> 24))) {
  385. return NetworkController::NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  386. }
  387. const uint64_t now = OSUtils::now();
  388. // Check rate limit circuit breaker to prevent flooding
  389. {
  390. Mutex::Lock _l(_lastRequestTime_m);
  391. uint64_t &lrt = _lastRequestTime[std::pair<uint64_t,uint64_t>(identity.address().toInt(),nwid)];
  392. if ((now - lrt) <= ZT_NETCONF_MIN_REQUEST_PERIOD)
  393. return NetworkController::NETCONF_QUERY_IGNORE;
  394. lrt = now;
  395. }
  396. const json network(_readJson(_networkJP(nwid,false)));
  397. if (!network.size())
  398. return NetworkController::NETCONF_QUERY_OBJECT_NOT_FOUND;
  399. const std::string memberJP(_memberJP(nwid,identity.address(),true));
  400. json member(_readJson(memberJP));
  401. {
  402. std::string haveIdStr(_jS(member["identity"],""));
  403. if (haveIdStr.length() > 0) {
  404. // If we already know this member's identity perform a full compare. This prevents
  405. // a "collision" from being able to auth onto our network in place of an already
  406. // known member.
  407. try {
  408. if (Identity(haveIdStr.c_str()) != identity)
  409. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  410. } catch ( ... ) {
  411. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  412. }
  413. } else {
  414. // If we do not yet know this member's identity, learn it.
  415. member["identity"] = identity.toString(false);
  416. }
  417. }
  418. _initMember(member);
  419. // Make sure these are always present no matter what, and increment member revision since we will always at least log something
  420. member["id"] = identity.address().toString();
  421. member["address"] = member["id"];
  422. member["nwid"] = network["id"];
  423. member["lastModified"] = now;
  424. {
  425. auto revj = member["revision"];
  426. const uint64_t rev = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  427. member["revision"] = rev;
  428. }
  429. // Determine whether and how member is authorized
  430. const char *authorizedBy = (const char *)0;
  431. if (!_jB(network["private"],true)) {
  432. authorizedBy = "networkIsPublic";
  433. // If member already has an authorized field, leave it alone. That way its state is
  434. // preserved if the user toggles the network back to private. Otherwise set it to
  435. // true by default for new members of public nets.
  436. if (!member.count("authorized")) {
  437. member["authorized"] = true;
  438. member["lastAuthorizedTime"] = now;
  439. member["lastAuthorizedBy"] = authorizedBy;
  440. }
  441. } else if (_jB(member["authorized"],false)) {
  442. authorizedBy = "memberIsAuthorized";
  443. } else {
  444. char atok[256];
  445. if (metaData.get(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_AUTH_TOKEN,atok,sizeof(atok)) > 0) {
  446. atok[255] = (char)0; // not necessary but YDIFLO
  447. if (strlen(atok) > 0) { // extra sanity check since we never want to compare a null token on either side
  448. auto authTokens = network["authTokens"];
  449. if (authTokens.is_array()) {
  450. for(unsigned long i=0;i<authTokens.size();++i) {
  451. auto at = authTokens[i];
  452. if (at.is_object()) {
  453. const uint64_t expires = _jI(at["expires"],0ULL);
  454. std::string tok = _jS(at["token"],"");
  455. if ( ((expires == 0ULL)||(expires > now)) && (tok.length() > 0) && (tok == atok) ) {
  456. authorizedBy = "token";
  457. member["authorized"] = true; // tokens actually change member authorization state
  458. member["lastAuthorizedTime"] = now;
  459. member["lastAuthorizedBy"] = authorizedBy;
  460. break;
  461. }
  462. }
  463. }
  464. }
  465. }
  466. }
  467. }
  468. // Log this request
  469. {
  470. json rlEntry = json::object();
  471. rlEntry["ts"] = now;
  472. rlEntry["authorized"] = (authorizedBy) ? true : false;
  473. rlEntry["authorizedBy"] = (authorizedBy) ? authorizedBy : "";
  474. rlEntry["clientMajorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MAJOR_VERSION,0);
  475. rlEntry["clientMinorVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_MINOR_VERSION,0);
  476. rlEntry["clientRevision"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_NODE_REVISION,0);
  477. rlEntry["clientProtocolVersion"] = metaData.getUI(ZT_NETWORKCONFIG_REQUEST_METADATA_KEY_PROTOCOL_VERSION,0);
  478. if (fromAddr)
  479. rlEntry["fromAddr"] = fromAddr.toString();
  480. json recentLog = json::array();
  481. recentLog.push_back(rlEntry);
  482. auto oldLog = member["recentLog"];
  483. if (oldLog.is_array()) {
  484. for(unsigned long i=0;i<oldLog.size();++i) {
  485. recentLog.push_back(oldLog[i]);
  486. if (recentLog.size() >= ZT_NETCONF_DB_MEMBER_HISTORY_LENGTH)
  487. break;
  488. }
  489. }
  490. member["recentLog"] = recentLog;
  491. }
  492. // If they are not authorized, STOP!
  493. if (!authorizedBy) {
  494. _writeJson(memberJP,member);
  495. return NetworkController::NETCONF_QUERY_ACCESS_DENIED;
  496. }
  497. // -------------------------------------------------------------------------
  498. // If we made it this far, they are authorized.
  499. // -------------------------------------------------------------------------
  500. _NetworkMemberInfo nmi;
  501. _getNetworkMemberInfo(now,nwid,nmi);
  502. // Compute credential TTL. This is the "moving window" for COM agreement and
  503. // the global TTL for Capability and Tag objects. (The same value is used
  504. // for both.) This is computed by reference to the last time we deauthorized
  505. // a member, since within the time period since this event any temporal
  506. // differences are not particularly relevant.
  507. uint64_t credentialTtl = ZT_NETWORKCONFIG_DEFAULT_MIN_CREDENTIAL_TTL;
  508. if (now > nmi.mostRecentDeauthTime)
  509. credentialTtl += (now - nmi.mostRecentDeauthTime);
  510. if (credentialTtl > ZT_NETWORKCONFIG_DEFAULT_MAX_CREDENTIAL_TTL)
  511. credentialTtl = ZT_NETWORKCONFIG_DEFAULT_MAX_CREDENTIAL_TTL;
  512. nc.networkId = nwid;
  513. nc.type = _jB(network["private"],true) ? ZT_NETWORK_TYPE_PRIVATE : ZT_NETWORK_TYPE_PUBLIC;
  514. nc.timestamp = now;
  515. nc.credentialTimeToLive = credentialTtl;
  516. nc.revision = _jI(network["revision"],0ULL);
  517. nc.issuedTo = identity.address();
  518. if (_jB(network["enableBroadcast"],true)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_BROADCAST;
  519. if (_jB(network["allowPassiveBridging"],false)) nc.flags |= ZT_NETWORKCONFIG_FLAG_ALLOW_PASSIVE_BRIDGING;
  520. Utils::scopy(nc.name,sizeof(nc.name),_jS(network["name"],"").c_str());
  521. nc.multicastLimit = (unsigned int)_jI(network["multicastLimit"],32ULL);
  522. for(std::set<Address>::const_iterator ab(nmi.activeBridges.begin());ab!=nmi.activeBridges.end();++ab)
  523. nc.addSpecialist(*ab,ZT_NETWORKCONFIG_SPECIALIST_TYPE_ACTIVE_BRIDGE);
  524. auto v4AssignMode = network["v4AssignMode"];
  525. auto v6AssignMode = network["v6AssignMode"];
  526. auto ipAssignmentPools = network["ipAssignmentPools"];
  527. auto routes = network["routes"];
  528. auto rules = network["rules"];
  529. auto capabilities = network["capabilities"];
  530. auto memberCapabilities = member["capabilities"];
  531. auto memberTags = member["tags"];
  532. if (rules.is_array()) {
  533. for(unsigned long i=0;i<rules.size();++i) {
  534. if (nc.ruleCount >= ZT_MAX_NETWORK_RULES)
  535. break;
  536. if (_parseRule(rules[i],nc.rules[nc.ruleCount]))
  537. ++nc.ruleCount;
  538. }
  539. }
  540. if ((memberCapabilities.is_array())&&(memberCapabilities.size() > 0)&&(capabilities.is_array())) {
  541. std::map< uint64_t,json > capsById;
  542. for(unsigned long i=0;i<capabilities.size();++i) {
  543. auto cap = capabilities[i];
  544. if (cap.is_object())
  545. capsById[_jI(cap["id"],0ULL) & 0xffffffffULL] = cap;
  546. }
  547. for(unsigned long i=0;i<memberCapabilities.size();++i) {
  548. const uint64_t capId = _jI(memberCapabilities[i],0ULL) & 0xffffffffULL;
  549. json &cap = capsById[capId];
  550. if ((cap.is_object())&&(cap.size() > 0)) {
  551. ZT_VirtualNetworkRule capr[ZT_MAX_CAPABILITY_RULES];
  552. unsigned int caprc = 0;
  553. auto caprj = cap["rules"];
  554. if ((caprj.is_array())&&(caprj.size() > 0)) {
  555. for(unsigned long j=0;j<caprj.size();++j) {
  556. if (caprc >= ZT_MAX_CAPABILITY_RULES)
  557. break;
  558. if (_parseRule(caprj[j],capr[caprc]))
  559. ++caprc;
  560. }
  561. }
  562. nc.capabilities[nc.capabilityCount] = Capability((uint32_t)capId,nwid,now,1,capr,caprc);
  563. if (nc.capabilities[nc.capabilityCount].sign(signingId,identity.address()))
  564. ++nc.capabilityCount;
  565. if (nc.capabilityCount >= ZT_MAX_NETWORK_CAPABILITIES)
  566. break;
  567. }
  568. }
  569. }
  570. if (memberTags.is_array()) {
  571. std::map< uint32_t,uint32_t > tagsById;
  572. for(unsigned long i=0;i<memberTags.size();++i) {
  573. auto t = memberTags[i];
  574. if ((t.is_array())&&(t.size() == 2))
  575. tagsById[(uint32_t)(_jI(t[0],0ULL) & 0xffffffffULL)] = (uint32_t)(_jI(t[1],0ULL) & 0xffffffffULL);
  576. }
  577. for(std::map< uint32_t,uint32_t >::const_iterator t(tagsById.begin());t!=tagsById.end();++t) {
  578. if (nc.tagCount >= ZT_MAX_NETWORK_TAGS)
  579. break;
  580. nc.tags[nc.tagCount] = Tag(nwid,now,identity.address(),t->first,t->second);
  581. if (nc.tags[nc.tagCount].sign(signingId))
  582. ++nc.tagCount;
  583. }
  584. }
  585. if (routes.is_array()) {
  586. for(unsigned long i=0;i<routes.size();++i) {
  587. if (nc.routeCount >= ZT_MAX_NETWORK_ROUTES)
  588. break;
  589. auto route = routes[i];
  590. InetAddress t(_jS(route["target"],""));
  591. InetAddress v(_jS(route["via"],""));
  592. if ((t)&&(v)&&(t.ss_family == v.ss_family)) {
  593. ZT_VirtualNetworkRoute *r = &(nc.routes[nc.routeCount]);
  594. *(reinterpret_cast<InetAddress *>(&(r->target))) = t;
  595. *(reinterpret_cast<InetAddress *>(&(r->via))) = v;
  596. ++nc.routeCount;
  597. }
  598. }
  599. }
  600. if (v6AssignMode.is_object()) {
  601. if ((_jB(v6AssignMode["rfc4193"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  602. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv6rfc4193(nwid,identity.address().toInt());
  603. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  604. }
  605. if ((_jB(v6AssignMode["6plane"],false))&&(nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)) {
  606. nc.staticIps[nc.staticIpCount++] = InetAddress::makeIpv66plane(nwid,identity.address().toInt());
  607. nc.flags |= ZT_NETWORKCONFIG_FLAG_ENABLE_IPV6_NDP_EMULATION;
  608. }
  609. }
  610. bool haveManagedIpv4AutoAssignment = false;
  611. bool haveManagedIpv6AutoAssignment = false; // "special" NDP-emulated address types do not count
  612. json ipAssignments = member["ipAssignments"];
  613. if (ipAssignments.is_array()) {
  614. for(unsigned long i=0;i<ipAssignments.size();++i) {
  615. std::string ips = ipAssignments[i];
  616. InetAddress ip(ips);
  617. // IP assignments are only pushed if there is a corresponding local route. We also now get the netmask bits from
  618. // this route, ignoring the netmask bits field of the assigned IP itself. Using that was worthless and a source
  619. // of user error / poor UX.
  620. int routedNetmaskBits = 0;
  621. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  622. if ( (!nc.routes[rk].via.ss_family) && (reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->containsAddress(ip)) )
  623. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  624. }
  625. if (routedNetmaskBits > 0) {
  626. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  627. ip.setPort(routedNetmaskBits);
  628. nc.staticIps[nc.staticIpCount++] = ip;
  629. }
  630. if (ip.ss_family == AF_INET)
  631. haveManagedIpv4AutoAssignment = true;
  632. else if (ip.ss_family == AF_INET6)
  633. haveManagedIpv6AutoAssignment = true;
  634. }
  635. }
  636. } else {
  637. ipAssignments = json::array();
  638. }
  639. if ( (ipAssignmentPools.is_array()) && ((v6AssignMode.is_object())&&(_jB(v6AssignMode["zt"],false))) && (!haveManagedIpv6AutoAssignment) && (!_jB(member["activeBridge"],false)) ) {
  640. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv6AutoAssignment));++p) {
  641. auto pool = ipAssignmentPools[p];
  642. if (pool.is_object()) {
  643. InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
  644. InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
  645. if ( (ipRangeStart.ss_family == AF_INET6) && (ipRangeEnd.ss_family == AF_INET6) ) {
  646. uint64_t s[2],e[2],x[2],xx[2];
  647. memcpy(s,ipRangeStart.rawIpData(),16);
  648. memcpy(e,ipRangeEnd.rawIpData(),16);
  649. s[0] = Utils::ntoh(s[0]);
  650. s[1] = Utils::ntoh(s[1]);
  651. e[0] = Utils::ntoh(e[0]);
  652. e[1] = Utils::ntoh(e[1]);
  653. x[0] = s[0];
  654. x[1] = s[1];
  655. for(unsigned int trialCount=0;trialCount<1000;++trialCount) {
  656. if ((trialCount == 0)&&(e[1] > s[1])&&((e[1] - s[1]) >= 0xffffffffffULL)) {
  657. // First see if we can just cram a ZeroTier ID into the higher 64 bits. If so do that.
  658. xx[0] = Utils::hton(x[0]);
  659. xx[1] = Utils::hton(x[1] + identity.address().toInt());
  660. } else {
  661. // 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
  662. Utils::getSecureRandom((void *)xx,16);
  663. if ((e[0] > s[0]))
  664. xx[0] %= (e[0] - s[0]);
  665. else xx[0] = 0;
  666. if ((e[1] > s[1]))
  667. xx[1] %= (e[1] - s[1]);
  668. else xx[1] = 0;
  669. xx[0] = Utils::hton(x[0] + xx[0]);
  670. xx[1] = Utils::hton(x[1] + xx[1]);
  671. }
  672. InetAddress ip6((const void *)xx,16,0);
  673. // Check if this IP is within a local-to-Ethernet routed network
  674. int routedNetmaskBits = 0;
  675. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  676. 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)) )
  677. routedNetmaskBits = reinterpret_cast<const InetAddress *>(&(nc.routes[rk].target))->netmaskBits();
  678. }
  679. // If it's routed, then try to claim and assign it and if successful end loop
  680. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip6))) {
  681. ipAssignments.push_back(ip6.toIpString());
  682. member["ipAssignments"] = ipAssignments;
  683. ip6.setPort((unsigned int)routedNetmaskBits);
  684. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES)
  685. nc.staticIps[nc.staticIpCount++] = ip6;
  686. haveManagedIpv4AutoAssignment = true;
  687. break;
  688. }
  689. }
  690. }
  691. }
  692. }
  693. }
  694. if ( (ipAssignmentPools.is_array()) && ((v4AssignMode.is_object())&&(_jB(v4AssignMode["zt"],false))) && (!haveManagedIpv4AutoAssignment) && (!_jB(member["activeBridge"],false)) ) {
  695. for(unsigned long p=0;((p<ipAssignmentPools.size())&&(!haveManagedIpv4AutoAssignment));++p) {
  696. auto pool = ipAssignmentPools[p];
  697. if (pool.is_object()) {
  698. InetAddress ipRangeStart(_jS(pool["ipRangeStart"],""));
  699. InetAddress ipRangeEnd(_jS(pool["ipRangeEnd"],""));
  700. if ( (ipRangeStart.ss_family == AF_INET) && (ipRangeEnd.ss_family == AF_INET) ) {
  701. uint32_t ipRangeStart = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeStart)->sin_addr.s_addr));
  702. uint32_t ipRangeEnd = Utils::ntoh((uint32_t)(reinterpret_cast<struct sockaddr_in *>(&ipRangeEnd)->sin_addr.s_addr));
  703. if ((ipRangeEnd <= ipRangeStart)||(ipRangeStart == 0))
  704. continue;
  705. uint32_t ipRangeLen = ipRangeEnd - ipRangeStart;
  706. // Start with the LSB of the member's address
  707. uint32_t ipTrialCounter = (uint32_t)(identity.address().toInt() & 0xffffffff);
  708. for(uint32_t k=ipRangeStart,trialCount=0;(k<=ipRangeEnd)&&(trialCount < 1000);++k,++trialCount) {
  709. uint32_t ip = (ipRangeLen > 0) ? (ipRangeStart + (ipTrialCounter % ipRangeLen)) : ipRangeStart;
  710. ++ipTrialCounter;
  711. if ((ip & 0x000000ff) == 0x000000ff)
  712. continue; // don't allow addresses that end in .255
  713. // Check if this IP is within a local-to-Ethernet routed network
  714. int routedNetmaskBits = 0;
  715. for(unsigned int rk=0;rk<nc.routeCount;++rk) {
  716. if ((!nc.routes[rk].via.ss_family)&&(nc.routes[rk].target.ss_family == AF_INET)) {
  717. uint32_t targetIp = Utils::ntoh((uint32_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_addr.s_addr));
  718. int targetBits = Utils::ntoh((uint16_t)(reinterpret_cast<const struct sockaddr_in *>(&(nc.routes[rk].target))->sin_port));
  719. if ((ip & (0xffffffff << (32 - targetBits))) == targetIp) {
  720. routedNetmaskBits = targetBits;
  721. break;
  722. }
  723. }
  724. }
  725. InetAddress ip4(Utils::hton(ip),0);
  726. // If it's routed, then try to claim and assign it and if successful end loop
  727. if ((routedNetmaskBits > 0)&&(!nmi.allocatedIps.count(ip4))) {
  728. ipAssignments.push_back(ip4.toIpString());
  729. member["ipAssignments"] = ipAssignments;
  730. if (nc.staticIpCount < ZT_MAX_ZT_ASSIGNED_ADDRESSES) {
  731. struct sockaddr_in *const v4ip = reinterpret_cast<struct sockaddr_in *>(&(nc.staticIps[nc.staticIpCount++]));
  732. v4ip->sin_family = AF_INET;
  733. v4ip->sin_port = Utils::hton((uint16_t)routedNetmaskBits);
  734. v4ip->sin_addr.s_addr = Utils::hton(ip);
  735. }
  736. haveManagedIpv4AutoAssignment = true;
  737. break;
  738. }
  739. }
  740. }
  741. }
  742. }
  743. }
  744. if (_jB(network["private"],true)) {
  745. CertificateOfMembership com(now,credentialTtl,nwid,identity.address());
  746. if (com.sign(signingId)) {
  747. nc.com = com;
  748. } else {
  749. return NETCONF_QUERY_INTERNAL_SERVER_ERROR;
  750. }
  751. }
  752. _writeJson(memberJP,member);
  753. return NetworkController::NETCONF_QUERY_OK;
  754. }
  755. unsigned int EmbeddedNetworkController::handleControlPlaneHttpGET(
  756. const std::vector<std::string> &path,
  757. const std::map<std::string,std::string> &urlArgs,
  758. const std::map<std::string,std::string> &headers,
  759. const std::string &body,
  760. std::string &responseBody,
  761. std::string &responseContentType)
  762. {
  763. if ((path.size() > 0)&&(path[0] == "network")) {
  764. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  765. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  766. char nwids[24];
  767. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  768. json network(_readJson(_networkJP(nwid,false)));
  769. if (!network.size())
  770. return 404;
  771. if (path.size() >= 3) {
  772. if (path[2] == "member") {
  773. if (path.size() >= 4) {
  774. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  775. json member(_readJson(_memberJP(nwid,Address(address),false)));
  776. if (!member.size())
  777. return 404;
  778. char addrs[24];
  779. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",address);
  780. // Add non-persisted fields
  781. member["clock"] = OSUtils::now();
  782. responseBody = member.dump(2);
  783. responseContentType = "application/json";
  784. return 200;
  785. } else {
  786. responseBody = "{";
  787. std::vector<std::string> members(OSUtils::listSubdirectories((_networkBP(nwid,false) + ZT_PATH_SEPARATOR_S + "member").c_str()));
  788. for(std::vector<std::string>::iterator i(members.begin());i!=members.end();++i) {
  789. if (i->length() == ZT_ADDRESS_LENGTH_HEX) {
  790. json member(_readJson(_memberJP(nwid,Address(Utils::hexStrToU64(i->c_str())),false)));
  791. if (member.size()) {
  792. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  793. responseBody.append(*i);
  794. responseBody.append("\":");
  795. responseBody.append(_jS(member["revision"],"0"));
  796. }
  797. }
  798. }
  799. responseBody.push_back('}');
  800. responseContentType = "application/json";
  801. return 200;
  802. }
  803. } else if ((path[2] == "active")&&(path.size() == 3)) {
  804. responseBody = "{";
  805. std::vector<std::string> members(OSUtils::listSubdirectories((_networkBP(nwid,false) + ZT_PATH_SEPARATOR_S + "member").c_str()));
  806. const uint64_t threshold = OSUtils::now() - ZT_NETCONF_NODE_ACTIVE_THRESHOLD;
  807. for(std::vector<std::string>::iterator i(members.begin());i!=members.end();++i) {
  808. if (i->length() == ZT_ADDRESS_LENGTH_HEX) {
  809. json member(_readJson(_memberJP(nwid,Address(Utils::hexStrToU64(i->c_str())),false)));
  810. if (member.size()) {
  811. auto recentLog = member["recentLog"];
  812. if ((recentLog.is_array())&&(recentLog.size() > 0)) {
  813. auto mostRecentLog = recentLog[0];
  814. if ((mostRecentLog.is_object())&&(_jI(mostRecentLog["ts"],0ULL) >= threshold)) {
  815. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  816. responseBody.append(*i);
  817. responseBody.append("\":");
  818. responseBody.append(mostRecentLog.dump());
  819. }
  820. }
  821. }
  822. }
  823. }
  824. responseBody.push_back('}');
  825. responseContentType = "application/json";
  826. return 200;
  827. } else if ((path[2] == "test")&&(path.size() >= 4)) {
  828. Mutex::Lock _l(_circuitTests_m);
  829. std::map< uint64_t,_CircuitTestEntry >::iterator cte(_circuitTests.find(Utils::hexStrToU64(path[3].c_str())));
  830. if ((cte != _circuitTests.end())&&(cte->second.test)) {
  831. responseBody = "[";
  832. responseBody.append(cte->second.jsonResults);
  833. responseBody.push_back(']');
  834. responseContentType = "application/json";
  835. return 200;
  836. } // else 404
  837. } // else 404
  838. } else {
  839. const uint64_t now = OSUtils::now();
  840. _NetworkMemberInfo nmi;
  841. _getNetworkMemberInfo(now,nwid,nmi);
  842. _addNetworkNonPersistedFields(network,now,nmi);
  843. responseBody = network.dump(2);
  844. responseContentType = "application/json";
  845. return 200;
  846. }
  847. } else if (path.size() == 1) {
  848. responseBody = "[";
  849. std::vector<std::string> networks(OSUtils::listSubdirectories((_path + ZT_PATH_SEPARATOR_S + "network").c_str()));
  850. for(auto i(networks.begin());i!=networks.end();++i) {
  851. if (i->length() == 16) {
  852. responseBody.append((responseBody.length() == 1) ? "\"" : ",\"");
  853. responseBody.append(*i);
  854. responseBody.append("\"");
  855. }
  856. }
  857. responseBody.push_back(']');
  858. responseContentType = "application/json";
  859. return 200;
  860. } // else 404
  861. } else {
  862. char tmp[4096];
  863. Utils::snprintf(tmp,sizeof(tmp),"{\n\t\"controller\": true,\n\t\"apiVersion\": %d,\n\t\"clock\": %llu\n}\n",ZT_NETCONF_CONTROLLER_API_VERSION,(unsigned long long)OSUtils::now());
  864. responseBody = tmp;
  865. responseContentType = "application/json";
  866. return 200;
  867. }
  868. return 404;
  869. }
  870. unsigned int EmbeddedNetworkController::handleControlPlaneHttpPOST(
  871. const std::vector<std::string> &path,
  872. const std::map<std::string,std::string> &urlArgs,
  873. const std::map<std::string,std::string> &headers,
  874. const std::string &body,
  875. std::string &responseBody,
  876. std::string &responseContentType)
  877. {
  878. if (path.empty())
  879. return 404;
  880. json b;
  881. try {
  882. b = json::parse(body);
  883. if (!b.is_object())
  884. return 400;
  885. } catch ( ... ) {
  886. return 400;
  887. }
  888. const uint64_t now = OSUtils::now();
  889. if (path[0] == "network") {
  890. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  891. uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  892. char nwids[24];
  893. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)nwid);
  894. if (path.size() >= 3) {
  895. json network(_readJson(_networkJP(nwid,false)));
  896. if (!network.size())
  897. return 404;
  898. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  899. uint64_t address = Utils::hexStrToU64(path[3].c_str());
  900. char addrs[24];
  901. Utils::snprintf(addrs,sizeof(addrs),"%.10llx",(unsigned long long)address);
  902. json member(_readJson(_memberJP(nwid,Address(address),true)));
  903. _initMember(member);
  904. try {
  905. if (b.count("activeBridge")) member["activeBridge"] = _jB(b["activeBridge"],false);
  906. if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
  907. if (b.count("authorized")) {
  908. const bool newAuth = _jB(b["authorized"],false);
  909. const bool oldAuth = _jB(member["authorized"],false);
  910. if (newAuth != oldAuth) {
  911. if (newAuth) {
  912. member["authorized"] = true;
  913. member["lastAuthorizedTime"] = now;
  914. member["lastAuthorizedBy"] = "user";
  915. } else {
  916. member["authorized"] = false;
  917. member["lastDeauthorizedTime"] = now;
  918. }
  919. }
  920. }
  921. if (b.count("ipAssignments")) {
  922. auto ipa = b["ipAssignments"];
  923. if (ipa.is_array()) {
  924. json mipa(json::array());
  925. for(unsigned long i=0;i<ipa.size();++i) {
  926. std::string ips = ipa[i];
  927. InetAddress ip(ips);
  928. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  929. mipa.push_back(ip.toIpString());
  930. }
  931. }
  932. member["ipAssignments"] = mipa;
  933. }
  934. }
  935. if (b.count("tags")) {
  936. auto tags = b["tags"];
  937. if (tags.is_array()) {
  938. std::map<uint64_t,uint64_t> mtags;
  939. for(unsigned long i=0;i<tags.size();++i) {
  940. auto tag = tags[i];
  941. if ((tag.is_array())&&(tag.size() == 2))
  942. mtags[_jI(tag[0],0ULL) & 0xffffffffULL] = _jI(tag[1],0ULL) & 0xffffffffULL;
  943. }
  944. json mtagsa = json::array();
  945. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  946. json ta = json::array();
  947. ta.push_back(t->first);
  948. ta.push_back(t->second);
  949. mtagsa.push_back(ta);
  950. }
  951. member["tags"] = mtagsa;
  952. }
  953. }
  954. if (b.count("capabilities")) {
  955. auto capabilities = b["capabilities"];
  956. if (capabilities.is_array()) {
  957. json mcaps = json::array();
  958. for(unsigned long i=0;i<capabilities.size();++i) {
  959. mcaps.push_back(_jI(capabilities[i],0ULL));
  960. }
  961. std::sort(mcaps.begin(),mcaps.end());
  962. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  963. member["capabilities"] = mcaps;
  964. }
  965. }
  966. } catch ( ... ) {
  967. return 400;
  968. }
  969. member["id"] = addrs;
  970. member["address"] = addrs; // legacy
  971. member["nwid"] = nwids;
  972. member["lastModified"] = now;
  973. {
  974. auto revj = member["revision"];
  975. const uint64_t rev = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  976. member["revision"] = rev;
  977. }
  978. _writeJson(_memberJP(nwid,Address(address),true).c_str(),member);
  979. // Add non-persisted fields
  980. member["clock"] = member["lastModified"];
  981. responseBody = member.dump(2);
  982. responseContentType = "application/json";
  983. return 200;
  984. } else if ((path.size() == 3)&&(path[2] == "test")) {
  985. Mutex::Lock _l(_circuitTests_m);
  986. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  987. memset(test,0,sizeof(ZT_CircuitTest));
  988. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  989. test->credentialNetworkId = nwid;
  990. test->ptr = (void *)this;
  991. json hops = b["hops"];
  992. if (hops.is_array()) {
  993. for(unsigned long i=0;i<hops.size();++i) {
  994. auto hops2 = hops[i];
  995. if (hops2.is_array()) {
  996. for(unsigned long j=0;j<hops2.size();++j) {
  997. std::string s = hops2[j];
  998. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  999. }
  1000. } else if (hops2.is_string()) {
  1001. std::string s = hops2;
  1002. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1003. }
  1004. }
  1005. }
  1006. test->reportAtEveryHop = (_jB(b["reportAtEveryHop"],true) ? 1 : 0);
  1007. if (!test->hopCount) {
  1008. ::free((void *)test);
  1009. return 400;
  1010. }
  1011. test->timestamp = OSUtils::now();
  1012. _CircuitTestEntry &te = _circuitTests[test->testId];
  1013. te.test = test;
  1014. te.jsonResults = "";
  1015. _node->circuitTestBegin(test,&(EmbeddedNetworkController::_circuitTestCallback));
  1016. char json[1024];
  1017. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
  1018. responseBody = json;
  1019. responseContentType = "application/json";
  1020. return 200;
  1021. } // else 404
  1022. } else {
  1023. // POST to network ID
  1024. // Magic ID ending with ______ picks a random unused network ID
  1025. if (path[1].substr(10) == "______") {
  1026. nwid = 0;
  1027. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  1028. uint64_t nwidPostfix = 0;
  1029. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  1030. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  1031. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1032. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  1033. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  1034. if (!OSUtils::fileExists(_networkJP(tryNwid,false).c_str())) {
  1035. nwid = tryNwid;
  1036. break;
  1037. }
  1038. }
  1039. if (!nwid)
  1040. return 503;
  1041. }
  1042. json network(_readJson(_networkJP(nwid,true)));
  1043. _initNetwork(network);
  1044. try {
  1045. if (b.count("name")) network["name"] = _jS(b["name"],"");
  1046. if (b.count("private")) network["private"] = _jB(b["private"],true);
  1047. if (b.count("enableBroadcast")) network["enableBroadcast"] = _jB(b["enableBroadcast"],false);
  1048. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = _jB(b["allowPassiveBridging"],false);
  1049. if (b.count("multicastLimit")) network["multicastLimit"] = _jI(b["multicastLimit"],32ULL);
  1050. if (b.count("v4AssignMode")) {
  1051. auto nv4m = network["v4AssignMode"];
  1052. if (!nv4m.is_object()) nv4m = json::object();
  1053. if (b["v4AssignMode"].is_string()) { // backward compatibility
  1054. nv4m["zt"] = (_jS(b["v4AssignMode"],"") == "zt");
  1055. } else if (b["v4AssignMode"].is_object()) {
  1056. auto v4m = b["v4AssignMode"];
  1057. if (v4m.count("zt")) nv4m["zt"] = _jB(v4m["zt"],false);
  1058. }
  1059. if (!nv4m.count("zt")) nv4m["zt"] = false;
  1060. }
  1061. if (b.count("v6AssignMode")) {
  1062. auto nv6m = network["v6AssignMode"];
  1063. if (!nv6m.is_object()) nv6m = json::object();
  1064. if (b["v6AssignMode"].is_string()) { // backward compatibility
  1065. std::vector<std::string> v6m(Utils::split(_jS(b["v6AssignMode"],"").c_str(),",","",""));
  1066. std::sort(v6m.begin(),v6m.end());
  1067. v6m.erase(std::unique(v6m.begin(),v6m.end()),v6m.end());
  1068. for(std::vector<std::string>::iterator i(v6m.begin());i!=v6m.end();++i) {
  1069. if (*i == "rfc4193")
  1070. nv6m["rfc4193"] = true;
  1071. else if (*i == "zt")
  1072. nv6m["zt"] = true;
  1073. else if (*i == "6plane")
  1074. nv6m["6plane"] = true;
  1075. }
  1076. } else if (b["v6AssignMode"].is_object()) {
  1077. auto v6m = b["v6AssignMode"];
  1078. if (v6m.count("rfc4193")) nv6m["rfc4193"] = _jB(v6m["rfc4193"],false);
  1079. if (v6m.count("zt")) nv6m["rfc4193"] = _jB(v6m["zt"],false);
  1080. if (v6m.count("6plane")) nv6m["rfc4193"] = _jB(v6m["6plane"],false);
  1081. }
  1082. if (!nv6m.count("rfc4193")) nv6m["rfc4193"] = false;
  1083. if (!nv6m.count("zt")) nv6m["zt"] = false;
  1084. if (!nv6m.count("6plane")) nv6m["6plane"] = false;
  1085. }
  1086. if (b.count("routes")) {
  1087. auto rts = b["routes"];
  1088. if (rts.is_array()) {
  1089. for(unsigned long i=0;i<rts.size();++i) {
  1090. auto rt = rts[i];
  1091. if ((rt.is_object())&&(rt.count("target"))&&(rt.count("via"))) {
  1092. InetAddress t(_jS(rt["target"],""));
  1093. InetAddress v(_jS(rt["via"],""));
  1094. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.ss_family == v.ss_family) && (t.netmaskBitsValid()) ) {
  1095. auto nrts = network["routes"];
  1096. if (!nrts.is_array()) nrts = json::array();
  1097. json tmp;
  1098. tmp["target"] = t.toString();
  1099. tmp["via"] = v.toIpString();
  1100. nrts.push_back(tmp);
  1101. }
  1102. }
  1103. }
  1104. }
  1105. }
  1106. if (b.count("ipAssignmentPools")) {
  1107. auto ipp = b["ipAssignmentPools"];
  1108. if (ipp.is_array()) {
  1109. for(unsigned long i=0;i<ipp.size();++i) {
  1110. auto ip = ipp[i];
  1111. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  1112. InetAddress f(_jS(ip["ipRangeStart"],""));
  1113. InetAddress t(_jS(ip["ipRangeEnd"],""));
  1114. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  1115. auto nipp = network["ipAssignmentPools"];
  1116. if (!nipp.is_array()) nipp = json::array();
  1117. json tmp;
  1118. tmp["ipRangeStart"] = f.toIpString();
  1119. tmp["ipRangeEnd"] = t.toIpString();
  1120. nipp.push_back(tmp);
  1121. }
  1122. }
  1123. }
  1124. }
  1125. }
  1126. if (b.count("rules")) {
  1127. auto rules = b["rules"];
  1128. if (rules.is_array()) {
  1129. json nrules = json::array();
  1130. for(unsigned long i=0;i<rules.size();++i) {
  1131. json rule = rules[i];
  1132. if (rule.is_object()) {
  1133. ZT_VirtualNetworkRule ztr;
  1134. if (_parseRule(rule,ztr)) {
  1135. rule = _renderRule(ztr);
  1136. if ((rule.is_object())&&(rule.count("type"))) {
  1137. nrules.push_back(rule);
  1138. }
  1139. }
  1140. }
  1141. }
  1142. network["rules"] = nrules;
  1143. }
  1144. }
  1145. if (b.count("authTokens")) {
  1146. auto authTokens = b["authTokens"];
  1147. if (authTokens.is_array()) {
  1148. json nat = json::array();
  1149. for(unsigned long i=0;i<authTokens.size();++i) {
  1150. auto token = authTokens[i];
  1151. if (token.is_object()) {
  1152. std::string tstr = token["token"];
  1153. if (tstr.length() > 0) {
  1154. json t = json::object();
  1155. t["token"] = tstr;
  1156. t["expires"] = _jI(token["expires"],0ULL);
  1157. nat.push_back(t);
  1158. }
  1159. }
  1160. }
  1161. network["authTokens"] = nat;
  1162. }
  1163. }
  1164. if (b.count("capabilities")) {
  1165. auto capabilities = b["capabilities"];
  1166. if (capabilities.is_array()) {
  1167. std::map< uint64_t,json > ncaps;
  1168. for(unsigned long i=0;i<capabilities.size();++i) {
  1169. auto cap = capabilities[i];
  1170. if (cap.is_object()) {
  1171. json ncap = json::object();
  1172. const uint64_t capId = _jI(cap["id"],0ULL);
  1173. ncap["id"] = capId;
  1174. auto rules = cap["rules"];
  1175. json nrules = json::array();
  1176. if (rules.is_array()) {
  1177. for(unsigned long i=0;i<rules.size();++i) {
  1178. json rule = rules[i];
  1179. if (rule.is_object()) {
  1180. ZT_VirtualNetworkRule ztr;
  1181. if (_parseRule(rule,ztr)) {
  1182. rule = _renderRule(ztr);
  1183. if ((rule.is_object())&&(rule.count("type"))) {
  1184. nrules.push_back(rule);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. }
  1190. ncap["rules"] = nrules;
  1191. ncaps[capId] = ncap;
  1192. }
  1193. }
  1194. json ncapsa = json::array();
  1195. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  1196. ncapsa.push_back(c->second);
  1197. network["capabilities"] = ncapsa;
  1198. }
  1199. }
  1200. } catch ( ... ) {
  1201. return 400;
  1202. }
  1203. network["id"] = nwids;
  1204. network["nwid"] = nwids; // legacy
  1205. auto rev = network["revision"];
  1206. network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
  1207. network["lastModified"] = now;
  1208. _writeJson(_networkJP(nwid,true),network);
  1209. _NetworkMemberInfo nmi;
  1210. _getNetworkMemberInfo(now,nwid,nmi);
  1211. _addNetworkNonPersistedFields(network,now,nmi);
  1212. responseBody = network.dump(2);
  1213. responseContentType = "application/json";
  1214. return 200;
  1215. } // else 404
  1216. } // else 404
  1217. } // else 404
  1218. return 404;
  1219. }
  1220. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  1221. const std::vector<std::string> &path,
  1222. const std::map<std::string,std::string> &urlArgs,
  1223. const std::map<std::string,std::string> &headers,
  1224. const std::string &body,
  1225. std::string &responseBody,
  1226. std::string &responseContentType)
  1227. {
  1228. if (path.empty())
  1229. return 404;
  1230. if (path[0] == "network") {
  1231. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1232. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1233. json network(_readJson(_networkJP(nwid,false)));
  1234. if (!network.size())
  1235. return 404;
  1236. if (path.size() >= 3) {
  1237. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1238. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1239. json member(_readJson(_memberJP(nwid,Address(address),false)));
  1240. if (!member.size())
  1241. return 404;
  1242. OSUtils::rmDashRf(_memberBP(nwid,Address(address),false).c_str());
  1243. responseBody = member.dump(2);
  1244. responseContentType = "application/json";
  1245. return 200;
  1246. }
  1247. } else {
  1248. OSUtils::rmDashRf(_networkBP(nwid,false).c_str());
  1249. {
  1250. Mutex::Lock _l(_networkMemberCache_m);
  1251. _networkMemberCache.erase(nwid);
  1252. }
  1253. responseBody = network.dump(2);
  1254. responseContentType = "application/json";
  1255. return 200;
  1256. }
  1257. } // else 404
  1258. } // else 404
  1259. return 404;
  1260. }
  1261. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1262. {
  1263. char tmp[65535];
  1264. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1265. if (!test)
  1266. return;
  1267. if (!report)
  1268. return;
  1269. Mutex::Lock _l(self->_circuitTests_m);
  1270. std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
  1271. if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
  1272. self->_node->circuitTestEnd(test);
  1273. ::free((void *)test);
  1274. return;
  1275. }
  1276. Utils::snprintf(tmp,sizeof(tmp),
  1277. "%s{\n"
  1278. "\t\"timestamp\": %llu," ZT_EOL_S
  1279. "\t\"testId\": \"%.16llx\"," ZT_EOL_S
  1280. "\t\"upstream\": \"%.10llx\"," ZT_EOL_S
  1281. "\t\"current\": \"%.10llx\"," ZT_EOL_S
  1282. "\t\"receivedTimestamp\": %llu," ZT_EOL_S
  1283. "\t\"remoteTimestamp\": %llu," ZT_EOL_S
  1284. "\t\"sourcePacketId\": \"%.16llx\"," ZT_EOL_S
  1285. "\t\"flags\": %llu," ZT_EOL_S
  1286. "\t\"sourcePacketHopCount\": %u," ZT_EOL_S
  1287. "\t\"errorCode\": %u," ZT_EOL_S
  1288. "\t\"vendor\": %d," ZT_EOL_S
  1289. "\t\"protocolVersion\": %u," ZT_EOL_S
  1290. "\t\"majorVersion\": %u," ZT_EOL_S
  1291. "\t\"minorVersion\": %u," ZT_EOL_S
  1292. "\t\"revision\": %u," ZT_EOL_S
  1293. "\t\"platform\": %d," ZT_EOL_S
  1294. "\t\"architecture\": %d," ZT_EOL_S
  1295. "\t\"receivedOnLocalAddress\": \"%s\"," ZT_EOL_S
  1296. "\t\"receivedFromRemoteAddress\": \"%s\"" ZT_EOL_S
  1297. "}",
  1298. ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
  1299. (unsigned long long)report->timestamp,
  1300. (unsigned long long)test->testId,
  1301. (unsigned long long)report->upstream,
  1302. (unsigned long long)report->current,
  1303. (unsigned long long)OSUtils::now(),
  1304. (unsigned long long)report->remoteTimestamp,
  1305. (unsigned long long)report->sourcePacketId,
  1306. (unsigned long long)report->flags,
  1307. report->sourcePacketHopCount,
  1308. report->errorCode,
  1309. (int)report->vendor,
  1310. report->protocolVersion,
  1311. report->majorVersion,
  1312. report->minorVersion,
  1313. report->revision,
  1314. (int)report->platform,
  1315. (int)report->architecture,
  1316. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1317. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1318. cte->second.jsonResults.append(tmp);
  1319. }
  1320. void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
  1321. {
  1322. Mutex::Lock _mcl(_networkMemberCache_m);
  1323. auto memberCacheEntry = _networkMemberCache[nwid];
  1324. if ((now - memberCacheEntry.second) >= ZT_NETCONF_NETWORK_MEMBER_CACHE_EXPIRE) {
  1325. const std::string bp(_networkBP(nwid,false) + ZT_PATH_SEPARATOR_S + "member");
  1326. std::vector<std::string> members(OSUtils::listSubdirectories(bp.c_str()));
  1327. for(std::vector<std::string>::iterator m(members.begin());m!=members.end();++m) {
  1328. if (m->length() == ZT_ADDRESS_LENGTH_HEX) {
  1329. nlohmann::json mj(_readJson(bp + ZT_PATH_SEPARATOR_S + *m + ZT_PATH_SEPARATOR_S + "config.json"));
  1330. if ((mj.is_object())&&(mj.size() > 0)) {
  1331. memberCacheEntry.first[Address(*m)] = mj;
  1332. }
  1333. }
  1334. }
  1335. memberCacheEntry.second = now;
  1336. }
  1337. nmi.totalMemberCount = memberCacheEntry.first.size();
  1338. for(std::map< Address,nlohmann::json >::const_iterator nm(memberCacheEntry.first.begin());nm!=memberCacheEntry.first.end();++nm) {
  1339. if (_jB(nm->second["authorized"],false)) {
  1340. ++nmi.authorizedMemberCount;
  1341. auto mlog = nm->second["recentLog"];
  1342. if ((mlog.is_array())&&(mlog.size() > 0)) {
  1343. auto mlog1 = mlog[0];
  1344. if (mlog1.is_object()) {
  1345. if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
  1346. ++nmi.activeMemberCount;
  1347. }
  1348. }
  1349. if (_jB(nm->second["activeBridge"],false)) {
  1350. nmi.activeBridges.insert(nm->first);
  1351. }
  1352. auto mips = nm->second["ipAssignments"];
  1353. if (mips.is_array()) {
  1354. for(unsigned long i=0;i<mips.size();++i) {
  1355. InetAddress mip(_jS(mips[i],""));
  1356. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  1357. nmi.allocatedIps.insert(mip);
  1358. }
  1359. }
  1360. } else {
  1361. nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(nm->second["lastDeauthorizedTime"],0ULL));
  1362. }
  1363. }
  1364. }
  1365. } // namespace ZeroTier