ControlPlane.cpp 14 KB

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