ControlPlane.cpp 16 KB

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