ControlPlane.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. #ifdef ZT_USE_SYSTEM_JSON_PARSER
  28. #include <json-parser/json.h>
  29. #else
  30. #include "../ext/json-parser/json.h"
  31. #endif
  32. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  33. #include "../controller/SqliteNetworkController.hpp"
  34. #endif
  35. #include "../node/InetAddress.hpp"
  36. #include "../node/Node.hpp"
  37. #include "../node/Utils.hpp"
  38. #include "../osdep/OSUtils.hpp"
  39. namespace ZeroTier {
  40. static std::string _jsonEscape(const char *s)
  41. {
  42. std::string buf;
  43. for(const char *p=s;(*p);++p) {
  44. switch(*p) {
  45. case '\t': buf.append("\\t"); break;
  46. case '\b': buf.append("\\b"); break;
  47. case '\r': buf.append("\\r"); break;
  48. case '\n': buf.append("\\n"); break;
  49. case '\f': buf.append("\\f"); break;
  50. case '"': buf.append("\\\""); break;
  51. case '\\': buf.append("\\\\"); break;
  52. case '/': buf.append("\\/"); break;
  53. default: buf.push_back(*p); break;
  54. }
  55. }
  56. return buf;
  57. }
  58. static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); }
  59. static std::string _jsonEnumerate(const struct sockaddr_storage *ss,unsigned int count)
  60. {
  61. std::string buf;
  62. buf.push_back('[');
  63. for(unsigned int i=0;i<count;++i) {
  64. if (i > 0)
  65. buf.push_back(',');
  66. buf.push_back('"');
  67. buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(ss[i]))->toString()));
  68. buf.push_back('"');
  69. }
  70. buf.push_back(']');
  71. return buf;
  72. }
  73. static std::string _jsonEnumerate(const ZT_VirtualNetworkRoute *routes,unsigned int count)
  74. {
  75. std::string buf;
  76. buf.push_back('[');
  77. for(unsigned int i=0;i<count;++i) {
  78. if (i > 0)
  79. buf.push_back(',');
  80. buf.append("{\"target\":\"");
  81. buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(routes[i].target))->toString()));
  82. buf.append("\",\"via\":");
  83. if (routes[i].via.ss_family == routes[i].target.ss_family) {
  84. buf.push_back('"');
  85. buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(routes[i].via))->toIpString()));
  86. buf.append("\",");
  87. } else buf.append("null,");
  88. char tmp[1024];
  89. Utils::snprintf(tmp,sizeof(tmp),"\"flags\":%u,\"metric\":%u}",(unsigned int)routes[i].flags,(unsigned int)routes[i].metric);
  90. buf.append(tmp);
  91. }
  92. buf.push_back(']');
  93. return buf;
  94. }
  95. static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
  96. {
  97. char json[4096];
  98. char prefix[32];
  99. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  100. return;
  101. for(unsigned int i=0;i<depth;++i)
  102. prefix[i] = '\t';
  103. prefix[depth] = '\0';
  104. const char *nstatus = "",*ntype = "";
  105. switch(nc->status) {
  106. case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  107. case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
  108. case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  109. case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  110. case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  111. case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  112. }
  113. switch(nc->type) {
  114. case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  115. case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  116. }
  117. Utils::snprintf(json,sizeof(json),
  118. "%s{\n"
  119. "%s\t\"nwid\": \"%.16llx\",\n"
  120. "%s\t\"mac\": \"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",\n"
  121. "%s\t\"name\": \"%s\",\n"
  122. "%s\t\"status\": \"%s\",\n"
  123. "%s\t\"type\": \"%s\",\n"
  124. "%s\t\"mtu\": %u,\n"
  125. "%s\t\"dhcp\": %s,\n"
  126. "%s\t\"bridge\": %s,\n"
  127. "%s\t\"broadcastEnabled\": %s,\n"
  128. "%s\t\"portError\": %d,\n"
  129. "%s\t\"netconfRevision\": %lu,\n"
  130. "%s\t\"assignedAddresses\": %s,\n"
  131. "%s\t\"routes\": %s,\n"
  132. "%s\t\"portDeviceName\": \"%s\",\n"
  133. "%s\t\"allowManaged\": %s,\n"
  134. "%s\t\"allowGlobal\": %s,\n"
  135. "%s\t\"allowDefault\": %s\n"
  136. "%s}",
  137. prefix,
  138. prefix,nc->nwid,
  139. 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),
  140. prefix,_jsonEscape(nc->name).c_str(),
  141. prefix,nstatus,
  142. prefix,ntype,
  143. prefix,nc->mtu,
  144. prefix,(nc->dhcp == 0) ? "false" : "true",
  145. prefix,(nc->bridge == 0) ? "false" : "true",
  146. prefix,(nc->broadcastEnabled == 0) ? "false" : "true",
  147. prefix,nc->portError,
  148. prefix,nc->netconfRevision,
  149. prefix,_jsonEnumerate(nc->assignedAddresses,nc->assignedAddressCount).c_str(),
  150. prefix,_jsonEnumerate(nc->routes,nc->routeCount).c_str(),
  151. prefix,_jsonEscape(portDeviceName).c_str(),
  152. prefix,(localSettings.allowManaged) ? "true" : "false",
  153. prefix,(localSettings.allowGlobal) ? "true" : "false",
  154. prefix,(localSettings.allowDefault) ? "true" : "false",
  155. prefix);
  156. buf.append(json);
  157. }
  158. static std::string _jsonEnumerate(unsigned int depth,const ZT_PeerPhysicalPath *pp,unsigned int count)
  159. {
  160. char json[1024];
  161. char prefix[32];
  162. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  163. return std::string();
  164. for(unsigned int i=0;i<depth;++i)
  165. prefix[i] = '\t';
  166. prefix[depth] = '\0';
  167. std::string buf;
  168. for(unsigned int i=0;i<count;++i) {
  169. if (i > 0)
  170. buf.push_back(',');
  171. Utils::snprintf(json,sizeof(json),
  172. "{\n"
  173. "%s\t\"address\": \"%s\",\n"
  174. "%s\t\"lastSend\": %llu,\n"
  175. "%s\t\"lastReceive\": %llu,\n"
  176. "%s\t\"active\": %s,\n"
  177. "%s\t\"preferred\": %s,\n"
  178. "%s\t\"trustedPathId\": %llu\n"
  179. "%s}",
  180. prefix,_jsonEscape(reinterpret_cast<const InetAddress *>(&(pp[i].address))->toString()).c_str(),
  181. prefix,pp[i].lastSend,
  182. prefix,pp[i].lastReceive,
  183. prefix,(pp[i].active == 0) ? "false" : "true",
  184. prefix,(pp[i].preferred == 0) ? "false" : "true",
  185. prefix,pp[i].trustedPathId,
  186. prefix);
  187. buf.append(json);
  188. }
  189. return buf;
  190. }
  191. static void _jsonAppend(unsigned int depth,std::string &buf,const ZT_Peer *peer)
  192. {
  193. char json[1024];
  194. char prefix[32];
  195. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  196. return;
  197. for(unsigned int i=0;i<depth;++i)
  198. prefix[i] = '\t';
  199. prefix[depth] = '\0';
  200. const char *prole = "";
  201. switch(peer->role) {
  202. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  203. case ZT_PEER_ROLE_RELAY: prole = "RELAY"; break;
  204. case ZT_PEER_ROLE_ROOT: prole = "ROOT"; break;
  205. }
  206. Utils::snprintf(json,sizeof(json),
  207. "%s{\n"
  208. "%s\t\"address\": \"%.10llx\",\n"
  209. "%s\t\"lastUnicastFrame\": %llu,\n"
  210. "%s\t\"lastMulticastFrame\": %llu,\n"
  211. "%s\t\"versionMajor\": %d,\n"
  212. "%s\t\"versionMinor\": %d,\n"
  213. "%s\t\"versionRev\": %d,\n"
  214. "%s\t\"version\": \"%d.%d.%d\",\n"
  215. "%s\t\"latency\": %u,\n"
  216. "%s\t\"role\": \"%s\",\n"
  217. "%s\t\"paths\": [%s]\n"
  218. "%s}",
  219. prefix,
  220. prefix,peer->address,
  221. prefix,peer->lastUnicastFrame,
  222. prefix,peer->lastMulticastFrame,
  223. prefix,peer->versionMajor,
  224. prefix,peer->versionMinor,
  225. prefix,peer->versionRev,
  226. prefix,peer->versionMajor,peer->versionMinor,peer->versionRev,
  227. prefix,peer->latency,
  228. prefix,prole,
  229. prefix,_jsonEnumerate(depth+1,peer->paths,peer->pathCount).c_str(),
  230. prefix);
  231. buf.append(json);
  232. }
  233. ControlPlane::ControlPlane(OneService *svc,Node *n,const char *uiStaticPath) :
  234. _svc(svc),
  235. _node(n),
  236. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  237. _controller((SqliteNetworkController *)0),
  238. #endif
  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(Utils::split(path.c_str(),"/","",""));
  257. std::map<std::string,std::string> urlArgs;
  258. Mutex::Lock _l(_lock);
  259. if (!((fromAddress.ipsEqual(InetAddress::LO4))||(fromAddress.ipsEqual(InetAddress::LO6))))
  260. return 403; // Forbidden: we only allow access from localhost right now
  261. /* Note: this is kind of restricted in what it'll take. It does not support
  262. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  263. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  264. * paths to simply-named resources. */
  265. if (ps.size() > 0) {
  266. std::size_t qpos = ps[ps.size() - 1].find('?');
  267. if (qpos != std::string::npos) {
  268. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  269. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  270. std::vector<std::string> asplit(Utils::split(args.c_str(),"&","",""));
  271. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  272. std::size_t eqpos = a->find('=');
  273. if (eqpos == std::string::npos)
  274. urlArgs[*a] = "";
  275. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  276. }
  277. }
  278. } else {
  279. ps.push_back(std::string("index.html"));
  280. }
  281. bool isAuth = false;
  282. {
  283. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  284. if ((ah != headers.end())&&(_authTokens.count(ah->second) > 0)) {
  285. isAuth = true;
  286. } else {
  287. ah = urlArgs.find("auth");
  288. if ((ah != urlArgs.end())&&(_authTokens.count(ah->second) > 0))
  289. isAuth = true;
  290. }
  291. }
  292. if (httpMethod == HTTP_GET) {
  293. std::string ext;
  294. std::size_t dotIdx = ps[0].find_last_of('.');
  295. if (dotIdx != std::string::npos)
  296. ext = ps[0].substr(dotIdx);
  297. if ((ps.size() == 1)&&(ext.length() >= 2)&&(ext[0] == '.')) {
  298. /* Static web pages can be served without authentication to enable a simple web
  299. * UI. This is still only allowed from approved IP addresses. Anything with a
  300. * dot in the first path element (e.g. foo.html) is considered a static page,
  301. * as nothing in the API is so named. */
  302. if (_uiStaticPath.length() > 0) {
  303. if (ext == ".html")
  304. responseContentType = "text/html";
  305. else if (ext == ".js")
  306. responseContentType = "application/javascript";
  307. else if (ext == ".jsx")
  308. responseContentType = "text/jsx";
  309. else if (ext == ".json")
  310. responseContentType = "application/json";
  311. else if (ext == ".css")
  312. responseContentType = "text/css";
  313. else if (ext == ".png")
  314. responseContentType = "image/png";
  315. else if (ext == ".jpg")
  316. responseContentType = "image/jpeg";
  317. else if (ext == ".gif")
  318. responseContentType = "image/gif";
  319. else if (ext == ".txt")
  320. responseContentType = "text/plain";
  321. else if (ext == ".xml")
  322. responseContentType = "text/xml";
  323. else if (ext == ".svg")
  324. responseContentType = "image/svg+xml";
  325. else responseContentType = "application/octet-stream";
  326. scode = OSUtils::readFile((_uiStaticPath + ZT_PATH_SEPARATOR_S + ps[0]).c_str(),responseBody) ? 200 : 404;
  327. } else {
  328. scode = 404;
  329. }
  330. } else if (isAuth) {
  331. /* Things that require authentication -- a.k.a. everything but static web app pages. */
  332. if (ps[0] == "status") {
  333. responseContentType = "application/json";
  334. ZT_NodeStatus status;
  335. _node->status(&status);
  336. std::string clusterJson;
  337. #ifdef ZT_ENABLE_CLUSTER
  338. {
  339. ZT_ClusterStatus cs;
  340. _node->clusterStatus(&cs);
  341. if (cs.clusterSize >= 1) {
  342. char t[1024];
  343. Utils::snprintf(t,sizeof(t),"{\n\t\t\"myId\": %u,\n\t\t\"clusterSize\": %u,\n\t\t\"members\": [",cs.myId,cs.clusterSize);
  344. clusterJson.append(t);
  345. for(unsigned int i=0;i<cs.clusterSize;++i) {
  346. 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}",
  347. ((i == 0) ? "\n" : ",\n"),
  348. cs.members[i].id,
  349. cs.members[i].msSinceLastHeartbeat,
  350. (cs.members[i].alive != 0) ? "true" : "false",
  351. cs.members[i].x,
  352. cs.members[i].y,
  353. cs.members[i].z,
  354. cs.members[i].load,
  355. cs.members[i].peers);
  356. clusterJson.append(t);
  357. }
  358. clusterJson.append(" ]\n\t\t}");
  359. }
  360. }
  361. #endif
  362. Utils::snprintf(json,sizeof(json),
  363. "{\n"
  364. "\t\"address\": \"%.10llx\",\n"
  365. "\t\"publicIdentity\": \"%s\",\n"
  366. "\t\"worldId\": %llu,\n"
  367. "\t\"worldTimestamp\": %llu,\n"
  368. "\t\"online\": %s,\n"
  369. "\t\"tcpFallbackActive\": %s,\n"
  370. "\t\"versionMajor\": %d,\n"
  371. "\t\"versionMinor\": %d,\n"
  372. "\t\"versionRev\": %d,\n"
  373. "\t\"version\": \"%d.%d.%d\",\n"
  374. "\t\"clock\": %llu,\n"
  375. "\t\"cluster\": %s\n"
  376. "}\n",
  377. status.address,
  378. status.publicIdentity,
  379. status.worldId,
  380. status.worldTimestamp,
  381. (status.online) ? "true" : "false",
  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] == "config") {
  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. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  467. if (_controller)
  468. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  469. else scode = 404;
  470. #else
  471. scode = 404;
  472. #endif
  473. }
  474. } else scode = 401; // isAuth == false
  475. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  476. if (isAuth) {
  477. if (ps[0] == "config") {
  478. // TODO
  479. } else if (ps[0] == "network") {
  480. if (ps.size() == 2) {
  481. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  482. _node->join(wantnw,(void *)0); // does nothing if we are a member
  483. ZT_VirtualNetworkList *nws = _node->networks();
  484. if (nws) {
  485. for(unsigned long i=0;i<nws->networkCount;++i) {
  486. if (nws->networks[i].nwid == wantnw) {
  487. OneService::NetworkSettings localSettings;
  488. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  489. json_value *j = json_parse(body.c_str(),body.length());
  490. if (j) {
  491. if (j->type == json_object) {
  492. for(unsigned int k=0;k<j->u.object.length;++k) {
  493. if (!strcmp(j->u.object.values[k].name,"allowManaged")) {
  494. if (j->u.object.values[k].value->type == json_boolean)
  495. localSettings.allowManaged = (j->u.object.values[k].value->u.boolean != 0);
  496. } else if (!strcmp(j->u.object.values[k].name,"allowGlobal")) {
  497. if (j->u.object.values[k].value->type == json_boolean)
  498. localSettings.allowGlobal = (j->u.object.values[k].value->u.boolean != 0);
  499. } else if (!strcmp(j->u.object.values[k].name,"allowDefault")) {
  500. if (j->u.object.values[k].value->type == json_boolean)
  501. localSettings.allowDefault = (j->u.object.values[k].value->u.boolean != 0);
  502. }
  503. }
  504. }
  505. json_value_free(j);
  506. }
  507. _svc->setNetworkSettings(nws->networks[i].nwid,localSettings);
  508. responseContentType = "application/json";
  509. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  510. responseBody.push_back('\n');
  511. scode = 200;
  512. break;
  513. }
  514. }
  515. _node->freeQueryResult((void *)nws);
  516. } else scode = 500;
  517. }
  518. } else {
  519. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  520. if (_controller)
  521. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  522. else scode = 404;
  523. #else
  524. scode = 404;
  525. #endif
  526. }
  527. } else scode = 401; // isAuth == false
  528. } else if (httpMethod == HTTP_DELETE) {
  529. if (isAuth) {
  530. if (ps[0] == "config") {
  531. // TODO
  532. } else if (ps[0] == "network") {
  533. ZT_VirtualNetworkList *nws = _node->networks();
  534. if (nws) {
  535. if (ps.size() == 2) {
  536. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  537. for(unsigned long i=0;i<nws->networkCount;++i) {
  538. if (nws->networks[i].nwid == wantnw) {
  539. _node->leave(wantnw,(void **)0);
  540. responseBody = "true";
  541. responseContentType = "application/json";
  542. scode = 200;
  543. break;
  544. }
  545. }
  546. } // else 404
  547. _node->freeQueryResult((void *)nws);
  548. } else scode = 500;
  549. } else {
  550. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  551. if (_controller)
  552. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  553. else scode = 404;
  554. #else
  555. scode = 404;
  556. #endif
  557. }
  558. } else {
  559. scode = 401; // isAuth = false
  560. }
  561. } else {
  562. scode = 400;
  563. responseBody = "Method not supported.";
  564. }
  565. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  566. // Also double-check isAuth since forbidding this without auth feels safer.
  567. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  568. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  569. if (responseBody.length() > 0)
  570. responseBody = jsonp->second + "(" + responseBody + ");";
  571. else responseBody = jsonp->second + "(null);";
  572. responseContentType = "application/javascript";
  573. }
  574. return scode;
  575. }
  576. } // namespace ZeroTier