ControlPlane.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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 "ControlPlane.hpp"
  19. #include "OneService.hpp"
  20. #include "../version.h"
  21. #include "../include/ZeroTierOne.h"
  22. #ifdef ZT_USE_SYSTEM_HTTP_PARSER
  23. #include <http_parser.h>
  24. #else
  25. #include "../ext/http-parser/http_parser.h"
  26. #endif
  27. #include "../ext/json/json.hpp"
  28. #include "../controller/EmbeddedNetworkController.hpp"
  29. #include "../node/InetAddress.hpp"
  30. #include "../node/Node.hpp"
  31. #include "../node/Utils.hpp"
  32. #include "../osdep/OSUtils.hpp"
  33. namespace ZeroTier {
  34. static std::string _jsonEscape(const char *s)
  35. {
  36. std::string buf;
  37. for(const char *p=s;(*p);++p) {
  38. switch(*p) {
  39. case '\t': buf.append("\\t"); break;
  40. case '\b': buf.append("\\b"); break;
  41. case '\r': buf.append("\\r"); break;
  42. case '\n': buf.append("\\n"); break;
  43. case '\f': buf.append("\\f"); break;
  44. case '"': buf.append("\\\""); break;
  45. case '\\': buf.append("\\\\"); break;
  46. case '/': buf.append("\\/"); break;
  47. default: buf.push_back(*p); break;
  48. }
  49. }
  50. return buf;
  51. }
  52. static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); }
  53. static std::string _jsonEnumerate(const struct sockaddr_storage *ss,unsigned int count)
  54. {
  55. std::string buf;
  56. buf.push_back('[');
  57. for(unsigned int i=0;i<count;++i) {
  58. if (i > 0)
  59. buf.push_back(',');
  60. buf.push_back('"');
  61. buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(ss[i]))->toString()));
  62. buf.push_back('"');
  63. }
  64. buf.push_back(']');
  65. return buf;
  66. }
  67. static std::string _jsonEnumerate(const ZT_VirtualNetworkRoute *routes,unsigned int count)
  68. {
  69. std::string buf;
  70. buf.push_back('[');
  71. for(unsigned int i=0;i<count;++i) {
  72. if (i > 0)
  73. buf.push_back(',');
  74. buf.append("{\"target\":\"");
  75. buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(routes[i].target))->toString()));
  76. buf.append("\",\"via\":");
  77. if (routes[i].via.ss_family == routes[i].target.ss_family) {
  78. buf.push_back('"');
  79. buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(routes[i].via))->toIpString()));
  80. buf.append("\",");
  81. } else buf.append("null,");
  82. char tmp[1024];
  83. Utils::snprintf(tmp,sizeof(tmp),"\"flags\":%u,\"metric\":%u}",(unsigned int)routes[i].flags,(unsigned int)routes[i].metric);
  84. buf.append(tmp);
  85. }
  86. buf.push_back(']');
  87. return buf;
  88. }
  89. static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
  90. {
  91. char json[4096];
  92. char prefix[32];
  93. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  94. return;
  95. for(unsigned int i=0;i<depth;++i)
  96. prefix[i] = '\t';
  97. prefix[depth] = '\0';
  98. const char *nstatus = "",*ntype = "";
  99. switch(nc->status) {
  100. case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  101. case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
  102. case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  103. case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  104. case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  105. case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  106. }
  107. switch(nc->type) {
  108. case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  109. case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  110. }
  111. Utils::snprintf(json,sizeof(json),
  112. "%s{\n"
  113. "%s\t\"nwid\": \"%.16llx\",\n"
  114. "%s\t\"mac\": \"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",\n"
  115. "%s\t\"name\": \"%s\",\n"
  116. "%s\t\"status\": \"%s\",\n"
  117. "%s\t\"type\": \"%s\",\n"
  118. "%s\t\"mtu\": %u,\n"
  119. "%s\t\"dhcp\": %s,\n"
  120. "%s\t\"bridge\": %s,\n"
  121. "%s\t\"broadcastEnabled\": %s,\n"
  122. "%s\t\"portError\": %d,\n"
  123. "%s\t\"netconfRevision\": %lu,\n"
  124. "%s\t\"assignedAddresses\": %s,\n"
  125. "%s\t\"routes\": %s,\n"
  126. "%s\t\"portDeviceName\": \"%s\",\n"
  127. "%s\t\"allowManaged\": %s,\n"
  128. "%s\t\"allowGlobal\": %s,\n"
  129. "%s\t\"allowDefault\": %s\n"
  130. "%s}",
  131. prefix,
  132. prefix,nc->nwid,
  133. prefix,(unsigned int)((nc->mac >> 40) & 0xff),(unsigned int)((nc->mac >> 32) & 0xff),(unsigned int)((nc->mac >> 24) & 0xff),(unsigned int)((nc->mac >> 16) & 0xff),(unsigned int)((nc->mac >> 8) & 0xff),(unsigned int)(nc->mac & 0xff),
  134. prefix,_jsonEscape(nc->name).c_str(),
  135. prefix,nstatus,
  136. prefix,ntype,
  137. prefix,nc->mtu,
  138. prefix,(nc->dhcp == 0) ? "false" : "true",
  139. prefix,(nc->bridge == 0) ? "false" : "true",
  140. prefix,(nc->broadcastEnabled == 0) ? "false" : "true",
  141. prefix,nc->portError,
  142. prefix,nc->netconfRevision,
  143. prefix,_jsonEnumerate(nc->assignedAddresses,nc->assignedAddressCount).c_str(),
  144. prefix,_jsonEnumerate(nc->routes,nc->routeCount).c_str(),
  145. prefix,_jsonEscape(portDeviceName).c_str(),
  146. prefix,(localSettings.allowManaged) ? "true" : "false",
  147. prefix,(localSettings.allowGlobal) ? "true" : "false",
  148. prefix,(localSettings.allowDefault) ? "true" : "false",
  149. prefix);
  150. buf.append(json);
  151. }
  152. static std::string _jsonEnumerate(unsigned int depth,const ZT_PeerPhysicalPath *pp,unsigned int count)
  153. {
  154. char json[1024];
  155. char prefix[32];
  156. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  157. return std::string();
  158. for(unsigned int i=0;i<depth;++i)
  159. prefix[i] = '\t';
  160. prefix[depth] = '\0';
  161. std::string buf;
  162. for(unsigned int i=0;i<count;++i) {
  163. if (i > 0)
  164. buf.push_back(',');
  165. Utils::snprintf(json,sizeof(json),
  166. "{\n"
  167. "%s\t\"address\": \"%s\",\n"
  168. "%s\t\"lastSend\": %llu,\n"
  169. "%s\t\"lastReceive\": %llu,\n"
  170. "%s\t\"active\": true,\n"
  171. "%s\t\"preferred\": %s,\n"
  172. "%s\t\"trustedPathId\": %llu\n"
  173. "%s}",
  174. prefix,_jsonEscape(reinterpret_cast<const InetAddress *>(&(pp[i].address))->toString()).c_str(),
  175. prefix,pp[i].lastSend,
  176. prefix,pp[i].lastReceive,
  177. prefix,
  178. prefix,(pp[i].preferred == 0) ? "false" : "true",
  179. prefix,pp[i].trustedPathId,
  180. prefix);
  181. buf.append(json);
  182. }
  183. return buf;
  184. }
  185. static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_Peer *peer)
  186. {
  187. char json[1024];
  188. char prefix[32];
  189. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  190. return;
  191. for(unsigned int i=0;i<depth;++i)
  192. prefix[i] = '\t';
  193. prefix[depth] = '\0';
  194. const char *prole = "";
  195. switch(peer->role) {
  196. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  197. case ZT_PEER_ROLE_RELAY: prole = "RELAY"; break;
  198. case ZT_PEER_ROLE_ROOT: prole = "ROOT"; break;
  199. }
  200. Utils::snprintf(json,sizeof(json),
  201. "%s{\n"
  202. "%s\t\"address\": \"%.10llx\",\n"
  203. "%s\t\"lastUnicastFrame\": %llu,\n"
  204. "%s\t\"lastMulticastFrame\": %llu,\n"
  205. "%s\t\"versionMajor\": %d,\n"
  206. "%s\t\"versionMinor\": %d,\n"
  207. "%s\t\"versionRev\": %d,\n"
  208. "%s\t\"version\": \"%d.%d.%d\",\n"
  209. "%s\t\"latency\": %u,\n"
  210. "%s\t\"role\": \"%s\",\n"
  211. "%s\t\"paths\": [%s]\n"
  212. "%s}",
  213. prefix,
  214. prefix,peer->address,
  215. prefix,peer->lastUnicastFrame,
  216. prefix,peer->lastMulticastFrame,
  217. prefix,peer->versionMajor,
  218. prefix,peer->versionMinor,
  219. prefix,peer->versionRev,
  220. prefix,peer->versionMajor,peer->versionMinor,peer->versionRev,
  221. prefix,peer->latency,
  222. prefix,prole,
  223. prefix,_jsonEnumerate(depth+1,peer->paths,peer->pathCount).c_str(),
  224. prefix);
  225. buf.append(json);
  226. }
  227. ControlPlane::ControlPlane(OneService *svc,Node *n,const char *uiStaticPath) :
  228. _svc(svc),
  229. _node(n),
  230. _controller((EmbeddedNetworkController *)0),
  231. _uiStaticPath((uiStaticPath) ? uiStaticPath : "")
  232. {
  233. }
  234. ControlPlane::~ControlPlane()
  235. {
  236. }
  237. unsigned int ControlPlane::handleRequest(
  238. const InetAddress &fromAddress,
  239. unsigned int httpMethod,
  240. const std::string &path,
  241. const std::map<std::string,std::string> &headers,
  242. const std::string &body,
  243. std::string &responseBody,
  244. std::string &responseContentType)
  245. {
  246. char json[8194];
  247. unsigned int scode = 404;
  248. std::vector<std::string> ps(Utils::split(path.c_str(),"/","",""));
  249. std::map<std::string,std::string> urlArgs;
  250. Mutex::Lock _l(_lock);
  251. if (!((fromAddress.ipsEqual(InetAddress::LO4))||(fromAddress.ipsEqual(InetAddress::LO6))))
  252. return 403; // Forbidden: we only allow access from localhost right now
  253. /* Note: this is kind of restricted in what it'll take. It does not support
  254. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  255. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  256. * paths to simply-named resources. */
  257. if (ps.size() > 0) {
  258. std::size_t qpos = ps[ps.size() - 1].find('?');
  259. if (qpos != std::string::npos) {
  260. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  261. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  262. std::vector<std::string> asplit(Utils::split(args.c_str(),"&","",""));
  263. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  264. std::size_t eqpos = a->find('=');
  265. if (eqpos == std::string::npos)
  266. urlArgs[*a] = "";
  267. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  268. }
  269. }
  270. } else {
  271. ps.push_back(std::string("index.html"));
  272. }
  273. bool isAuth = false;
  274. {
  275. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  276. if ((ah != headers.end())&&(_authTokens.count(ah->second) > 0)) {
  277. isAuth = true;
  278. } else {
  279. ah = urlArgs.find("auth");
  280. if ((ah != urlArgs.end())&&(_authTokens.count(ah->second) > 0))
  281. isAuth = true;
  282. }
  283. }
  284. if (httpMethod == HTTP_GET) {
  285. std::string ext;
  286. std::size_t dotIdx = ps[0].find_last_of('.');
  287. if (dotIdx != std::string::npos)
  288. ext = ps[0].substr(dotIdx);
  289. if ((ps.size() == 1)&&(ext.length() >= 2)&&(ext[0] == '.')) {
  290. /* Static web pages can be served without authentication to enable a simple web
  291. * UI. This is still only allowed from approved IP addresses. Anything with a
  292. * dot in the first path element (e.g. foo.html) is considered a static page,
  293. * as nothing in the API is so named. */
  294. if (_uiStaticPath.length() > 0) {
  295. if (ext == ".html")
  296. responseContentType = "text/html";
  297. else if (ext == ".js")
  298. responseContentType = "application/javascript";
  299. else if (ext == ".jsx")
  300. responseContentType = "text/jsx";
  301. else if (ext == ".json")
  302. responseContentType = "application/json";
  303. else if (ext == ".css")
  304. responseContentType = "text/css";
  305. else if (ext == ".png")
  306. responseContentType = "image/png";
  307. else if (ext == ".jpg")
  308. responseContentType = "image/jpeg";
  309. else if (ext == ".gif")
  310. responseContentType = "image/gif";
  311. else if (ext == ".txt")
  312. responseContentType = "text/plain";
  313. else if (ext == ".xml")
  314. responseContentType = "text/xml";
  315. else if (ext == ".svg")
  316. responseContentType = "image/svg+xml";
  317. else responseContentType = "application/octet-stream";
  318. scode = OSUtils::readFile((_uiStaticPath + ZT_PATH_SEPARATOR_S + ps[0]).c_str(),responseBody) ? 200 : 404;
  319. } else {
  320. scode = 404;
  321. }
  322. } else if (isAuth) {
  323. /* Things that require authentication -- a.k.a. everything but static web app pages. */
  324. if (ps[0] == "status") {
  325. responseContentType = "application/json";
  326. ZT_NodeStatus status;
  327. _node->status(&status);
  328. std::string clusterJson;
  329. #ifdef ZT_ENABLE_CLUSTER
  330. {
  331. ZT_ClusterStatus cs;
  332. _node->clusterStatus(&cs);
  333. if (cs.clusterSize >= 1) {
  334. char t[1024];
  335. Utils::snprintf(t,sizeof(t),"{\n\t\t\"myId\": %u,\n\t\t\"clusterSize\": %u,\n\t\t\"members\": [",cs.myId,cs.clusterSize);
  336. clusterJson.append(t);
  337. for(unsigned int i=0;i<cs.clusterSize;++i) {
  338. Utils::snprintf(t,sizeof(t),"%s\t\t\t{\n\t\t\t\t\"id\": %u,\n\t\t\t\t\"msSinceLastHeartbeat\": %u,\n\t\t\t\t\"alive\": %s,\n\t\t\t\t\"x\": %d,\n\t\t\t\t\"y\": %d,\n\t\t\t\t\"z\": %d,\n\t\t\t\t\"load\": %llu,\n\t\t\t\t\"peers\": %llu\n\t\t\t}",
  339. ((i == 0) ? "\n" : ",\n"),
  340. cs.members[i].id,
  341. cs.members[i].msSinceLastHeartbeat,
  342. (cs.members[i].alive != 0) ? "true" : "false",
  343. cs.members[i].x,
  344. cs.members[i].y,
  345. cs.members[i].z,
  346. cs.members[i].load,
  347. cs.members[i].peers);
  348. clusterJson.append(t);
  349. }
  350. clusterJson.append(" ]\n\t\t}");
  351. }
  352. }
  353. #endif
  354. Utils::snprintf(json,sizeof(json),
  355. "{\n"
  356. "\t\"address\": \"%.10llx\",\n"
  357. "\t\"publicIdentity\": \"%s\",\n"
  358. "\t\"worldId\": %llu,\n"
  359. "\t\"worldTimestamp\": %llu,\n"
  360. "\t\"online\": %s,\n"
  361. "\t\"tcpFallbackActive\": %s,\n"
  362. "\t\"versionMajor\": %d,\n"
  363. "\t\"versionMinor\": %d,\n"
  364. "\t\"versionRev\": %d,\n"
  365. "\t\"version\": \"%d.%d.%d\",\n"
  366. "\t\"clock\": %llu,\n"
  367. "\t\"cluster\": %s\n"
  368. "}\n",
  369. status.address,
  370. status.publicIdentity,
  371. status.worldId,
  372. status.worldTimestamp,
  373. (status.online) ? "true" : "false",
  374. (_svc->tcpFallbackActive()) ? "true" : "false",
  375. ZEROTIER_ONE_VERSION_MAJOR,
  376. ZEROTIER_ONE_VERSION_MINOR,
  377. ZEROTIER_ONE_VERSION_REVISION,
  378. ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION,
  379. (unsigned long long)OSUtils::now(),
  380. ((clusterJson.length() > 0) ? clusterJson.c_str() : "null"));
  381. responseBody = json;
  382. scode = 200;
  383. } else if (ps[0] == "config") {
  384. responseContentType = "application/json";
  385. responseBody = "{}"; // TODO
  386. scode = 200;
  387. } else if (ps[0] == "network") {
  388. ZT_VirtualNetworkList *nws = _node->networks();
  389. if (nws) {
  390. if (ps.size() == 1) {
  391. // Return [array] of all networks
  392. responseContentType = "application/json";
  393. responseBody = "[\n";
  394. for(unsigned long i=0;i<nws->networkCount;++i) {
  395. if (i > 0)
  396. responseBody.append(",");
  397. OneService::NetworkSettings localSettings;
  398. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  399. _jsonAppend(1,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  400. }
  401. responseBody.append("\n]\n");
  402. scode = 200;
  403. } else if (ps.size() == 2) {
  404. // Return a single network by ID or 404 if not found
  405. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  406. for(unsigned long i=0;i<nws->networkCount;++i) {
  407. if (nws->networks[i].nwid == wantnw) {
  408. responseContentType = "application/json";
  409. OneService::NetworkSettings localSettings;
  410. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  411. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  412. responseBody.push_back('\n');
  413. scode = 200;
  414. break;
  415. }
  416. }
  417. } // else 404
  418. _node->freeQueryResult((void *)nws);
  419. } else scode = 500;
  420. } else if (ps[0] == "peer") {
  421. ZT_PeerList *pl = _node->peers();
  422. if (pl) {
  423. if (ps.size() == 1) {
  424. // Return [array] of all peers
  425. responseContentType = "application/json";
  426. responseBody = "[\n";
  427. for(unsigned long i=0;i<pl->peerCount;++i) {
  428. if (i > 0)
  429. responseBody.append(",\n");
  430. _jsonAppend(1,responseBody,&(pl->peers[i]));
  431. }
  432. responseBody.append("\n]\n");
  433. scode = 200;
  434. } else if (ps.size() == 2) {
  435. // Return a single peer by ID or 404 if not found
  436. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  437. for(unsigned long i=0;i<pl->peerCount;++i) {
  438. if (pl->peers[i].address == wantp) {
  439. responseContentType = "application/json";
  440. _jsonAppend(0,responseBody,&(pl->peers[i]));
  441. responseBody.push_back('\n');
  442. scode = 200;
  443. break;
  444. }
  445. }
  446. } // else 404
  447. _node->freeQueryResult((void *)pl);
  448. } else scode = 500;
  449. } else if (ps[0] == "newIdentity") {
  450. // Return a newly generated ZeroTier identity -- this is primarily for debugging
  451. // and testing to make it easy for automated test scripts to generate test IDs.
  452. Identity newid;
  453. newid.generate();
  454. responseBody = newid.toString(true);
  455. responseContentType = "text/plain";
  456. scode = 200;
  457. } else {
  458. if (_controller)
  459. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  460. else scode = 404;
  461. }
  462. } else scode = 401; // isAuth == false
  463. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  464. if (isAuth) {
  465. if (ps[0] == "config") {
  466. // TODO
  467. } else if (ps[0] == "network") {
  468. if (ps.size() == 2) {
  469. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  470. _node->join(wantnw,(void *)0); // does nothing if we are a member
  471. ZT_VirtualNetworkList *nws = _node->networks();
  472. if (nws) {
  473. for(unsigned long i=0;i<nws->networkCount;++i) {
  474. if (nws->networks[i].nwid == wantnw) {
  475. OneService::NetworkSettings localSettings;
  476. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  477. try {
  478. nlohmann::json j(nlohmann::json::parse(body));
  479. if (j.is_object()) {
  480. auto allowManaged = j["allowManaged"];
  481. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  482. auto allowGlobal = j["allowGlobal"];
  483. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  484. auto allowDefault = j["allowDefault"];
  485. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  486. }
  487. } catch ( ... ) {
  488. // discard invalid JSON
  489. }
  490. _svc->setNetworkSettings(nws->networks[i].nwid,localSettings);
  491. responseContentType = "application/json";
  492. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  493. responseBody.push_back('\n');
  494. scode = 200;
  495. break;
  496. }
  497. }
  498. _node->freeQueryResult((void *)nws);
  499. } else scode = 500;
  500. }
  501. } else {
  502. if (_controller)
  503. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  504. else scode = 404;
  505. }
  506. } else scode = 401; // isAuth == false
  507. } else if (httpMethod == HTTP_DELETE) {
  508. if (isAuth) {
  509. if (ps[0] == "config") {
  510. // TODO
  511. } else if (ps[0] == "network") {
  512. ZT_VirtualNetworkList *nws = _node->networks();
  513. if (nws) {
  514. if (ps.size() == 2) {
  515. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  516. for(unsigned long i=0;i<nws->networkCount;++i) {
  517. if (nws->networks[i].nwid == wantnw) {
  518. _node->leave(wantnw,(void **)0);
  519. responseBody = "true";
  520. responseContentType = "application/json";
  521. scode = 200;
  522. break;
  523. }
  524. }
  525. } // else 404
  526. _node->freeQueryResult((void *)nws);
  527. } else scode = 500;
  528. } else {
  529. if (_controller)
  530. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  531. else scode = 404;
  532. }
  533. } else {
  534. scode = 401; // isAuth = false
  535. }
  536. } else {
  537. scode = 400;
  538. responseBody = "Method not supported.";
  539. }
  540. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  541. // Also double-check isAuth since forbidding this without auth feels safer.
  542. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  543. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  544. if (responseBody.length() > 0)
  545. responseBody = jsonp->second + "(" + responseBody + ");";
  546. else responseBody = jsonp->second + "(null);";
  547. responseContentType = "application/javascript";
  548. }
  549. return scode;
  550. }
  551. } // namespace ZeroTier