ControlPlane.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "ControlPlane.hpp"
  28. #include "ControlPlaneSubsystem.hpp"
  29. #include "OneService.hpp"
  30. #include "../version.h"
  31. #include "../include/ZeroTierOne.h"
  32. #include "../ext/http-parser/http_parser.h"
  33. #include "../node/InetAddress.hpp"
  34. #include "../node/Node.hpp"
  35. #include "../node/Utils.hpp"
  36. #include "../osdep/OSUtils.hpp"
  37. namespace ZeroTier {
  38. static std::string _jsonEscape(const char *s)
  39. {
  40. std::string buf;
  41. for(const char *p=s;(*p);++p) {
  42. switch(*p) {
  43. case '\t': buf.append("\\t"); break;
  44. case '\b': buf.append("\\b"); break;
  45. case '\r': buf.append("\\r"); break;
  46. case '\n': buf.append("\\n"); break;
  47. case '\f': buf.append("\\f"); break;
  48. case '"': buf.append("\\\""); break;
  49. case '\\': buf.append("\\\\"); break;
  50. case '/': buf.append("\\/"); break;
  51. default: buf.push_back(*p); break;
  52. }
  53. }
  54. return buf;
  55. }
  56. static std::string _jsonEscape(const std::string &s) { return _jsonEscape(s.c_str()); }
  57. static std::string _jsonEnumerate(const ZT1_MulticastGroup *mg,unsigned int count)
  58. {
  59. std::string buf;
  60. char tmp[128];
  61. buf.push_back('[');
  62. for(unsigned int i=0;i<count;++i) {
  63. if (i > 0)
  64. buf.push_back(',');
  65. Utils::snprintf(tmp,sizeof(tmp),"\"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\\/%.8lx\"",
  66. (unsigned int)((mg[i].mac >> 40) & 0xff),
  67. (unsigned int)((mg[i].mac >> 32) & 0xff),
  68. (unsigned int)((mg[i].mac >> 24) & 0xff),
  69. (unsigned int)((mg[i].mac >> 16) & 0xff),
  70. (unsigned int)((mg[i].mac >> 8) & 0xff),
  71. (unsigned int)(mg[i].mac & 0xff),
  72. (unsigned long)(mg[i].adi));
  73. buf.append(tmp);
  74. }
  75. buf.push_back(']');
  76. return buf;
  77. }
  78. static std::string _jsonEnumerate(const struct sockaddr_storage *ss,unsigned int count)
  79. {
  80. std::string buf;
  81. buf.push_back('[');
  82. for(unsigned int i=0;i<count;++i) {
  83. if (i > 0)
  84. buf.push_back(',');
  85. buf.push_back('"');
  86. buf.append(_jsonEscape(reinterpret_cast<const InetAddress *>(&(ss[i]))->toString()));
  87. buf.push_back('"');
  88. }
  89. buf.push_back(']');
  90. return buf;
  91. }
  92. static void _jsonAppend(unsigned int depth,std::string &buf,const ZT1_VirtualNetworkConfig *nc,const std::string &portDeviceName)
  93. {
  94. char json[4096];
  95. char prefix[32];
  96. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  97. return;
  98. for(unsigned int i=0;i<depth;++i)
  99. prefix[i] = '\t';
  100. prefix[depth] = '\0';
  101. const char *nstatus = "",*ntype = "";
  102. switch(nc->status) {
  103. case ZT1_NETWORK_STATUS_REQUESTING_CONFIGURATION: nstatus = "REQUESTING_CONFIGURATION"; break;
  104. case ZT1_NETWORK_STATUS_OK: nstatus = "OK"; break;
  105. case ZT1_NETWORK_STATUS_ACCESS_DENIED: nstatus = "ACCESS_DENIED"; break;
  106. case ZT1_NETWORK_STATUS_NOT_FOUND: nstatus = "NOT_FOUND"; break;
  107. case ZT1_NETWORK_STATUS_PORT_ERROR: nstatus = "PORT_ERROR"; break;
  108. case ZT1_NETWORK_STATUS_CLIENT_TOO_OLD: nstatus = "CLIENT_TOO_OLD"; break;
  109. }
  110. switch(nc->type) {
  111. case ZT1_NETWORK_TYPE_PRIVATE: ntype = "PRIVATE"; break;
  112. case ZT1_NETWORK_TYPE_PUBLIC: ntype = "PUBLIC"; break;
  113. }
  114. Utils::snprintf(json,sizeof(json),
  115. "%s{\n"
  116. "%s\t\"nwid\": \"%.16llx\",\n"
  117. "%s\t\"mac\": \"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\",\n"
  118. "%s\t\"name\": \"%s\",\n"
  119. "%s\t\"status\": \"%s\",\n"
  120. "%s\t\"type\": \"%s\",\n"
  121. "%s\t\"mtu\": %u,\n"
  122. "%s\t\"dhcp\": %s,\n"
  123. "%s\t\"bridge\": %s,\n"
  124. "%s\t\"broadcastEnabled\": %s,\n"
  125. "%s\t\"portError\": %d,\n"
  126. "%s\t\"netconfRevision\": %lu,\n"
  127. "%s\t\"multicastSubscriptions\": %s,\n"
  128. "%s\t\"assignedAddresses\": %s,\n"
  129. "%s\t\"portDeviceName\": \"%s\"\n"
  130. "%s}",
  131. prefix,
  132. prefix,nc->nwid,
  133. prefix,(unsigned int)((nc->mac >> 40) & 0xff),(unsigned int)((nc->mac >> 32) & 0xff),(unsigned int)((nc->mac >> 24) & 0xff),(unsigned int)((nc->mac >> 16) & 0xff),(unsigned int)((nc->mac >> 8) & 0xff),(unsigned int)(nc->mac & 0xff),
  134. prefix,_jsonEscape(nc->name).c_str(),
  135. prefix,nstatus,
  136. prefix,ntype,
  137. prefix,nc->mtu,
  138. prefix,(nc->dhcp == 0) ? "false" : "true",
  139. prefix,(nc->bridge == 0) ? "false" : "true",
  140. prefix,(nc->broadcastEnabled == 0) ? "false" : "true",
  141. prefix,nc->portError,
  142. prefix,nc->netconfRevision,
  143. prefix,_jsonEnumerate(nc->multicastSubscriptions,nc->multicastSubscriptionCount).c_str(),
  144. prefix,_jsonEnumerate(nc->assignedAddresses,nc->assignedAddressCount).c_str(),
  145. prefix,_jsonEscape(portDeviceName).c_str(),
  146. prefix);
  147. buf.append(json);
  148. }
  149. static std::string _jsonEnumerate(unsigned int depth,const ZT1_PeerPhysicalPath *pp,unsigned int count)
  150. {
  151. char json[1024];
  152. char prefix[32];
  153. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  154. return std::string();
  155. for(unsigned int i=0;i<depth;++i)
  156. prefix[i] = '\t';
  157. prefix[depth] = '\0';
  158. std::string buf;
  159. for(unsigned int i=0;i<count;++i) {
  160. if (i > 0)
  161. buf.push_back(',');
  162. Utils::snprintf(json,sizeof(json),
  163. "{\n"
  164. "%s\t\"address\": \"%s\",\n"
  165. "%s\t\"lastSend\": %llu,\n"
  166. "%s\t\"lastReceive\": %llu,\n"
  167. "%s\t\"fixed\": %s,\n"
  168. "%s\t\"active\": %s,\n"
  169. "%s\t\"preferred\": %s\n"
  170. "%s}",
  171. prefix,_jsonEscape(reinterpret_cast<const InetAddress *>(&(pp[i].address))->toString()).c_str(),
  172. prefix,pp[i].lastSend,
  173. prefix,pp[i].lastReceive,
  174. prefix,(pp[i].fixed == 0) ? "false" : "true",
  175. prefix,(pp[i].active == 0) ? "false" : "true",
  176. prefix,(pp[i].preferred == 0) ? "false" : "true",
  177. prefix);
  178. buf.append(json);
  179. }
  180. return buf;
  181. }
  182. static void _jsonAppend(unsigned int depth,std::string &buf,const ZT1_Peer *peer)
  183. {
  184. char json[1024];
  185. char prefix[32];
  186. if (depth >= sizeof(prefix)) // sanity check -- shouldn't be possible
  187. return;
  188. for(unsigned int i=0;i<depth;++i)
  189. prefix[i] = '\t';
  190. prefix[depth] = '\0';
  191. const char *prole = "";
  192. switch(peer->role) {
  193. case ZT1_PEER_ROLE_LEAF: prole = "LEAF"; break;
  194. case ZT1_PEER_ROLE_HUB: prole = "HUB"; break;
  195. case ZT1_PEER_ROLE_SUPERNODE: prole = "SUPERNODE"; break;
  196. }
  197. Utils::snprintf(json,sizeof(json),
  198. "%s{\n"
  199. "%s\t\"address\": \"%.10llx\",\n"
  200. "%s\t\"lastUnicastFrame\": %llu,\n"
  201. "%s\t\"lastMulticastFrame\": %llu,\n"
  202. "%s\t\"versionMajor\": %d,\n"
  203. "%s\t\"versionMinor\": %d,\n"
  204. "%s\t\"versionRev\": %d,\n"
  205. "%s\t\"version\": \"%d.%d.%d\",\n"
  206. "%s\t\"latency\": %u,\n"
  207. "%s\t\"role\": \"%s\",\n"
  208. "%s\t\"paths\": [%s]\n"
  209. "%s}",
  210. prefix,
  211. prefix,peer->address,
  212. prefix,peer->lastUnicastFrame,
  213. prefix,peer->lastMulticastFrame,
  214. prefix,peer->versionMajor,
  215. prefix,peer->versionMinor,
  216. prefix,peer->versionRev,
  217. prefix,peer->versionMajor,peer->versionMinor,peer->versionRev,
  218. prefix,peer->latency,
  219. prefix,prole,
  220. prefix,_jsonEnumerate(depth+1,peer->paths,peer->pathCount).c_str(),
  221. prefix);
  222. buf.append(json);
  223. }
  224. ControlPlane::ControlPlane(OneService *svc,Node *n,const char *uiStaticPath) :
  225. _svc(svc),
  226. _node(n),
  227. _uiStaticPath((uiStaticPath) ? uiStaticPath : "")
  228. {
  229. }
  230. ControlPlane::~ControlPlane()
  231. {
  232. }
  233. unsigned int ControlPlane::handleRequest(
  234. const InetAddress &fromAddress,
  235. unsigned int httpMethod,
  236. const std::string &path,
  237. const std::map<std::string,std::string> &headers,
  238. const std::string &body,
  239. std::string &responseBody,
  240. std::string &responseContentType)
  241. {
  242. char json[1024];
  243. unsigned int scode = 404;
  244. std::vector<std::string> ps(Utils::split(path.c_str(),"/","",""));
  245. std::map<std::string,std::string> urlArgs;
  246. Mutex::Lock _l(_lock);
  247. if (!((fromAddress.ipsEqual(InetAddress::LO4))||(fromAddress.ipsEqual(InetAddress::LO6))))
  248. return 403; // Forbidden: we only allow access from localhost right now
  249. /* Note: this is kind of restricted in what it'll take. It does not support
  250. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  251. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  252. * paths to simply-named resources. */
  253. if (ps.size() > 0) {
  254. std::size_t qpos = ps[ps.size() - 1].find('?');
  255. if (qpos != std::string::npos) {
  256. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  257. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  258. std::vector<std::string> asplit(Utils::split(args.c_str(),"&","",""));
  259. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  260. std::size_t eqpos = a->find('=');
  261. if (eqpos == std::string::npos)
  262. urlArgs[*a] = "";
  263. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  264. }
  265. }
  266. } else {
  267. ps.push_back(std::string("index.html"));
  268. }
  269. bool isAuth = false;
  270. {
  271. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  272. if ((ah != headers.end())&&(_authTokens.count(ah->second) > 0)) {
  273. isAuth = true;
  274. } else {
  275. ah = urlArgs.find("auth");
  276. if ((ah != urlArgs.end())&&(_authTokens.count(ah->second) > 0))
  277. isAuth = true;
  278. }
  279. }
  280. if (httpMethod == HTTP_GET) {
  281. std::string ext;
  282. std::size_t dotIdx = ps[0].find_last_of('.');
  283. if (dotIdx != std::string::npos)
  284. ext = ps[0].substr(dotIdx);
  285. if ((ps.size() == 1)&&(ext.length() >= 2)&&(ext[0] == '.')) {
  286. /* Static web pages can be served without authentication to enable a simple web
  287. * UI. This is still only allowed from approved IP addresses. Anything with a
  288. * dot in the first path element (e.g. foo.html) is considered a static page,
  289. * as nothing in the API is so named. */
  290. if (_uiStaticPath.length() > 0) {
  291. if (ext == ".html")
  292. responseContentType = "text/html";
  293. else if (ext == ".js")
  294. responseContentType = "application/javascript";
  295. else if (ext == ".jsx")
  296. responseContentType = "text/jsx";
  297. else if (ext == ".json")
  298. responseContentType = "application/json";
  299. else if (ext == ".css")
  300. responseContentType = "text/css";
  301. else if (ext == ".png")
  302. responseContentType = "image/png";
  303. else if (ext == ".jpg")
  304. responseContentType = "image/jpeg";
  305. else if (ext == ".gif")
  306. responseContentType = "image/gif";
  307. else if (ext == ".txt")
  308. responseContentType = "text/plain";
  309. else if (ext == ".xml")
  310. responseContentType = "text/xml";
  311. else if (ext == ".svg")
  312. responseContentType = "image/svg+xml";
  313. else responseContentType = "application/octet-stream";
  314. scode = OSUtils::readFile((_uiStaticPath + ZT_PATH_SEPARATOR_S + ps[0]).c_str(),responseBody) ? 200 : 404;
  315. } else {
  316. scode = 404;
  317. }
  318. } else if (isAuth) {
  319. /* Things that require authentication -- a.k.a. everything but static web app pages. */
  320. if (ps[0] == "status") {
  321. responseContentType = "application/json";
  322. ZT1_NodeStatus status;
  323. _node->status(&status);
  324. Utils::snprintf(json,sizeof(json),
  325. "{\n"
  326. "\t\"address\":\"%.10llx\",\n"
  327. "\t\"publicIdentity\":\"%s\",\n"
  328. "\t\"online\":%s,\n"
  329. "\t\"versionMajor\":%d,\n"
  330. "\t\"versionMinor\":%d,\n"
  331. "\t\"versionRev\":%d,\n"
  332. "\t\"version\":\"%d.%d.%d\"\n"
  333. "}\n",
  334. status.address,
  335. status.publicIdentity,
  336. (status.online) ? "true" : "false",
  337. ZEROTIER_ONE_VERSION_MAJOR,
  338. ZEROTIER_ONE_VERSION_MINOR,
  339. ZEROTIER_ONE_VERSION_REVISION,
  340. ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  341. responseBody = json;
  342. scode = 200;
  343. } else if (ps[0] == "config") {
  344. responseContentType = "application/json";
  345. responseBody = "{}"; // TODO
  346. scode = 200;
  347. } else if (ps[0] == "network") {
  348. ZT1_VirtualNetworkList *nws = _node->networks();
  349. if (nws) {
  350. if (ps.size() == 1) {
  351. // Return [array] of all networks
  352. responseContentType = "application/json";
  353. responseBody = "[\n";
  354. for(unsigned long i=0;i<nws->networkCount;++i) {
  355. if (i > 0)
  356. responseBody.append(",");
  357. _jsonAppend(1,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid));
  358. }
  359. responseBody.append("\n]\n");
  360. scode = 200;
  361. } else if (ps.size() == 2) {
  362. // Return a single network by ID or 404 if not found
  363. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  364. for(unsigned long i=0;i<nws->networkCount;++i) {
  365. if (nws->networks[i].nwid == wantnw) {
  366. responseContentType = "application/json";
  367. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid));
  368. responseBody.push_back('\n');
  369. scode = 200;
  370. break;
  371. }
  372. }
  373. } // else 404
  374. _node->freeQueryResult((void *)nws);
  375. } else scode = 500;
  376. } else if (ps[0] == "peer") {
  377. ZT1_PeerList *pl = _node->peers();
  378. if (pl) {
  379. if (ps.size() == 1) {
  380. // Return [array] of all peers
  381. responseContentType = "application/json";
  382. responseBody = "[\n";
  383. for(unsigned long i=0;i<pl->peerCount;++i) {
  384. if (i > 0)
  385. responseBody.append(",\n");
  386. _jsonAppend(1,responseBody,&(pl->peers[i]));
  387. }
  388. responseBody.append("\n]\n");
  389. scode = 200;
  390. } else if (ps.size() == 2) {
  391. // Return a single peer by ID or 404 if not found
  392. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  393. for(unsigned long i=0;i<pl->peerCount;++i) {
  394. if (pl->peers[i].address == wantp) {
  395. responseContentType = "application/json";
  396. _jsonAppend(0,responseBody,&(pl->peers[i]));
  397. responseBody.push_back('\n');
  398. scode = 200;
  399. break;
  400. }
  401. }
  402. } // else 404
  403. _node->freeQueryResult((void *)pl);
  404. } else scode = 500;
  405. } else {
  406. std::map<std::string,ControlPlaneSubsystem *>::const_iterator ss(_subsystems.find(ps[0]));
  407. if (ss != _subsystems.end())
  408. scode = ss->second->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  409. else scode = 404;
  410. }
  411. } else scode = 401; // isAuth == false
  412. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  413. if (isAuth) {
  414. if (ps[0] == "config") {
  415. // TODO
  416. } else if (ps[0] == "network") {
  417. if (ps.size() == 2) {
  418. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  419. _node->join(wantnw); // does nothing if we are a member
  420. ZT1_VirtualNetworkList *nws = _node->networks();
  421. if (nws) {
  422. for(unsigned long i=0;i<nws->networkCount;++i) {
  423. if (nws->networks[i].nwid == wantnw) {
  424. responseContentType = "application/json";
  425. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid));
  426. responseBody.push_back('\n');
  427. scode = 200;
  428. break;
  429. }
  430. }
  431. _node->freeQueryResult((void *)nws);
  432. } else scode = 500;
  433. }
  434. } else {
  435. std::map<std::string,ControlPlaneSubsystem *>::const_iterator ss(_subsystems.find(ps[0]));
  436. if (ss != _subsystems.end())
  437. scode = ss->second->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  438. else scode = 404;
  439. }
  440. } else scode = 401; // isAuth == false
  441. } else if (httpMethod == HTTP_DELETE) {
  442. if (isAuth) {
  443. if (ps[0] == "config") {
  444. // TODO
  445. } else if (ps[0] == "network") {
  446. ZT1_VirtualNetworkList *nws = _node->networks();
  447. if (nws) {
  448. if (ps.size() == 2) {
  449. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  450. for(unsigned long i=0;i<nws->networkCount;++i) {
  451. if (nws->networks[i].nwid == wantnw) {
  452. _node->leave(wantnw);
  453. responseBody = "true";
  454. responseContentType = "application/json";
  455. scode = 200;
  456. break;
  457. }
  458. }
  459. } // else 404
  460. _node->freeQueryResult((void *)nws);
  461. } else scode = 500;
  462. } else {
  463. std::map<std::string,ControlPlaneSubsystem *>::const_iterator ss(_subsystems.find(ps[0]));
  464. if (ss != _subsystems.end())
  465. scode = ss->second->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  466. else scode = 404;
  467. }
  468. } else {
  469. scode = 401; // isAuth = false
  470. }
  471. } else {
  472. scode = 400;
  473. responseBody = "Method not supported.";
  474. }
  475. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  476. // Also double-check isAuth since forbidding this without auth feels safer.
  477. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  478. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  479. if (responseBody.length() > 0)
  480. responseBody = jsonp->second + "(" + responseBody + ");";
  481. else responseBody = jsonp->second + "(null);";
  482. responseContentType = "application/javascript";
  483. }
  484. return scode;
  485. }
  486. } // namespace ZeroTier