2
0

ControlPlane.cpp 20 KB

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