ControlPlane.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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[2048];
  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\": %s,\n"
  171. "%s\t\"expired\": %s,\n"
  172. "%s\t\"preferred\": %s,\n"
  173. "%s\t\"trustedPathId\": %llu\n"
  174. "%s}",
  175. prefix,_jsonEscape(reinterpret_cast<const InetAddress *>(&(pp[i].address))->toString()).c_str(),
  176. prefix,pp[i].lastSend,
  177. prefix,pp[i].lastReceive,
  178. prefix,(pp[i].expired != 0) ? "false" : "true",
  179. prefix,(pp[i].expired == 0) ? "false" : "true",
  180. prefix,(pp[i].preferred == 0) ? "false" : "true",
  181. prefix,pp[i].trustedPathId,
  182. prefix);
  183. buf.append(json);
  184. }
  185. return buf;
  186. }
  187. static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_Peer *peer)
  188. {
  189. char json[2048];
  190. char prefix[32];
  191. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  192. return;
  193. for(unsigned int i=0;i<depth;++i)
  194. prefix[i] = '\t';
  195. prefix[depth] = '\0';
  196. const char *prole = "";
  197. switch(peer->role) {
  198. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  199. case ZT_PEER_ROLE_UPSTREAM: prole = "UPSTREAM"; break;
  200. case ZT_PEER_ROLE_ROOT: prole = "ROOT"; break;
  201. }
  202. Utils::snprintf(json,sizeof(json),
  203. "%s{\n"
  204. "%s\t\"address\": \"%.10llx\",\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->versionMajor,
  216. prefix,peer->versionMinor,
  217. prefix,peer->versionRev,
  218. prefix,peer->versionMajor,peer->versionMinor,peer->versionRev,
  219. prefix,peer->latency,
  220. prefix,prole,
  221. prefix,_jsonEnumerate(depth+1,peer->paths,peer->pathCount).c_str(),
  222. prefix);
  223. buf.append(json);
  224. }
  225. ControlPlane::ControlPlane(OneService *svc,Node *n,const char *uiStaticPath) :
  226. _svc(svc),
  227. _node(n),
  228. _controller((EmbeddedNetworkController *)0),
  229. _uiStaticPath((uiStaticPath) ? uiStaticPath : "")
  230. {
  231. }
  232. ControlPlane::~ControlPlane()
  233. {
  234. }
  235. unsigned int ControlPlane::handleRequest(
  236. const InetAddress &fromAddress,
  237. unsigned int httpMethod,
  238. const std::string &path,
  239. const std::map<std::string,std::string> &headers,
  240. const std::string &body,
  241. std::string &responseBody,
  242. std::string &responseContentType)
  243. {
  244. char json[8194];
  245. unsigned int scode = 404;
  246. std::vector<std::string> ps(Utils::split(path.c_str(),"/","",""));
  247. std::map<std::string,std::string> urlArgs;
  248. Mutex::Lock _l(_lock);
  249. /* Note: this is kind of restricted in what it'll take. It does not support
  250. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  251. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  252. * paths to simply-named resources. */
  253. if (ps.size() > 0) {
  254. std::size_t qpos = ps[ps.size() - 1].find('?');
  255. if (qpos != std::string::npos) {
  256. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  257. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  258. std::vector<std::string> asplit(Utils::split(args.c_str(),"&","",""));
  259. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  260. std::size_t eqpos = a->find('=');
  261. if (eqpos == std::string::npos)
  262. urlArgs[*a] = "";
  263. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  264. }
  265. }
  266. } else {
  267. ps.push_back(std::string("index.html"));
  268. }
  269. bool isAuth = false;
  270. {
  271. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  272. if ((ah != headers.end())&&(_authTokens.count(ah->second) > 0)) {
  273. isAuth = true;
  274. } else {
  275. ah = urlArgs.find("auth");
  276. if ((ah != urlArgs.end())&&(_authTokens.count(ah->second) > 0))
  277. isAuth = true;
  278. }
  279. }
  280. if (httpMethod == HTTP_GET) {
  281. std::string ext;
  282. std::size_t dotIdx = ps[0].find_last_of('.');
  283. if (dotIdx != std::string::npos)
  284. ext = ps[0].substr(dotIdx);
  285. if ((ps.size() == 1)&&(ext.length() >= 2)&&(ext[0] == '.')) {
  286. /* Static web pages can be served without authentication to enable a simple web
  287. * UI. This is still only allowed from approved IP addresses. Anything with a
  288. * dot in the first path element (e.g. foo.html) is considered a static page,
  289. * as nothing in the API is so named. */
  290. if (_uiStaticPath.length() > 0) {
  291. if (ext == ".html")
  292. responseContentType = "text/html";
  293. else if (ext == ".js")
  294. responseContentType = "application/javascript";
  295. else if (ext == ".jsx")
  296. responseContentType = "text/jsx";
  297. else if (ext == ".json")
  298. responseContentType = "application/json";
  299. else if (ext == ".css")
  300. responseContentType = "text/css";
  301. else if (ext == ".png")
  302. responseContentType = "image/png";
  303. else if (ext == ".jpg")
  304. responseContentType = "image/jpeg";
  305. else if (ext == ".gif")
  306. responseContentType = "image/gif";
  307. else if (ext == ".txt")
  308. responseContentType = "text/plain";
  309. else if (ext == ".xml")
  310. responseContentType = "text/xml";
  311. else if (ext == ".svg")
  312. responseContentType = "image/svg+xml";
  313. else responseContentType = "application/octet-stream";
  314. scode = OSUtils::readFile((_uiStaticPath + ZT_PATH_SEPARATOR_S + ps[0]).c_str(),responseBody) ? 200 : 404;
  315. } else {
  316. scode = 404;
  317. }
  318. } else if (isAuth) {
  319. /* Things that require authentication -- a.k.a. everything but static web app pages. */
  320. if (ps[0] == "status") {
  321. responseContentType = "application/json";
  322. ZT_NodeStatus status;
  323. _node->status(&status);
  324. std::string clusterJson;
  325. #ifdef ZT_ENABLE_CLUSTER
  326. {
  327. ZT_ClusterStatus cs;
  328. _node->clusterStatus(&cs);
  329. if (cs.clusterSize >= 1) {
  330. char t[1024];
  331. Utils::snprintf(t,sizeof(t),"{\n\t\t\"myId\": %u,\n\t\t\"clusterSize\": %u,\n\t\t\"members\": [",cs.myId,cs.clusterSize);
  332. clusterJson.append(t);
  333. for(unsigned int i=0;i<cs.clusterSize;++i) {
  334. 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}",
  335. ((i == 0) ? "\n" : ",\n"),
  336. cs.members[i].id,
  337. cs.members[i].msSinceLastHeartbeat,
  338. (cs.members[i].alive != 0) ? "true" : "false",
  339. cs.members[i].x,
  340. cs.members[i].y,
  341. cs.members[i].z,
  342. cs.members[i].load,
  343. cs.members[i].peers);
  344. clusterJson.append(t);
  345. }
  346. clusterJson.append(" ]\n\t\t}");
  347. }
  348. }
  349. #endif
  350. Utils::snprintf(json,sizeof(json),
  351. "{\n"
  352. "\t\"address\": \"%.10llx\",\n"
  353. "\t\"publicIdentity\": \"%s\",\n"
  354. "\t\"worldId\": %llu,\n"
  355. "\t\"worldTimestamp\": %llu,\n"
  356. "\t\"online\": %s,\n"
  357. "\t\"tcpFallbackActive\": %s,\n"
  358. "\t\"versionMajor\": %d,\n"
  359. "\t\"versionMinor\": %d,\n"
  360. "\t\"versionRev\": %d,\n"
  361. "\t\"version\": \"%d.%d.%d\",\n"
  362. "\t\"clock\": %llu,\n"
  363. "\t\"cluster\": %s\n"
  364. "}\n",
  365. status.address,
  366. status.publicIdentity,
  367. status.worldId,
  368. status.worldTimestamp,
  369. (status.online) ? "true" : "false",
  370. (_svc->tcpFallbackActive()) ? "true" : "false",
  371. ZEROTIER_ONE_VERSION_MAJOR,
  372. ZEROTIER_ONE_VERSION_MINOR,
  373. ZEROTIER_ONE_VERSION_REVISION,
  374. ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION,
  375. (unsigned long long)OSUtils::now(),
  376. ((clusterJson.length() > 0) ? clusterJson.c_str() : "null"));
  377. responseBody = json;
  378. scode = 200;
  379. } else if (ps[0] == "config") {
  380. responseContentType = "application/json";
  381. responseBody = "{}"; // TODO
  382. scode = 200;
  383. } else if (ps[0] == "network") {
  384. ZT_VirtualNetworkList *nws = _node->networks();
  385. if (nws) {
  386. if (ps.size() == 1) {
  387. // Return [array] of all networks
  388. responseContentType = "application/json";
  389. responseBody = "[\n";
  390. for(unsigned long i=0;i<nws->networkCount;++i) {
  391. if (i > 0)
  392. responseBody.append(",");
  393. OneService::NetworkSettings localSettings;
  394. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  395. _jsonAppend(1,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  396. }
  397. responseBody.append("\n]\n");
  398. scode = 200;
  399. } else if (ps.size() == 2) {
  400. // Return a single network by ID or 404 if not found
  401. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  402. for(unsigned long i=0;i<nws->networkCount;++i) {
  403. if (nws->networks[i].nwid == wantnw) {
  404. responseContentType = "application/json";
  405. OneService::NetworkSettings localSettings;
  406. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  407. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  408. responseBody.push_back('\n');
  409. scode = 200;
  410. break;
  411. }
  412. }
  413. } // else 404
  414. _node->freeQueryResult((void *)nws);
  415. } else scode = 500;
  416. } else if (ps[0] == "peer") {
  417. ZT_PeerList *pl = _node->peers();
  418. if (pl) {
  419. if (ps.size() == 1) {
  420. // Return [array] of all peers
  421. responseContentType = "application/json";
  422. responseBody = "[\n";
  423. for(unsigned long i=0;i<pl->peerCount;++i) {
  424. if (i > 0)
  425. responseBody.append(",\n");
  426. _jsonAppend(1,responseBody,&(pl->peers[i]));
  427. }
  428. responseBody.append("\n]\n");
  429. scode = 200;
  430. } else if (ps.size() == 2) {
  431. // Return a single peer by ID or 404 if not found
  432. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  433. for(unsigned long i=0;i<pl->peerCount;++i) {
  434. if (pl->peers[i].address == wantp) {
  435. responseContentType = "application/json";
  436. _jsonAppend(0,responseBody,&(pl->peers[i]));
  437. responseBody.push_back('\n');
  438. scode = 200;
  439. break;
  440. }
  441. }
  442. } // else 404
  443. _node->freeQueryResult((void *)pl);
  444. } else scode = 500;
  445. } else if (ps[0] == "newIdentity") {
  446. // Return a newly generated ZeroTier identity -- this is primarily for debugging
  447. // and testing to make it easy for automated test scripts to generate test IDs.
  448. Identity newid;
  449. newid.generate();
  450. responseBody = newid.toString(true);
  451. responseContentType = "text/plain";
  452. scode = 200;
  453. } else {
  454. if (_controller)
  455. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  456. else scode = 404;
  457. }
  458. } else scode = 401; // isAuth == false
  459. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  460. if (isAuth) {
  461. if (ps[0] == "config") {
  462. // TODO
  463. } else if (ps[0] == "network") {
  464. if (ps.size() == 2) {
  465. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  466. _node->join(wantnw,(void *)0); // does nothing if we are a member
  467. ZT_VirtualNetworkList *nws = _node->networks();
  468. if (nws) {
  469. for(unsigned long i=0;i<nws->networkCount;++i) {
  470. if (nws->networks[i].nwid == wantnw) {
  471. OneService::NetworkSettings localSettings;
  472. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  473. try {
  474. nlohmann::json j(nlohmann::json::parse(body));
  475. if (j.is_object()) {
  476. auto allowManaged = j["allowManaged"];
  477. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  478. auto allowGlobal = j["allowGlobal"];
  479. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  480. auto allowDefault = j["allowDefault"];
  481. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  482. }
  483. } catch ( ... ) {
  484. // discard invalid JSON
  485. }
  486. _svc->setNetworkSettings(nws->networks[i].nwid,localSettings);
  487. responseContentType = "application/json";
  488. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  489. responseBody.push_back('\n');
  490. scode = 200;
  491. break;
  492. }
  493. }
  494. _node->freeQueryResult((void *)nws);
  495. } else scode = 500;
  496. }
  497. } else {
  498. if (_controller)
  499. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  500. else scode = 404;
  501. }
  502. } else scode = 401; // isAuth == false
  503. } else if (httpMethod == HTTP_DELETE) {
  504. if (isAuth) {
  505. if (ps[0] == "config") {
  506. // TODO
  507. } else if (ps[0] == "network") {
  508. ZT_VirtualNetworkList *nws = _node->networks();
  509. if (nws) {
  510. if (ps.size() == 2) {
  511. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  512. for(unsigned long i=0;i<nws->networkCount;++i) {
  513. if (nws->networks[i].nwid == wantnw) {
  514. _node->leave(wantnw,(void **)0);
  515. responseBody = "true";
  516. responseContentType = "application/json";
  517. scode = 200;
  518. break;
  519. }
  520. }
  521. } // else 404
  522. _node->freeQueryResult((void *)nws);
  523. } else scode = 500;
  524. } else {
  525. if (_controller)
  526. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  527. else scode = 404;
  528. }
  529. } else {
  530. scode = 401; // isAuth = false
  531. }
  532. } else {
  533. scode = 400;
  534. responseBody = "Method not supported.";
  535. }
  536. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  537. // Also double-check isAuth since forbidding this without auth feels safer.
  538. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  539. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  540. if (responseBody.length() > 0)
  541. responseBody = jsonp->second + "(" + responseBody + ");";
  542. else responseBody = jsonp->second + "(null);";
  543. responseContentType = "application/javascript";
  544. }
  545. return scode;
  546. }
  547. } // namespace ZeroTier