EmbeddedNetworkController.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  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["noAutoAssignIps"],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["noAutoAssignIps"],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("noAutoAssignIps")) member["noAutoAssignIps"] = _jB(b["noAutoAssignIps"],false);
  915. if ((b.count("identity"))&&(!member.count("identity"))) member["identity"] = _jS(b["identity"],""); // allow identity to be populated only if not already known
  916. if (b.count("authorized")) {
  917. const bool newAuth = _jB(b["authorized"],false);
  918. const bool oldAuth = _jB(member["authorized"],false);
  919. if (newAuth != oldAuth) {
  920. if (newAuth) {
  921. member["authorized"] = true;
  922. member["lastAuthorizedTime"] = now;
  923. member["lastAuthorizedBy"] = "user";
  924. } else {
  925. member["authorized"] = false;
  926. member["lastDeauthorizedTime"] = now;
  927. }
  928. }
  929. }
  930. if (b.count("ipAssignments")) {
  931. auto ipa = b["ipAssignments"];
  932. if (ipa.is_array()) {
  933. json mipa(json::array());
  934. for(unsigned long i=0;i<ipa.size();++i) {
  935. std::string ips = ipa[i];
  936. InetAddress ip(ips);
  937. if ((ip.ss_family == AF_INET)||(ip.ss_family == AF_INET6)) {
  938. mipa.push_back(ip.toIpString());
  939. }
  940. }
  941. member["ipAssignments"] = mipa;
  942. }
  943. }
  944. if (b.count("tags")) {
  945. auto tags = b["tags"];
  946. if (tags.is_array()) {
  947. std::map<uint64_t,uint64_t> mtags;
  948. for(unsigned long i=0;i<tags.size();++i) {
  949. auto tag = tags[i];
  950. if ((tag.is_array())&&(tag.size() == 2))
  951. mtags[_jI(tag[0],0ULL) & 0xffffffffULL] = _jI(tag[1],0ULL) & 0xffffffffULL;
  952. }
  953. json mtagsa = json::array();
  954. for(std::map<uint64_t,uint64_t>::iterator t(mtags.begin());t!=mtags.end();++t) {
  955. json ta = json::array();
  956. ta.push_back(t->first);
  957. ta.push_back(t->second);
  958. mtagsa.push_back(ta);
  959. }
  960. member["tags"] = mtagsa;
  961. }
  962. }
  963. if (b.count("capabilities")) {
  964. auto capabilities = b["capabilities"];
  965. if (capabilities.is_array()) {
  966. json mcaps = json::array();
  967. for(unsigned long i=0;i<capabilities.size();++i) {
  968. mcaps.push_back(_jI(capabilities[i],0ULL));
  969. }
  970. std::sort(mcaps.begin(),mcaps.end());
  971. mcaps.erase(std::unique(mcaps.begin(),mcaps.end()),mcaps.end());
  972. member["capabilities"] = mcaps;
  973. }
  974. }
  975. } catch ( ... ) {
  976. return 400;
  977. }
  978. member["id"] = addrs;
  979. member["address"] = addrs; // legacy
  980. member["nwid"] = nwids;
  981. member["lastModified"] = now;
  982. auto revj = member["revision"];
  983. member["revision"] = (revj.is_number() ? ((uint64_t)revj + 1ULL) : 1ULL);
  984. _writeJson(_memberJP(nwid,Address(address),true).c_str(),member);
  985. if (_node)
  986. _node->pushNetworkRefresh(address,nwid,(const uint64_t *)0,(const uint64_t *)0,0);
  987. // Add non-persisted fields
  988. member["clock"] = now;
  989. responseBody = member.dump(2);
  990. responseContentType = "application/json";
  991. return 200;
  992. } else if ((path.size() == 3)&&(path[2] == "test")) {
  993. Mutex::Lock _l(_circuitTests_m);
  994. ZT_CircuitTest *test = (ZT_CircuitTest *)malloc(sizeof(ZT_CircuitTest));
  995. memset(test,0,sizeof(ZT_CircuitTest));
  996. Utils::getSecureRandom(&(test->testId),sizeof(test->testId));
  997. test->credentialNetworkId = nwid;
  998. test->ptr = (void *)this;
  999. json hops = b["hops"];
  1000. if (hops.is_array()) {
  1001. for(unsigned long i=0;i<hops.size();++i) {
  1002. auto hops2 = hops[i];
  1003. if (hops2.is_array()) {
  1004. for(unsigned long j=0;j<hops2.size();++j) {
  1005. std::string s = hops2[j];
  1006. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1007. }
  1008. } else if (hops2.is_string()) {
  1009. std::string s = hops2;
  1010. test->hops[test->hopCount].addresses[test->hops[test->hopCount].breadth++] = Utils::hexStrToU64(s.c_str()) & 0xffffffffffULL;
  1011. }
  1012. }
  1013. }
  1014. test->reportAtEveryHop = (_jB(b["reportAtEveryHop"],true) ? 1 : 0);
  1015. if (!test->hopCount) {
  1016. ::free((void *)test);
  1017. return 400;
  1018. }
  1019. test->timestamp = OSUtils::now();
  1020. _CircuitTestEntry &te = _circuitTests[test->testId];
  1021. te.test = test;
  1022. te.jsonResults = "";
  1023. if (_node)
  1024. _node->circuitTestBegin(test,&(EmbeddedNetworkController::_circuitTestCallback));
  1025. else return 500;
  1026. char json[1024];
  1027. Utils::snprintf(json,sizeof(json),"{\"testId\":\"%.16llx\"}",test->testId);
  1028. responseBody = json;
  1029. responseContentType = "application/json";
  1030. return 200;
  1031. } // else 404
  1032. } else {
  1033. // POST to network ID
  1034. // Magic ID ending with ______ picks a random unused network ID
  1035. if (path[1].substr(10) == "______") {
  1036. nwid = 0;
  1037. uint64_t nwidPrefix = (Utils::hexStrToU64(path[1].substr(0,10).c_str()) << 24) & 0xffffffffff000000ULL;
  1038. uint64_t nwidPostfix = 0;
  1039. for(unsigned long k=0;k<100000;++k) { // sanity limit on trials
  1040. Utils::getSecureRandom(&nwidPostfix,sizeof(nwidPostfix));
  1041. uint64_t tryNwid = nwidPrefix | (nwidPostfix & 0xffffffULL);
  1042. if ((tryNwid & 0xffffffULL) == 0ULL) tryNwid |= 1ULL;
  1043. Utils::snprintf(nwids,sizeof(nwids),"%.16llx",(unsigned long long)tryNwid);
  1044. if (!OSUtils::fileExists(_networkJP(tryNwid,false).c_str())) {
  1045. nwid = tryNwid;
  1046. break;
  1047. }
  1048. }
  1049. if (!nwid)
  1050. return 503;
  1051. }
  1052. json network(_readJson(_networkJP(nwid,true)));
  1053. _initNetwork(network);
  1054. try {
  1055. if (b.count("name")) network["name"] = _jS(b["name"],"");
  1056. if (b.count("private")) network["private"] = _jB(b["private"],true);
  1057. if (b.count("enableBroadcast")) network["enableBroadcast"] = _jB(b["enableBroadcast"],false);
  1058. if (b.count("allowPassiveBridging")) network["allowPassiveBridging"] = _jB(b["allowPassiveBridging"],false);
  1059. if (b.count("multicastLimit")) network["multicastLimit"] = _jI(b["multicastLimit"],32ULL);
  1060. if (b.count("v4AssignMode")) {
  1061. auto nv4m = network["v4AssignMode"];
  1062. if (!nv4m.is_object()) nv4m = json::object();
  1063. if (b["v4AssignMode"].is_string()) { // backward compatibility
  1064. nv4m["zt"] = (_jS(b["v4AssignMode"],"") == "zt");
  1065. } else if (b["v4AssignMode"].is_object()) {
  1066. auto v4m = b["v4AssignMode"];
  1067. if (v4m.count("zt")) nv4m["zt"] = _jB(v4m["zt"],false);
  1068. }
  1069. if (!nv4m.count("zt")) nv4m["zt"] = false;
  1070. }
  1071. if (b.count("v6AssignMode")) {
  1072. auto nv6m = network["v6AssignMode"];
  1073. if (!nv6m.is_object()) nv6m = json::object();
  1074. if (b["v6AssignMode"].is_string()) { // backward compatibility
  1075. std::vector<std::string> v6m(Utils::split(_jS(b["v6AssignMode"],"").c_str(),",","",""));
  1076. std::sort(v6m.begin(),v6m.end());
  1077. v6m.erase(std::unique(v6m.begin(),v6m.end()),v6m.end());
  1078. for(std::vector<std::string>::iterator i(v6m.begin());i!=v6m.end();++i) {
  1079. if (*i == "rfc4193")
  1080. nv6m["rfc4193"] = true;
  1081. else if (*i == "zt")
  1082. nv6m["zt"] = true;
  1083. else if (*i == "6plane")
  1084. nv6m["6plane"] = true;
  1085. }
  1086. } else if (b["v6AssignMode"].is_object()) {
  1087. auto v6m = b["v6AssignMode"];
  1088. if (v6m.count("rfc4193")) nv6m["rfc4193"] = _jB(v6m["rfc4193"],false);
  1089. if (v6m.count("zt")) nv6m["rfc4193"] = _jB(v6m["zt"],false);
  1090. if (v6m.count("6plane")) nv6m["rfc4193"] = _jB(v6m["6plane"],false);
  1091. }
  1092. if (!nv6m.count("rfc4193")) nv6m["rfc4193"] = false;
  1093. if (!nv6m.count("zt")) nv6m["zt"] = false;
  1094. if (!nv6m.count("6plane")) nv6m["6plane"] = false;
  1095. }
  1096. if (b.count("routes")) {
  1097. auto rts = b["routes"];
  1098. if (rts.is_array()) {
  1099. for(unsigned long i=0;i<rts.size();++i) {
  1100. auto rt = rts[i];
  1101. if ((rt.is_object())&&(rt.count("target"))&&(rt.count("via"))) {
  1102. InetAddress t(_jS(rt["target"],""));
  1103. InetAddress v(_jS(rt["via"],""));
  1104. if ( ((t.ss_family == AF_INET)||(t.ss_family == AF_INET6)) && (t.ss_family == v.ss_family) && (t.netmaskBitsValid()) ) {
  1105. auto nrts = network["routes"];
  1106. if (!nrts.is_array()) nrts = json::array();
  1107. json tmp;
  1108. tmp["target"] = t.toString();
  1109. tmp["via"] = v.toIpString();
  1110. nrts.push_back(tmp);
  1111. }
  1112. }
  1113. }
  1114. }
  1115. }
  1116. if (b.count("ipAssignmentPools")) {
  1117. auto ipp = b["ipAssignmentPools"];
  1118. if (ipp.is_array()) {
  1119. for(unsigned long i=0;i<ipp.size();++i) {
  1120. auto ip = ipp[i];
  1121. if ((ip.is_object())&&(ip.count("ipRangeStart"))&&(ip.count("ipRangeEnd"))) {
  1122. InetAddress f(_jS(ip["ipRangeStart"],""));
  1123. InetAddress t(_jS(ip["ipRangeEnd"],""));
  1124. if ( ((f.ss_family == AF_INET)||(f.ss_family == AF_INET6)) && (f.ss_family == t.ss_family) ) {
  1125. auto nipp = network["ipAssignmentPools"];
  1126. if (!nipp.is_array()) nipp = json::array();
  1127. json tmp;
  1128. tmp["ipRangeStart"] = f.toIpString();
  1129. tmp["ipRangeEnd"] = t.toIpString();
  1130. nipp.push_back(tmp);
  1131. }
  1132. }
  1133. }
  1134. }
  1135. }
  1136. if (b.count("rules")) {
  1137. auto rules = b["rules"];
  1138. if (rules.is_array()) {
  1139. json nrules = json::array();
  1140. for(unsigned long i=0;i<rules.size();++i) {
  1141. json rule = rules[i];
  1142. if (rule.is_object()) {
  1143. ZT_VirtualNetworkRule ztr;
  1144. if (_parseRule(rule,ztr)) {
  1145. rule = _renderRule(ztr);
  1146. if ((rule.is_object())&&(rule.count("type"))) {
  1147. nrules.push_back(rule);
  1148. }
  1149. }
  1150. }
  1151. }
  1152. network["rules"] = nrules;
  1153. }
  1154. }
  1155. if (b.count("authTokens")) {
  1156. auto authTokens = b["authTokens"];
  1157. if (authTokens.is_array()) {
  1158. json nat = json::array();
  1159. for(unsigned long i=0;i<authTokens.size();++i) {
  1160. auto token = authTokens[i];
  1161. if (token.is_object()) {
  1162. std::string tstr = token["token"];
  1163. if (tstr.length() > 0) {
  1164. json t = json::object();
  1165. t["token"] = tstr;
  1166. t["expires"] = _jI(token["expires"],0ULL);
  1167. nat.push_back(t);
  1168. }
  1169. }
  1170. }
  1171. network["authTokens"] = nat;
  1172. }
  1173. }
  1174. if (b.count("capabilities")) {
  1175. auto capabilities = b["capabilities"];
  1176. if (capabilities.is_array()) {
  1177. std::map< uint64_t,json > ncaps;
  1178. for(unsigned long i=0;i<capabilities.size();++i) {
  1179. auto cap = capabilities[i];
  1180. if (cap.is_object()) {
  1181. json ncap = json::object();
  1182. const uint64_t capId = _jI(cap["id"],0ULL);
  1183. ncap["id"] = capId;
  1184. auto rules = cap["rules"];
  1185. json nrules = json::array();
  1186. if (rules.is_array()) {
  1187. for(unsigned long i=0;i<rules.size();++i) {
  1188. json rule = rules[i];
  1189. if (rule.is_object()) {
  1190. ZT_VirtualNetworkRule ztr;
  1191. if (_parseRule(rule,ztr)) {
  1192. rule = _renderRule(ztr);
  1193. if ((rule.is_object())&&(rule.count("type"))) {
  1194. nrules.push_back(rule);
  1195. }
  1196. }
  1197. }
  1198. }
  1199. }
  1200. ncap["rules"] = nrules;
  1201. ncaps[capId] = ncap;
  1202. }
  1203. }
  1204. json ncapsa = json::array();
  1205. for(std::map< uint64_t,json >::iterator c(ncaps.begin());c!=ncaps.end();++c)
  1206. ncapsa.push_back(c->second);
  1207. network["capabilities"] = ncapsa;
  1208. }
  1209. }
  1210. } catch ( ... ) {
  1211. return 400;
  1212. }
  1213. network["id"] = nwids;
  1214. network["nwid"] = nwids; // legacy
  1215. auto rev = network["revision"];
  1216. network["revision"] = (rev.is_number() ? ((uint64_t)rev + 1ULL) : 1ULL);
  1217. network["lastModified"] = now;
  1218. _writeJson(_networkJP(nwid,true),network);
  1219. _NetworkMemberInfo nmi;
  1220. _getNetworkMemberInfo(now,nwid,nmi);
  1221. _addNetworkNonPersistedFields(network,now,nmi);
  1222. responseBody = network.dump(2);
  1223. responseContentType = "application/json";
  1224. return 200;
  1225. } // else 404
  1226. } // else 404
  1227. } // else 404
  1228. return 404;
  1229. }
  1230. unsigned int EmbeddedNetworkController::handleControlPlaneHttpDELETE(
  1231. const std::vector<std::string> &path,
  1232. const std::map<std::string,std::string> &urlArgs,
  1233. const std::map<std::string,std::string> &headers,
  1234. const std::string &body,
  1235. std::string &responseBody,
  1236. std::string &responseContentType)
  1237. {
  1238. if (path.empty())
  1239. return 404;
  1240. if (path[0] == "network") {
  1241. if ((path.size() >= 2)&&(path[1].length() == 16)) {
  1242. const uint64_t nwid = Utils::hexStrToU64(path[1].c_str());
  1243. json network(_readJson(_networkJP(nwid,false)));
  1244. if (!network.size())
  1245. return 404;
  1246. if (path.size() >= 3) {
  1247. if ((path.size() == 4)&&(path[2] == "member")&&(path[3].length() == 10)) {
  1248. const uint64_t address = Utils::hexStrToU64(path[3].c_str());
  1249. json member(_readJson(_memberJP(nwid,Address(address),false)));
  1250. if (!member.size())
  1251. return 404;
  1252. OSUtils::rmDashRf(_memberBP(nwid,Address(address),false).c_str());
  1253. responseBody = member.dump(2);
  1254. responseContentType = "application/json";
  1255. return 200;
  1256. }
  1257. } else {
  1258. OSUtils::rmDashRf(_networkBP(nwid,false).c_str());
  1259. {
  1260. Mutex::Lock _l(_networkMemberCache_m);
  1261. _networkMemberCache.erase(nwid);
  1262. }
  1263. responseBody = network.dump(2);
  1264. responseContentType = "application/json";
  1265. return 200;
  1266. }
  1267. } // else 404
  1268. } // else 404
  1269. return 404;
  1270. }
  1271. void EmbeddedNetworkController::_circuitTestCallback(ZT_Node *node,ZT_CircuitTest *test,const ZT_CircuitTestReport *report)
  1272. {
  1273. char tmp[65535];
  1274. EmbeddedNetworkController *const self = reinterpret_cast<EmbeddedNetworkController *>(test->ptr);
  1275. if (!test)
  1276. return;
  1277. if (!report)
  1278. return;
  1279. Mutex::Lock _l(self->_circuitTests_m);
  1280. std::map< uint64_t,_CircuitTestEntry >::iterator cte(self->_circuitTests.find(test->testId));
  1281. if (cte == self->_circuitTests.end()) { // sanity check: a circuit test we didn't launch?
  1282. self->_node->circuitTestEnd(test);
  1283. ::free((void *)test);
  1284. return;
  1285. }
  1286. Utils::snprintf(tmp,sizeof(tmp),
  1287. "%s{\n"
  1288. "\t\"timestamp\": %llu," ZT_EOL_S
  1289. "\t\"testId\": \"%.16llx\"," ZT_EOL_S
  1290. "\t\"upstream\": \"%.10llx\"," ZT_EOL_S
  1291. "\t\"current\": \"%.10llx\"," ZT_EOL_S
  1292. "\t\"receivedTimestamp\": %llu," ZT_EOL_S
  1293. "\t\"remoteTimestamp\": %llu," ZT_EOL_S
  1294. "\t\"sourcePacketId\": \"%.16llx\"," ZT_EOL_S
  1295. "\t\"flags\": %llu," ZT_EOL_S
  1296. "\t\"sourcePacketHopCount\": %u," ZT_EOL_S
  1297. "\t\"errorCode\": %u," ZT_EOL_S
  1298. "\t\"vendor\": %d," ZT_EOL_S
  1299. "\t\"protocolVersion\": %u," ZT_EOL_S
  1300. "\t\"majorVersion\": %u," ZT_EOL_S
  1301. "\t\"minorVersion\": %u," ZT_EOL_S
  1302. "\t\"revision\": %u," ZT_EOL_S
  1303. "\t\"platform\": %d," ZT_EOL_S
  1304. "\t\"architecture\": %d," ZT_EOL_S
  1305. "\t\"receivedOnLocalAddress\": \"%s\"," ZT_EOL_S
  1306. "\t\"receivedFromRemoteAddress\": \"%s\"" ZT_EOL_S
  1307. "}",
  1308. ((cte->second.jsonResults.length() > 0) ? ",\n" : ""),
  1309. (unsigned long long)report->timestamp,
  1310. (unsigned long long)test->testId,
  1311. (unsigned long long)report->upstream,
  1312. (unsigned long long)report->current,
  1313. (unsigned long long)OSUtils::now(),
  1314. (unsigned long long)report->remoteTimestamp,
  1315. (unsigned long long)report->sourcePacketId,
  1316. (unsigned long long)report->flags,
  1317. report->sourcePacketHopCount,
  1318. report->errorCode,
  1319. (int)report->vendor,
  1320. report->protocolVersion,
  1321. report->majorVersion,
  1322. report->minorVersion,
  1323. report->revision,
  1324. (int)report->platform,
  1325. (int)report->architecture,
  1326. reinterpret_cast<const InetAddress *>(&(report->receivedOnLocalAddress))->toString().c_str(),
  1327. reinterpret_cast<const InetAddress *>(&(report->receivedFromRemoteAddress))->toString().c_str());
  1328. cte->second.jsonResults.append(tmp);
  1329. }
  1330. void EmbeddedNetworkController::_getNetworkMemberInfo(uint64_t now,uint64_t nwid,_NetworkMemberInfo &nmi)
  1331. {
  1332. Mutex::Lock _mcl(_networkMemberCache_m);
  1333. auto memberCacheEntry = _networkMemberCache[nwid];
  1334. if ((now - memberCacheEntry.second) >= ZT_NETCONF_NETWORK_MEMBER_CACHE_EXPIRE) {
  1335. const std::string bp(_networkBP(nwid,false) + ZT_PATH_SEPARATOR_S + "member");
  1336. std::vector<std::string> members(OSUtils::listSubdirectories(bp.c_str()));
  1337. for(std::vector<std::string>::iterator m(members.begin());m!=members.end();++m) {
  1338. if (m->length() == ZT_ADDRESS_LENGTH_HEX) {
  1339. nlohmann::json mj(_readJson(bp + ZT_PATH_SEPARATOR_S + *m + ZT_PATH_SEPARATOR_S + "config.json"));
  1340. if ((mj.is_object())&&(mj.size() > 0)) {
  1341. memberCacheEntry.first[Address(*m)] = mj;
  1342. }
  1343. }
  1344. }
  1345. memberCacheEntry.second = now;
  1346. }
  1347. nmi.totalMemberCount = memberCacheEntry.first.size();
  1348. for(std::map< Address,nlohmann::json >::const_iterator nm(memberCacheEntry.first.begin());nm!=memberCacheEntry.first.end();++nm) {
  1349. if (_jB(nm->second["authorized"],false)) {
  1350. ++nmi.authorizedMemberCount;
  1351. auto mlog = nm->second["recentLog"];
  1352. if ((mlog.is_array())&&(mlog.size() > 0)) {
  1353. auto mlog1 = mlog[0];
  1354. if (mlog1.is_object()) {
  1355. if ((now - _jI(mlog1["ts"],0ULL)) < ZT_NETCONF_NODE_ACTIVE_THRESHOLD)
  1356. ++nmi.activeMemberCount;
  1357. }
  1358. }
  1359. if (_jB(nm->second["activeBridge"],false)) {
  1360. nmi.activeBridges.insert(nm->first);
  1361. }
  1362. auto mips = nm->second["ipAssignments"];
  1363. if (mips.is_array()) {
  1364. for(unsigned long i=0;i<mips.size();++i) {
  1365. InetAddress mip(_jS(mips[i],""));
  1366. if ((mip.ss_family == AF_INET)||(mip.ss_family == AF_INET6))
  1367. nmi.allocatedIps.insert(mip);
  1368. }
  1369. }
  1370. } else {
  1371. nmi.mostRecentDeauthTime = std::max(nmi.mostRecentDeauthTime,_jI(nm->second["lastDeauthorizedTime"],0ULL));
  1372. }
  1373. }
  1374. }
  1375. } // namespace ZeroTier