2
0

ControlPlane.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 "../node/World.hpp"
  33. #include "../osdep/OSUtils.hpp"
  34. namespace ZeroTier {
  35. namespace {
  36. static void _networkToJson(nlohmann::json &nj,const ZT_VirtualNetworkConfig *nc,const std::string &portDeviceName,const OneService::NetworkSettings &localSettings)
  37. {
  38. char tmp[256];
  39. const char *nstatus = "",*ntype = "";
  40. switch(nc->status) {
  41. case ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  42. case ZT_NETWORK_STATUS_OK: nstatus = "OK"; break;
  43. case ZT_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  44. case ZT_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  45. case ZT_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  46. case ZT_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  47. }
  48. switch(nc->type) {
  49. case ZT_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  50. case ZT_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  51. }
  52. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",nc->nwid);
  53. nj["id"] = tmp;
  54. nj["nwid"] = tmp;
  55. Utils::snprintf(tmp,sizeof(tmp),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(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));
  56. nj["mac"] = tmp;
  57. nj["name"] = nc->name;
  58. nj["status"] = nstatus;
  59. nj["type"] = ntype;
  60. nj["mtu"] = nc->mtu;
  61. nj["dhcp"] = (bool)(nc->dhcp != 0);
  62. nj["bridge"] = (bool)(nc->bridge != 0);
  63. nj["broadcastEnabled"] = (bool)(nc->broadcastEnabled != 0);
  64. nj["portError"] = nc->portError;
  65. nj["netconfRevision"] = nc->netconfRevision;
  66. nj["portDeviceName"] = portDeviceName;
  67. nj["allowManaged"] = localSettings.allowManaged;
  68. nj["allowGlobal"] = localSettings.allowGlobal;
  69. nj["allowDefault"] = localSettings.allowDefault;
  70. nlohmann::json aa = nlohmann::json::array();
  71. for(unsigned int i=0;i<nc->assignedAddressCount;++i) {
  72. aa.push_back(reinterpret_cast<const InetAddress *>(&(nc->assignedAddresses[i]))->toString());
  73. }
  74. nj["assignedAddresses"] = aa;
  75. nlohmann::json ra = nlohmann::json::array();
  76. for(unsigned int i=0;i<nc->routeCount;++i) {
  77. nlohmann::json rj;
  78. rj["target"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].target))->toString();
  79. if (nc->routes[i].via.ss_family == nc->routes[i].target.ss_family)
  80. rj["via"] = reinterpret_cast<const InetAddress *>(&(nc->routes[i].via))->toIpString();
  81. else rj["via"] = nlohmann::json();
  82. rj["flags"] = (int)nc->routes[i].flags;
  83. rj["metric"] = (int)nc->routes[i].metric;
  84. ra.push_back(rj);
  85. }
  86. nj["routes"] = ra;
  87. }
  88. static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer)
  89. {
  90. char tmp[256];
  91. const char *prole = "";
  92. switch(peer->role) {
  93. case ZT_PEER_ROLE_LEAF: prole = "LEAF"; break;
  94. case ZT_PEER_ROLE_MOON: prole = "MOON"; break;
  95. case ZT_PEER_ROLE_PLANET: prole = "PLANET"; break;
  96. }
  97. Utils::snprintf(tmp,sizeof(tmp),"%.10llx",peer->address);
  98. pj["address"] = tmp;
  99. pj["versionMajor"] = peer->versionMajor;
  100. pj["versionMinor"] = peer->versionMinor;
  101. pj["versionRev"] = peer->versionRev;
  102. Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d",peer->versionMajor,peer->versionMinor,peer->versionRev);
  103. pj["version"] = tmp;
  104. pj["latency"] = peer->latency;
  105. pj["role"] = prole;
  106. nlohmann::json pa = nlohmann::json::array();
  107. for(unsigned int i=0;i<peer->pathCount;++i) {
  108. nlohmann::json j;
  109. j["address"] = reinterpret_cast<const InetAddress *>(&(peer->paths[i].address))->toString();
  110. j["lastSend"] = peer->paths[i].lastSend;
  111. j["lastReceive"] = peer->paths[i].lastReceive;
  112. j["trustedPathId"] = peer->paths[i].trustedPathId;
  113. j["linkQuality"] = (double)peer->paths[i].linkQuality / (double)ZT_PATH_LINK_QUALITY_MAX;
  114. j["active"] = (bool)(peer->paths[i].expired == 0);
  115. j["expired"] = (bool)(peer->paths[i].expired != 0);
  116. j["preferred"] = (bool)(peer->paths[i].preferred != 0);
  117. pa.push_back(j);
  118. }
  119. pj["paths"] = pa;
  120. }
  121. static void _moonToJson(nlohmann::json &mj,const World &world)
  122. {
  123. char tmp[64];
  124. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",world.id());
  125. mj["id"] = tmp;
  126. mj["timestamp"] = world.timestamp();
  127. mj["signature"] = Utils::hex(world.signature().data,(unsigned int)world.signature().size());
  128. mj["updatesMustBeSignedBy"] = Utils::hex(world.updatesMustBeSignedBy().data,(unsigned int)world.updatesMustBeSignedBy().size());
  129. nlohmann::json ra = nlohmann::json::array();
  130. for(std::vector<World::Root>::const_iterator r(world.roots().begin());r!=world.roots().end();++r) {
  131. nlohmann::json rj;
  132. rj["identity"] = r->identity.toString(false);
  133. nlohmann::json eps = nlohmann::json::array();
  134. for(std::vector<InetAddress>::const_iterator a(r->stableEndpoints.begin());a!=r->stableEndpoints.end();++a)
  135. eps.push_back(a->toString());
  136. rj["stableEndpoints"] = eps;
  137. ra.push_back(rj);
  138. }
  139. mj["roots"] = ra;
  140. mj["waiting"] = false;
  141. }
  142. } // anonymous namespace
  143. ControlPlane::ControlPlane(OneService *svc,Node *n) :
  144. _svc(svc),
  145. _node(n),
  146. _controller((EmbeddedNetworkController *)0)
  147. {
  148. }
  149. unsigned int ControlPlane::handleRequest(
  150. const InetAddress &fromAddress,
  151. unsigned int httpMethod,
  152. const std::string &path,
  153. const std::map<std::string,std::string> &headers,
  154. const std::string &body,
  155. std::string &responseBody,
  156. std::string &responseContentType)
  157. {
  158. char tmp[256];
  159. unsigned int scode = 404;
  160. nlohmann::json res;
  161. std::vector<std::string> ps(OSUtils::split(path.c_str(),"/","",""));
  162. std::map<std::string,std::string> urlArgs;
  163. Mutex::Lock _l(_lock);
  164. /* Note: this is kind of restricted in what it'll take. It does not support
  165. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  166. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  167. * paths to simply-named resources. */
  168. if (ps.size() > 0) {
  169. std::size_t qpos = ps[ps.size() - 1].find('?');
  170. if (qpos != std::string::npos) {
  171. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  172. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  173. std::vector<std::string> asplit(OSUtils::split(args.c_str(),"&","",""));
  174. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  175. std::size_t eqpos = a->find('=');
  176. if (eqpos == std::string::npos)
  177. urlArgs[*a] = "";
  178. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  179. }
  180. }
  181. }
  182. bool isAuth = false;
  183. {
  184. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  185. if ((ah != headers.end())&&(_authTokens.count(ah->second) > 0)) {
  186. isAuth = true;
  187. } else {
  188. ah = urlArgs.find("auth");
  189. if ((ah != urlArgs.end())&&(_authTokens.count(ah->second) > 0))
  190. isAuth = true;
  191. }
  192. }
  193. if (httpMethod == HTTP_GET) {
  194. if (isAuth) {
  195. if (ps[0] == "status") {
  196. ZT_NodeStatus status;
  197. _node->status(&status);
  198. Utils::snprintf(tmp,sizeof(tmp),"%.10llx",status.address);
  199. res["address"] = tmp;
  200. res["publicIdentity"] = status.publicIdentity;
  201. res["online"] = (bool)(status.online != 0);
  202. res["tcpFallbackActive"] = _svc->tcpFallbackActive();
  203. res["versionMajor"] = ZEROTIER_ONE_VERSION_MAJOR;
  204. res["versionMinor"] = ZEROTIER_ONE_VERSION_MINOR;
  205. res["versionRev"] = ZEROTIER_ONE_VERSION_REVISION;
  206. res["versionBuild"] = ZEROTIER_ONE_VERSION_BUILD;
  207. Utils::snprintf(tmp,sizeof(tmp),"%d.%d.%d",ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  208. res["version"] = tmp;
  209. res["clock"] = OSUtils::now();
  210. World planet(_node->planet());
  211. res["planetWorldId"] = planet.id();
  212. res["planetWorldTimestamp"] = planet.timestamp();
  213. #ifdef ZT_ENABLE_CLUSTER
  214. nlohmann::json cj;
  215. ZT_ClusterStatus cs;
  216. _node->clusterStatus(&cs);
  217. if (cs.clusterSize >= 1) {
  218. nlohmann::json cja = nlohmann::json::array();
  219. for(unsigned int i=0;i<cs.clusterSize;++i) {
  220. nlohmann::json cjm;
  221. cjm["id"] = (int)cs.members[i].id;
  222. cjm["msSinceLastHeartbeat"] = cs.members[i].msSinceLastHeartbeat;
  223. cjm["alive"] = (bool)(cs.members[i].alive != 0);
  224. cjm["x"] = cs.members[i].x;
  225. cjm["y"] = cs.members[i].y;
  226. cjm["z"] = cs.members[i].z;
  227. cjm["load"] = cs.members[i].load;
  228. cjm["peers"] = cs.members[i].peers;
  229. cja.push_back(cjm);
  230. }
  231. cj["members"] = cja;
  232. cj["myId"] = (int)cs.myId;
  233. cj["clusterSize"] = cs.clusterSize;
  234. }
  235. res["cluster"] = cj;
  236. #else
  237. res["cluster"] = nlohmann::json();
  238. #endif
  239. scode = 200;
  240. } else if (ps[0] == "moon") {
  241. std::vector<World> moons(_node->moons());
  242. if (ps.size() == 1) {
  243. // Return [array] of all moons
  244. res = nlohmann::json::array();
  245. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  246. nlohmann::json mj;
  247. _moonToJson(mj,*m);
  248. res.push_back(mj);
  249. }
  250. scode = 200;
  251. } else {
  252. // Return a single moon by ID
  253. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  254. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  255. if (m->id() == id) {
  256. _moonToJson(res,*m);
  257. scode = 200;
  258. break;
  259. }
  260. }
  261. }
  262. } else if (ps[0] == "network") {
  263. ZT_VirtualNetworkList *nws = _node->networks();
  264. if (nws) {
  265. if (ps.size() == 1) {
  266. // Return [array] of all networks
  267. res = nlohmann::json::array();
  268. for(unsigned long i=0;i<nws->networkCount;++i) {
  269. OneService::NetworkSettings localSettings;
  270. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  271. nlohmann::json nj;
  272. _networkToJson(nj,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  273. res.push_back(nj);
  274. }
  275. scode = 200;
  276. } else if (ps.size() == 2) {
  277. // Return a single network by ID or 404 if not found
  278. const uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  279. for(unsigned long i=0;i<nws->networkCount;++i) {
  280. if (nws->networks[i].nwid == wantnw) {
  281. OneService::NetworkSettings localSettings;
  282. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  283. _networkToJson(res,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  284. scode = 200;
  285. break;
  286. }
  287. }
  288. } else scode = 404;
  289. _node->freeQueryResult((void *)nws);
  290. } else scode = 500;
  291. } else if (ps[0] == "peer") {
  292. ZT_PeerList *pl = _node->peers();
  293. if (pl) {
  294. if (ps.size() == 1) {
  295. // Return [array] of all peers
  296. res = nlohmann::json::array();
  297. for(unsigned long i=0;i<pl->peerCount;++i) {
  298. nlohmann::json pj;
  299. _peerToJson(pj,&(pl->peers[i]));
  300. res.push_back(pj);
  301. }
  302. scode = 200;
  303. } else if (ps.size() == 2) {
  304. // Return a single peer by ID or 404 if not found
  305. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  306. for(unsigned long i=0;i<pl->peerCount;++i) {
  307. if (pl->peers[i].address == wantp) {
  308. _peerToJson(res,&(pl->peers[i]));
  309. scode = 200;
  310. break;
  311. }
  312. }
  313. } else scode = 404;
  314. _node->freeQueryResult((void *)pl);
  315. } else scode = 500;
  316. } else {
  317. if (_controller) {
  318. scode = _controller->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  319. } else scode = 404;
  320. }
  321. } else scode = 401; // isAuth == false
  322. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  323. if (isAuth) {
  324. if (ps[0] == "moon") {
  325. if (ps.size() == 2) {
  326. uint64_t seed = 0;
  327. try {
  328. nlohmann::json j(OSUtils::jsonParse(body));
  329. if (j.is_object()) {
  330. seed = Utils::hexStrToU64(OSUtils::jsonString(j["seed"],"0").c_str());
  331. }
  332. } catch ( ... ) {
  333. // discard invalid JSON
  334. }
  335. std::vector<World> moons(_node->moons());
  336. const uint64_t id = Utils::hexStrToU64(ps[1].c_str());
  337. for(std::vector<World>::const_iterator m(moons.begin());m!=moons.end();++m) {
  338. if (m->id() == id) {
  339. _moonToJson(res,*m);
  340. scode = 200;
  341. break;
  342. }
  343. }
  344. if ((scode != 200)&&(seed != 0)) {
  345. char tmp[64];
  346. Utils::snprintf(tmp,sizeof(tmp),"%.16llx",id);
  347. res["id"] = tmp;
  348. res["roots"] = nlohmann::json::array();
  349. res["timestamp"] = 0;
  350. res["signature"] = nlohmann::json();
  351. res["updatesMustBeSignedBy"] = nlohmann::json();
  352. res["waiting"] = true;
  353. _node->orbit(id,seed);
  354. }
  355. } else scode = 404;
  356. } else if (ps[0] == "network") {
  357. if (ps.size() == 2) {
  358. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  359. _node->join(wantnw,(void *)0); // does nothing if we are a member
  360. ZT_VirtualNetworkList *nws = _node->networks();
  361. if (nws) {
  362. for(unsigned long i=0;i<nws->networkCount;++i) {
  363. if (nws->networks[i].nwid == wantnw) {
  364. OneService::NetworkSettings localSettings;
  365. _svc->getNetworkSettings(nws->networks[i].nwid,localSettings);
  366. try {
  367. nlohmann::json j(OSUtils::jsonParse(body));
  368. if (j.is_object()) {
  369. nlohmann::json &allowManaged = j["allowManaged"];
  370. if (allowManaged.is_boolean()) localSettings.allowManaged = (bool)allowManaged;
  371. nlohmann::json &allowGlobal = j["allowGlobal"];
  372. if (allowGlobal.is_boolean()) localSettings.allowGlobal = (bool)allowGlobal;
  373. nlohmann::json &allowDefault = j["allowDefault"];
  374. if (allowDefault.is_boolean()) localSettings.allowDefault = (bool)allowDefault;
  375. }
  376. } catch ( ... ) {
  377. // discard invalid JSON
  378. }
  379. _svc->setNetworkSettings(nws->networks[i].nwid,localSettings);
  380. _networkToJson(res,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid),localSettings);
  381. scode = 200;
  382. break;
  383. }
  384. }
  385. _node->freeQueryResult((void *)nws);
  386. } else scode = 500;
  387. } else scode = 404;
  388. } else {
  389. if (_controller)
  390. scode = _controller->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  391. else scode = 404;
  392. }
  393. } else scode = 401; // isAuth == false
  394. } else if (httpMethod == HTTP_DELETE) {
  395. if (isAuth) {
  396. if (ps[0] == "moon") {
  397. if (ps.size() == 2) {
  398. _node->deorbit(Utils::hexStrToU64(ps[1].c_str()));
  399. res["result"] = true;
  400. scode = 200;
  401. } // else 404
  402. } else if (ps[0] == "network") {
  403. ZT_VirtualNetworkList *nws = _node->networks();
  404. if (nws) {
  405. if (ps.size() == 2) {
  406. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  407. for(unsigned long i=0;i<nws->networkCount;++i) {
  408. if (nws->networks[i].nwid == wantnw) {
  409. _node->leave(wantnw,(void **)0);
  410. res["result"] = true;
  411. scode = 200;
  412. break;
  413. }
  414. }
  415. } // else 404
  416. _node->freeQueryResult((void *)nws);
  417. } else scode = 500;
  418. } else {
  419. if (_controller)
  420. scode = _controller->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  421. else scode = 404;
  422. }
  423. } else scode = 401; // isAuth = false
  424. } else {
  425. scode = 400;
  426. }
  427. if (responseBody.length() == 0) {
  428. if ((res.is_object())||(res.is_array()))
  429. responseBody = OSUtils::jsonDump(res);
  430. else responseBody = "{}";
  431. responseContentType = "application/json";
  432. }
  433. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  434. // Also double-check isAuth since forbidding this without auth feels safer.
  435. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  436. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  437. if (responseBody.length() > 0)
  438. responseBody = jsonp->second + "(" + responseBody + ");";
  439. else responseBody = jsonp->second + "(null);";
  440. responseContentType = "application/javascript";
  441. }
  442. return scode;
  443. }
  444. } // namespace ZeroTier