ControlPlane.cpp 14 KB

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