ControlPlane.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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_UPSTREAM: prole = "UPSTREAM"; break;
  210. case ZT_PEER_ROLE_ROOT: prole = "ROOT"; 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\"relayPolicy\": \"%s\",\n"
  368. "\t\"tcpFallbackActive\": %s,\n"
  369. "\t\"versionMajor\": %d,\n"
  370. "\t\"versionMinor\": %d,\n"
  371. "\t\"versionRev\": %d,\n"
  372. "\t\"version\": \"%d.%d.%d\",\n"
  373. "\t\"clock\": %llu,\n"
  374. "\t\"cluster\": %s\n"
  375. "}\n",
  376. status.address,
  377. status.publicIdentity,
  378. status.worldId,
  379. status.worldTimestamp,
  380. (status.online) ? "true" : "false",
  381. ((status.relayPolicy == ZT_RELAY_POLICY_ALWAYS) ? "always" : ((status.relayPolicy == ZT_RELAY_POLICY_NEVER) ? "never" : "trusted")),
  382. (_svc->tcpFallbackActive()) ? "true" : "false",
  383. ZEROTIER_ONE_VERSION_MAJOR,
  384. ZEROTIER_ONE_VERSION_MINOR,
  385. ZEROTIER_ONE_VERSION_REVISION,
  386. ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION,
  387. (unsigned long long)OSUtils::now(),
  388. ((clusterJson.length() > 0) ? clusterJson.c_str() : "null"));
  389. responseBody = json;
  390. scode = 200;
  391. } else if (ps[0] == "settings") {
  392. responseContentType = "application/json";
  393. responseBody = "{}"; // TODO
  394. scode = 200;
  395. } else if (ps[0] == "network") {
  396. ZT_VirtualNetworkList *nws = _node->networks();
  397. if (nws) {
  398. if (ps.size() == 1) {
  399. // Return [array] of all networks
  400. responseContentType = "application/json";
  401. responseBody = "[\n";
  402. for(unsigned long i=0;i<nws->networkCount;++i) {
  403. if (i > 0)
  404. responseBody.append(",");
  405. OneService::NetworkSettings localSettings;
  406. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  407. _jsonAppend(1,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  408. }
  409. responseBody.append("\n]\n");
  410. scode = 200;
  411. } else if (ps.size() == 2) {
  412. // Return a single network by ID or 404 if not found
  413. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  414. for(unsigned long i=0;i<nws->networkCount;++i) {
  415. if (nws->networks[i].nwid == wantnw) {
  416. responseContentType = "application/json";
  417. OneService::NetworkSettings localSettings;
  418. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  419. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  420. responseBody.push_back('\n');
  421. scode = 200;
  422. break;
  423. }
  424. }
  425. } // else 404
  426. _node->freeQueryResult((void *)nws);
  427. } else scode = 500;
  428. } else if (ps[0] == "peer") {
  429. ZT_PeerList *pl = _node->peers();
  430. if (pl) {
  431. if (ps.size() == 1) {
  432. // Return [array] of all peers
  433. responseContentType = "application/json";
  434. responseBody = "[\n";
  435. for(unsigned long i=0;i<pl->peerCount;++i) {
  436. if (i > 0)
  437. responseBody.append(",\n");
  438. _jsonAppend(1,responseBody,&(pl->peers[i]));
  439. }
  440. responseBody.append("\n]\n");
  441. scode = 200;
  442. } else if (ps.size() == 2) {
  443. // Return a single peer by ID or 404 if not found
  444. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  445. for(unsigned long i=0;i<pl->peerCount;++i) {
  446. if (pl->peers[i].address == wantp) {
  447. responseContentType = "application/json";
  448. _jsonAppend(0,responseBody,&(pl->peers[i]));
  449. responseBody.push_back('\n');
  450. scode = 200;
  451. break;
  452. }
  453. }
  454. } // else 404
  455. _node->freeQueryResult((void *)pl);
  456. } else scode = 500;
  457. } else if (ps[0] == "newIdentity") {
  458. // Return a newly generated ZeroTier identity -- this is primarily for debugging
  459. // and testing to make it easy for automated test scripts to generate test IDs.
  460. Identity newid;
  461. newid.generate();
  462. responseBody = newid.toString(true);
  463. responseContentType = "text/plain";
  464. scode = 200;
  465. } else {
  466. if (_controller)
  467. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  468. else scode = 404;
  469. }
  470. } else scode = 401; // isAuth == false
  471. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  472. if (isAuth) {
  473. if (ps[0] == "settings") {
  474. // TODO
  475. } else if (ps[0] == "network") {
  476. if (ps.size() == 2) {
  477. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  478. _node->join(wantnw,(void *)0); // does nothing if we are a member
  479. ZT_VirtualNetworkList *nws = _node->networks();
  480. if (nws) {
  481. for(unsigned long i=0;i<nws->networkCount;++i) {
  482. if (nws->networks[i].nwid == wantnw) {
  483. OneService::NetworkSettings localSettings;
  484. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  485. try {
  486. nlohmann::json j(OSUtils::jsonParse(body));
  487. if (j.is_object()) {
  488. nlohmann::json &allowManaged = j["allowManaged"];
  489. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  490. nlohmann::json &allowGlobal = j["allowGlobal"];
  491. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  492. nlohmann::json &allowDefault = j["allowDefault"];
  493. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  494. }
  495. } catch ( ... ) {
  496. // discard invalid JSON
  497. }
  498. _svc->setNetworkSettings(nws->networks[i].nwid,localSettings);
  499. responseContentType = "application/json";
  500. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  501. responseBody.push_back('\n');
  502. scode = 200;
  503. break;
  504. }
  505. }
  506. _node->freeQueryResult((void *)nws);
  507. } else scode = 500;
  508. }
  509. } else {
  510. if (_controller)
  511. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  512. else scode = 404;
  513. }
  514. } else scode = 401; // isAuth == false
  515. } else if (httpMethod == HTTP_DELETE) {
  516. if (isAuth) {
  517. if (ps[0] == "network") {
  518. ZT_VirtualNetworkList *nws = _node->networks();
  519. if (nws) {
  520. if (ps.size() == 2) {
  521. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  522. for(unsigned long i=0;i<nws->networkCount;++i) {
  523. if (nws->networks[i].nwid == wantnw) {
  524. _node->leave(wantnw,(void **)0);
  525. responseBody = "true";
  526. responseContentType = "application/json";
  527. scode = 200;
  528. break;
  529. }
  530. }
  531. } // else 404
  532. _node->freeQueryResult((void *)nws);
  533. } else scode = 500;
  534. } else {
  535. if (_controller)
  536. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  537. else scode = 404;
  538. }
  539. } else {
  540. scode = 401; // isAuth = false
  541. }
  542. } else {
  543. scode = 400;
  544. responseBody = "Method not supported.";
  545. }
  546. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  547. // Also double-check isAuth since forbidding this without auth feels safer.
  548. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  549. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  550. if (responseBody.length() > 0)
  551. responseBody = jsonp->second + "(" + responseBody + ");";
  552. else responseBody = jsonp->second + "(null);";
  553. responseContentType = "application/javascript";
  554. }
  555. return scode;
  556. }
  557. } // namespace ZeroTier