ControlPlane.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. #define ZT_BUILD_IN_WEB_UI
  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->mac >> 40) & 0xff),
  67. (unsigned int)((mg->mac >> 32) & 0xff),
  68. (unsigned int)((mg->mac >> 24) & 0xff),
  69. (unsigned int)((mg->mac >> 16) & 0xff),
  70. (unsigned int)((mg->mac >> 8) & 0xff),
  71. (unsigned int)(mg->mac & 0xff),
  72. mg->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)->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) :
  225. _svc(svc),
  226. _node(n)
  227. {
  228. }
  229. ControlPlane::~ControlPlane()
  230. {
  231. }
  232. unsigned int ControlPlane::handleRequest(
  233. const InetAddress &fromAddress,
  234. unsigned int httpMethod,
  235. const std::string &path,
  236. const std::map<std::string,std::string> &headers,
  237. const std::string &body,
  238. std::string &responseBody,
  239. std::string &responseContentType)
  240. {
  241. char json[1024];
  242. unsigned int scode = 404;
  243. std::vector<std::string> ps(Utils::split(path.c_str(),"/","",""));
  244. std::map<std::string,std::string> urlArgs;
  245. Mutex::Lock _l(_lock);
  246. if (!((fromAddress.ipsEqual(InetAddress::LO4))||(fromAddress.ipsEqual(InetAddress::LO6))))
  247. return 403; // Forbidden: we only allow access from localhost right now
  248. /* Note: this is kind of restricted in what it'll take. It does not support
  249. * URL encoding, and /'s in URL args will screw it up. But the only URL args
  250. * it really uses in ?jsonp=funcionName, and otherwise it just takes simple
  251. * paths to simply-named resources. */
  252. if (ps.size() > 0) {
  253. std::size_t qpos = ps[ps.size() - 1].find('?');
  254. if (qpos != std::string::npos) {
  255. std::string args(ps[ps.size() - 1].substr(qpos + 1));
  256. ps[ps.size() - 1] = ps[ps.size() - 1].substr(0,qpos);
  257. std::vector<std::string> asplit(Utils::split(args.c_str(),"&","",""));
  258. for(std::vector<std::string>::iterator a(asplit.begin());a!=asplit.end();++a) {
  259. std::size_t eqpos = a->find('=');
  260. if (eqpos == std::string::npos)
  261. urlArgs[*a] = "";
  262. else urlArgs[a->substr(0,eqpos)] = a->substr(eqpos + 1);
  263. }
  264. }
  265. } else {
  266. ps.push_back(std::string("index.html"));
  267. }
  268. bool isAuth = false;
  269. {
  270. std::map<std::string,std::string>::const_iterator ah(headers.find("x-zt1-auth"));
  271. if ((ah != headers.end())&&(_authTokens.count(ah->second) > 0)) {
  272. isAuth = true;
  273. } else {
  274. ah = urlArgs.find("auth");
  275. if ((ah != urlArgs.end())&&(_authTokens.count(ah->second) > 0))
  276. isAuth = true;
  277. }
  278. }
  279. if (httpMethod == HTTP_GET) {
  280. std::string ext;
  281. std::size_t dotIdx = ps[0].find_last_of('.');
  282. if (dotIdx != std::string::npos)
  283. ext = ps[0].substr(dotIdx);
  284. if ((ps.size() == 1)&&(ext.length() >= 2)&&(ext[0] == '.')) {
  285. /* Static web pages can be served without authentication to enable a simple web
  286. * UI. This is still only allowed from approved IP addresses. Anything with a
  287. * dot in the first path element (e.g. foo.html) is considered a static page,
  288. * as nothing in the API is so named. */
  289. #ifdef ZT_BUILD_IN_WEB_UI
  290. if (ext == ".html")
  291. responseContentType = "text/html";
  292. else if (ext == ".js")
  293. responseContentType = "application/javascript";
  294. else if (ext == ".json")
  295. responseContentType = "application/json";
  296. else if (ext == ".css")
  297. responseContentType = "text/css";
  298. else if (ext == ".png")
  299. responseContentType = "image/png";
  300. else if (ext == ".jpg")
  301. responseContentType = "image/jpeg";
  302. else if (ext == ".gif")
  303. responseContentType = "image/gif";
  304. else if (ext == ".txt")
  305. responseContentType = "text/plain";
  306. else if (ext == ".xml")
  307. responseContentType = "text/xml";
  308. else if (ext == ".svg")
  309. responseContentType = "image/svg+xml";
  310. else responseContentType = "application/octet-stream";
  311. responseBody = "<html><body>Hello World!</body></html>";
  312. scode = 200;
  313. #endif // ZT_BUILD_IN_WEB_UI
  314. } else if (isAuth) {
  315. /* Things that require authentication -- a.k.a. everything but static web app pages. */
  316. if (ps[0] == "status") {
  317. responseContentType = "application/json";
  318. ZT1_NodeStatus status;
  319. _node->status(&status);
  320. Utils::snprintf(json,sizeof(json),
  321. "{\n"
  322. "\t\"address\":\"%.10llx\",\n"
  323. "\t\"publicIdentity\":\"%s\",\n"
  324. "\t\"online\":%s,\n"
  325. "\t\"versionMajor\":%d,\n"
  326. "\t\"versionMinor\":%d,\n"
  327. "\t\"versionRev\":%d,\n"
  328. "\t\"version\":\"%d.%d.%d\"\n"
  329. "}\n",
  330. status.address,
  331. status.publicIdentity,
  332. (status.online) ? "true" : "false",
  333. ZEROTIER_ONE_VERSION_MAJOR,
  334. ZEROTIER_ONE_VERSION_MINOR,
  335. ZEROTIER_ONE_VERSION_REVISION,
  336. ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  337. responseBody = json;
  338. scode = 200;
  339. } else if (ps[0] == "config") {
  340. responseContentType = "application/json";
  341. responseBody = "{}"; // TODO
  342. scode = 200;
  343. } else if (ps[0] == "network") {
  344. ZT1_VirtualNetworkList *nws = _node->networks();
  345. if (nws) {
  346. if (ps.size() == 1) {
  347. // Return [array] of all networks
  348. responseContentType = "application/json";
  349. responseBody = "[\n";
  350. for(unsigned long i=0;i<nws->networkCount;++i) {
  351. if (i > 0)
  352. responseBody.append(",");
  353. _jsonAppend(1,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid));
  354. }
  355. responseBody.append("\n]\n");
  356. scode = 200;
  357. } else if (ps.size() == 2) {
  358. // Return a single network by ID or 404 if not found
  359. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  360. for(unsigned long i=0;i<nws->networkCount;++i) {
  361. if (nws->networks[i].nwid == wantnw) {
  362. responseContentType = "application/json";
  363. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid));
  364. responseBody.push_back('\n');
  365. scode = 200;
  366. break;
  367. }
  368. }
  369. } // else 404
  370. _node->freeQueryResult((void *)nws);
  371. } else scode = 500;
  372. } else if (ps[0] == "peer") {
  373. ZT1_PeerList *pl = _node->peers();
  374. if (pl) {
  375. if (ps.size() == 1) {
  376. // Return [array] of all peers
  377. responseContentType = "application/json";
  378. responseBody = "[\n";
  379. for(unsigned long i=0;i<pl->peerCount;++i) {
  380. if (i > 0)
  381. responseBody.append(",\n");
  382. _jsonAppend(1,responseBody,&(pl->peers[i]));
  383. }
  384. responseBody.append("\n]\n");
  385. scode = 200;
  386. } else if (ps.size() == 2) {
  387. // Return a single peer by ID or 404 if not found
  388. uint64_t wantp = Utils::hexStrToU64(ps[1].c_str());
  389. for(unsigned long i=0;i<pl->peerCount;++i) {
  390. if (pl->peers[i].address == wantp) {
  391. responseContentType = "application/json";
  392. _jsonAppend(0,responseBody,&(pl->peers[i]));
  393. responseBody.push_back('\n');
  394. scode = 200;
  395. break;
  396. }
  397. }
  398. } // else 404
  399. _node->freeQueryResult((void *)pl);
  400. } else scode = 500;
  401. } else {
  402. std::map<std::string,ControlPlaneSubsystem *>::const_iterator ss(_subsystems.find(ps[0]));
  403. if (ss != _subsystems.end())
  404. scode = ss->second->handleControlPlaneHttpGET(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  405. else scode = 404;
  406. }
  407. } else scode = 401; // isAuth == false
  408. } else if ((httpMethod == HTTP_POST)||(httpMethod == HTTP_PUT)) {
  409. if (isAuth) {
  410. if (ps[0] == "config") {
  411. // TODO
  412. } else if (ps[0] == "network") {
  413. if (ps.size() == 2) {
  414. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  415. _node->join(wantnw); // does nothing if we are a member
  416. ZT1_VirtualNetworkList *nws = _node->networks();
  417. if (nws) {
  418. for(unsigned long i=0;i<nws->networkCount;++i) {
  419. if (nws->networks[i].nwid == wantnw) {
  420. responseContentType = "application/json";
  421. _jsonAppend(0,responseBody,&(nws->networks[i]),_svc->portDeviceName(nws->networks[i].nwid));
  422. responseBody.push_back('\n');
  423. scode = 200;
  424. break;
  425. }
  426. }
  427. _node->freeQueryResult((void *)nws);
  428. } else scode = 500;
  429. }
  430. } else {
  431. std::map<std::string,ControlPlaneSubsystem *>::const_iterator ss(_subsystems.find(ps[0]));
  432. if (ss != _subsystems.end())
  433. scode = ss->second->handleControlPlaneHttpPOST(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  434. else scode = 404;
  435. }
  436. } else scode = 401; // isAuth == false
  437. } else if (httpMethod == HTTP_DELETE) {
  438. if (isAuth) {
  439. if (ps[0] == "config") {
  440. // TODO
  441. } else if (ps[0] == "network") {
  442. ZT1_VirtualNetworkList *nws = _node->networks();
  443. if (nws) {
  444. if (ps.size() == 2) {
  445. uint64_t wantnw = Utils::hexStrToU64(ps[1].c_str());
  446. for(unsigned long i=0;i<nws->networkCount;++i) {
  447. if (nws->networks[i].nwid == wantnw) {
  448. _node->leave(wantnw);
  449. responseBody = "true";
  450. responseContentType = "application/json";
  451. scode = 200;
  452. break;
  453. }
  454. }
  455. } // else 404
  456. _node->freeQueryResult((void *)nws);
  457. } else scode = 500;
  458. } else {
  459. std::map<std::string,ControlPlaneSubsystem *>::const_iterator ss(_subsystems.find(ps[0]));
  460. if (ss != _subsystems.end())
  461. scode = ss->second->handleControlPlaneHttpDELETE(std::vector<std::string>(ps.begin()+1,ps.end()),urlArgs,headers,body,responseBody,responseContentType);
  462. else scode = 404;
  463. }
  464. } else {
  465. scode = 401; // isAuth = false
  466. }
  467. } else {
  468. scode = 400;
  469. responseBody = "Method not supported.";
  470. }
  471. // Wrap result in jsonp function call if the user included a jsonp= url argument.
  472. // Also double-check isAuth since forbidding this without auth feels safer.
  473. std::map<std::string,std::string>::const_iterator jsonp(urlArgs.find("jsonp"));
  474. if ((isAuth)&&(jsonp != urlArgs.end())&&(responseContentType == "application/json")) {
  475. if (responseBody.length() > 0)
  476. responseBody = jsonp->second + "(" + responseBody + ");";
  477. else responseBody = jsonp->second + "(null);";
  478. responseContentType = "application/javascript";
  479. }
  480. return scode;
  481. }
  482. } // namespace ZeroTier