EmbeddedNetworkController.cpp 58 KB

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