EmbeddedNetworkController.cpp 54 KB

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