EmbeddedNetworkController.cpp 59 KB

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