one.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include "node/Constants.hpp"
  25. #ifdef __WINDOWS__
  26. #include <WinSock2.h>
  27. #include <Windows.h>
  28. #include <tchar.h>
  29. #include <wchar.h>
  30. #include <lmcons.h>
  31. #include <newdev.h>
  32. #include <atlbase.h>
  33. #include "osdep/WindowsEthernetTap.hpp"
  34. #include "windows/ZeroTierOne/ServiceInstaller.h"
  35. #include "windows/ZeroTierOne/ServiceBase.h"
  36. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  37. #else
  38. #include <unistd.h>
  39. #include <pwd.h>
  40. #include <fcntl.h>
  41. #include <sys/types.h>
  42. #include <sys/stat.h>
  43. #include <signal.h>
  44. #endif
  45. #include <string>
  46. #include <stdexcept>
  47. #include "version.h"
  48. #include "include/ZeroTierOne.h"
  49. #ifdef ZT_USE_SYSTEM_JSON_PARSER
  50. #include <json-parser/json.h>
  51. #else
  52. #include "ext/json-parser/json.h"
  53. #endif
  54. #include "node/Identity.hpp"
  55. #include "node/CertificateOfMembership.hpp"
  56. #include "node/Utils.hpp"
  57. #include "node/NetworkController.hpp"
  58. #include "osdep/OSUtils.hpp"
  59. #include "osdep/Http.hpp"
  60. #include "service/OneService.hpp"
  61. #define ZT_PID_PATH "zerotier-one.pid"
  62. using namespace ZeroTier;
  63. static OneService *volatile zt1Service = (OneService *)0;
  64. #define PROGRAM_NAME "ZeroTier One"
  65. #define COPYRIGHT_NOTICE "Copyright © 2011–2016 ZeroTier, Inc."
  66. #define LICENSE_GRANT \
  67. "This is free software: you may copy, modify, and/or distribute this" ZT_EOL_S \
  68. "work under the terms of the GNU General Public License, version 3 or" ZT_EOL_S \
  69. "later as published by the Free Software Foundation." ZT_EOL_S \
  70. "No warranty expressed or implied." ZT_EOL_S
  71. /****************************************************************************/
  72. /* zerotier-cli personality */
  73. /****************************************************************************/
  74. // This is getting deprecated soon in favor of the stuff in cli/
  75. static void cliPrintHelp(const char *pn,FILE *out)
  76. {
  77. fprintf(out,
  78. "%s version %d.%d.%d" ZT_EOL_S,
  79. PROGRAM_NAME,
  80. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  81. fprintf(out,
  82. COPYRIGHT_NOTICE ZT_EOL_S
  83. LICENSE_GRANT ZT_EOL_S);
  84. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  85. fprintf(out,"Available switches:" ZT_EOL_S);
  86. fprintf(out," -h - Display this help" ZT_EOL_S);
  87. fprintf(out," -v - Show version" ZT_EOL_S);
  88. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  89. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  90. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  91. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  92. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  93. fprintf(out," info - Display status info" ZT_EOL_S);
  94. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  95. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  96. fprintf(out," join <network> - Join a network" ZT_EOL_S);
  97. fprintf(out," leave <network> - Leave a network" ZT_EOL_S);
  98. fprintf(out," set <network> <setting> - Set a network setting" ZT_EOL_S);
  99. }
  100. static std::string cliFixJsonCRs(const std::string &s)
  101. {
  102. std::string r;
  103. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  104. if (*c == '\n')
  105. r.append(ZT_EOL_S);
  106. else r.push_back(*c);
  107. }
  108. return r;
  109. }
  110. #ifdef __WINDOWS__
  111. static int cli(int argc, _TCHAR* argv[])
  112. #else
  113. static int cli(int argc,char **argv)
  114. #endif
  115. {
  116. unsigned int port = 0;
  117. std::string homeDir,command,arg1,arg2,authToken;
  118. std::string ip("127.0.0.1");
  119. bool json = false;
  120. for(int i=1;i<argc;++i) {
  121. if (argv[i][0] == '-') {
  122. switch(argv[i][1]) {
  123. case 'q': // ignore -q used to invoke this personality
  124. if (argv[i][2]) {
  125. cliPrintHelp(argv[0],stdout);
  126. return 1;
  127. }
  128. break;
  129. case 'j':
  130. if (argv[i][2]) {
  131. cliPrintHelp(argv[0],stdout);
  132. return 1;
  133. }
  134. json = true;
  135. break;
  136. case 'p':
  137. port = Utils::strToUInt(argv[i] + 2);
  138. if ((port > 0xffff)||(port == 0)) {
  139. cliPrintHelp(argv[0],stdout);
  140. return 1;
  141. }
  142. break;
  143. case 'D':
  144. if (argv[i][2]) {
  145. homeDir = argv[i] + 2;
  146. } else {
  147. cliPrintHelp(argv[0],stdout);
  148. return 1;
  149. }
  150. break;
  151. case 'H':
  152. if (argv[i][2]) {
  153. ip = argv[i] + 2;
  154. } else {
  155. cliPrintHelp(argv[0],stdout);
  156. return 1;
  157. }
  158. break;
  159. case 'T':
  160. if (argv[i][2]) {
  161. authToken = argv[i] + 2;
  162. } else {
  163. cliPrintHelp(argv[0],stdout);
  164. return 1;
  165. }
  166. break;
  167. case 'v':
  168. if (argv[i][2]) {
  169. cliPrintHelp(argv[0],stdout);
  170. return 1;
  171. }
  172. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  173. return 0;
  174. case 'h':
  175. case '?':
  176. default:
  177. cliPrintHelp(argv[0],stdout);
  178. return 0;
  179. }
  180. } else {
  181. if (arg1.length())
  182. arg2 = argv[i];
  183. else if (command.length())
  184. arg1 = argv[i];
  185. else command = argv[i];
  186. }
  187. }
  188. if (!homeDir.length())
  189. homeDir = OneService::platformDefaultHomePath();
  190. if ((!port)||(!authToken.length())) {
  191. if (!homeDir.length()) {
  192. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  193. return 2;
  194. }
  195. if (!port) {
  196. std::string portStr;
  197. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  198. port = Utils::strToUInt(portStr.c_str());
  199. if ((port == 0)||(port > 0xffff)) {
  200. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  201. return 2;
  202. }
  203. }
  204. if (!authToken.length()) {
  205. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  206. #ifdef __UNIX_LIKE__
  207. if (!authToken.length()) {
  208. const char *hd = getenv("HOME");
  209. if (hd) {
  210. char p[4096];
  211. #ifdef __APPLE__
  212. Utils::snprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  213. #else
  214. Utils::snprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  215. #endif
  216. OSUtils::readFile(p,authToken);
  217. }
  218. }
  219. #endif
  220. if (!authToken.length()) {
  221. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  222. return 2;
  223. }
  224. }
  225. }
  226. InetAddress addr;
  227. {
  228. char addrtmp[256];
  229. Utils::snprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  230. addr = InetAddress(addrtmp);
  231. }
  232. std::map<std::string,std::string> requestHeaders;
  233. std::map<std::string,std::string> responseHeaders;
  234. std::string responseBody;
  235. requestHeaders["X-ZT1-Auth"] = authToken;
  236. if ((command.length() > 0)&&(command[0] == '/')) {
  237. unsigned int scode = Http::GET(
  238. 1024 * 1024 * 16,
  239. 60000,
  240. (const struct sockaddr *)&addr,
  241. command.c_str(),
  242. requestHeaders,
  243. responseHeaders,
  244. responseBody);
  245. if (scode == 200) {
  246. printf("%s",cliFixJsonCRs(responseBody).c_str());
  247. return 0;
  248. } else {
  249. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  250. return 1;
  251. }
  252. } else if ((command == "info")||(command == "status")) {
  253. unsigned int scode = Http::GET(
  254. 1024 * 1024 * 16,
  255. 60000,
  256. (const struct sockaddr *)&addr,
  257. "/status",
  258. requestHeaders,
  259. responseHeaders,
  260. responseBody);
  261. if (scode == 200) {
  262. if (json) {
  263. printf("%s",cliFixJsonCRs(responseBody).c_str());
  264. return 0;
  265. } else {
  266. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  267. bool good = false;
  268. if (j) {
  269. if (j->type == json_object) {
  270. const char *address = (const char *)0;
  271. bool online = false;
  272. const char *version = (const char *)0;
  273. for(unsigned int k=0;k<j->u.object.length;++k) {
  274. if ((!strcmp(j->u.object.values[k].name,"address"))&&(j->u.object.values[k].value->type == json_string))
  275. address = j->u.object.values[k].value->u.string.ptr;
  276. else if ((!strcmp(j->u.object.values[k].name,"version"))&&(j->u.object.values[k].value->type == json_string))
  277. version = j->u.object.values[k].value->u.string.ptr;
  278. else if ((!strcmp(j->u.object.values[k].name,"online"))&&(j->u.object.values[k].value->type == json_boolean))
  279. online = (j->u.object.values[k].value->u.boolean != 0);
  280. }
  281. if ((address)&&(version)) {
  282. printf("200 info %s %s %s" ZT_EOL_S,address,(online ? "ONLINE" : "OFFLINE"),version);
  283. good = true;
  284. }
  285. }
  286. json_value_free(j);
  287. }
  288. if (good) {
  289. return 0;
  290. } else {
  291. printf("%u %s invalid JSON response" ZT_EOL_S,scode,command.c_str());
  292. return 1;
  293. }
  294. }
  295. } else {
  296. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  297. return 1;
  298. }
  299. } else if (command == "listpeers") {
  300. unsigned int scode = Http::GET(
  301. 1024 * 1024 * 16,
  302. 60000,
  303. (const struct sockaddr *)&addr,
  304. "/peer",
  305. requestHeaders,
  306. responseHeaders,
  307. responseBody);
  308. if (scode == 200) {
  309. if (json) {
  310. printf("%s",cliFixJsonCRs(responseBody).c_str());
  311. return 0;
  312. } else {
  313. printf("200 listpeers <ztaddr> <paths> <latency> <version> <role>" ZT_EOL_S);
  314. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  315. if (j) {
  316. if (j->type == json_array) {
  317. for(unsigned int p=0;p<j->u.array.length;++p) {
  318. json_value *jp = j->u.array.values[p];
  319. if (jp->type == json_object) {
  320. const char *address = (const char *)0;
  321. std::string paths;
  322. int64_t latency = 0;
  323. int64_t versionMajor = -1,versionMinor = -1,versionRev = -1;
  324. const char *role = (const char *)0;
  325. for(unsigned int k=0;k<jp->u.object.length;++k) {
  326. if ((!strcmp(jp->u.object.values[k].name,"address"))&&(jp->u.object.values[k].value->type == json_string))
  327. address = jp->u.object.values[k].value->u.string.ptr;
  328. else if ((!strcmp(jp->u.object.values[k].name,"versionMajor"))&&(jp->u.object.values[k].value->type == json_integer))
  329. versionMajor = jp->u.object.values[k].value->u.integer;
  330. else if ((!strcmp(jp->u.object.values[k].name,"versionMinor"))&&(jp->u.object.values[k].value->type == json_integer))
  331. versionMinor = jp->u.object.values[k].value->u.integer;
  332. else if ((!strcmp(jp->u.object.values[k].name,"versionRev"))&&(jp->u.object.values[k].value->type == json_integer))
  333. versionRev = jp->u.object.values[k].value->u.integer;
  334. else if ((!strcmp(jp->u.object.values[k].name,"role"))&&(jp->u.object.values[k].value->type == json_string))
  335. role = jp->u.object.values[k].value->u.string.ptr;
  336. else if ((!strcmp(jp->u.object.values[k].name,"latency"))&&(jp->u.object.values[k].value->type == json_integer))
  337. latency = jp->u.object.values[k].value->u.integer;
  338. else if ((!strcmp(jp->u.object.values[k].name,"paths"))&&(jp->u.object.values[k].value->type == json_array)) {
  339. for(unsigned int pp=0;pp<jp->u.object.values[k].value->u.array.length;++pp) {
  340. json_value *jpath = jp->u.object.values[k].value->u.array.values[pp];
  341. if (jpath->type == json_object) {
  342. const char *paddr = (const char *)0;
  343. int64_t lastSend = 0;
  344. int64_t lastReceive = 0;
  345. bool preferred = false;
  346. bool active = false;
  347. for(unsigned int kk=0;kk<jpath->u.object.length;++kk) {
  348. if ((!strcmp(jpath->u.object.values[kk].name,"address"))&&(jpath->u.object.values[kk].value->type == json_string))
  349. paddr = jpath->u.object.values[kk].value->u.string.ptr;
  350. else if ((!strcmp(jpath->u.object.values[kk].name,"lastSend"))&&(jpath->u.object.values[kk].value->type == json_integer))
  351. lastSend = jpath->u.object.values[kk].value->u.integer;
  352. else if ((!strcmp(jpath->u.object.values[kk].name,"lastReceive"))&&(jpath->u.object.values[kk].value->type == json_integer))
  353. lastReceive = jpath->u.object.values[kk].value->u.integer;
  354. else if ((!strcmp(jpath->u.object.values[kk].name,"preferred"))&&(jpath->u.object.values[kk].value->type == json_boolean))
  355. preferred = (jpath->u.object.values[kk].value->u.boolean != 0);
  356. else if ((!strcmp(jpath->u.object.values[kk].name,"active"))&&(jpath->u.object.values[kk].value->type == json_boolean))
  357. active = (jpath->u.object.values[kk].value->u.boolean != 0);
  358. }
  359. if ((paddr)&&(active)) {
  360. int64_t now = (int64_t)OSUtils::now();
  361. if (lastSend > 0)
  362. lastSend = now - lastSend;
  363. if (lastReceive > 0)
  364. lastReceive = now - lastReceive;
  365. char pathtmp[256];
  366. Utils::snprintf(pathtmp,sizeof(pathtmp),"%s;%lld;%lld;%s",
  367. paddr,
  368. lastSend,
  369. lastReceive,
  370. (preferred ? "preferred" : "active"));
  371. if (paths.length())
  372. paths.push_back(',');
  373. paths.append(pathtmp);
  374. }
  375. }
  376. }
  377. }
  378. }
  379. if ((address)&&(role)) {
  380. char verstr[64];
  381. if ((versionMajor >= 0)&&(versionMinor >= 0)&&(versionRev >= 0))
  382. Utils::snprintf(verstr,sizeof(verstr),"%lld.%lld.%lld",versionMajor,versionMinor,versionRev);
  383. else {
  384. verstr[0] = '-';
  385. verstr[1] = (char)0;
  386. }
  387. printf("200 listpeers %s %s %lld %s %s" ZT_EOL_S,address,(paths.length()) ? paths.c_str() : "-",(long long)latency,verstr,role);
  388. }
  389. }
  390. }
  391. }
  392. json_value_free(j);
  393. }
  394. return 0;
  395. }
  396. } else {
  397. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  398. return 1;
  399. }
  400. } else if (command == "listnetworks") {
  401. unsigned int scode = Http::GET(
  402. 1024 * 1024 * 16,
  403. 60000,
  404. (const struct sockaddr *)&addr,
  405. "/network",
  406. requestHeaders,
  407. responseHeaders,
  408. responseBody);
  409. if (scode == 200) {
  410. if (json) {
  411. printf("%s",cliFixJsonCRs(responseBody).c_str());
  412. return 0;
  413. } else {
  414. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  415. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  416. if (j) {
  417. if (j->type == json_array) {
  418. for(unsigned int p=0;p<j->u.array.length;++p) {
  419. json_value *jn = j->u.array.values[p];
  420. if (jn->type == json_object) {
  421. const char *nwid = (const char *)0;
  422. const char *name = "";
  423. const char *mac = (const char *)0;
  424. const char *status = (const char *)0;
  425. const char *type = (const char *)0;
  426. const char *portDeviceName = "";
  427. std::string ips;
  428. for(unsigned int k=0;k<jn->u.object.length;++k) {
  429. if ((!strcmp(jn->u.object.values[k].name,"nwid"))&&(jn->u.object.values[k].value->type == json_string))
  430. nwid = jn->u.object.values[k].value->u.string.ptr;
  431. else if ((!strcmp(jn->u.object.values[k].name,"name"))&&(jn->u.object.values[k].value->type == json_string))
  432. name = jn->u.object.values[k].value->u.string.ptr;
  433. else if ((!strcmp(jn->u.object.values[k].name,"mac"))&&(jn->u.object.values[k].value->type == json_string))
  434. mac = jn->u.object.values[k].value->u.string.ptr;
  435. else if ((!strcmp(jn->u.object.values[k].name,"status"))&&(jn->u.object.values[k].value->type == json_string))
  436. status = jn->u.object.values[k].value->u.string.ptr;
  437. else if ((!strcmp(jn->u.object.values[k].name,"type"))&&(jn->u.object.values[k].value->type == json_string))
  438. type = jn->u.object.values[k].value->u.string.ptr;
  439. else if ((!strcmp(jn->u.object.values[k].name,"portDeviceName"))&&(jn->u.object.values[k].value->type == json_string))
  440. portDeviceName = jn->u.object.values[k].value->u.string.ptr;
  441. else if ((!strcmp(jn->u.object.values[k].name,"assignedAddresses"))&&(jn->u.object.values[k].value->type == json_array)) {
  442. for(unsigned int a=0;a<jn->u.object.values[k].value->u.array.length;++a) {
  443. json_value *aa = jn->u.object.values[k].value->u.array.values[a];
  444. if (aa->type == json_string) {
  445. if (ips.length())
  446. ips.push_back(',');
  447. ips.append(aa->u.string.ptr);
  448. }
  449. }
  450. }
  451. }
  452. if ((nwid)&&(mac)&&(status)&&(type)) {
  453. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  454. nwid,
  455. (((name)&&(name[0])) ? name : "-"),
  456. mac,
  457. status,
  458. type,
  459. (((portDeviceName)&&(portDeviceName[0])) ? portDeviceName : "-"),
  460. ((ips.length() > 0) ? ips.c_str() : "-"));
  461. }
  462. }
  463. }
  464. }
  465. json_value_free(j);
  466. }
  467. }
  468. } else {
  469. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  470. return 1;
  471. }
  472. } else if (command == "join") {
  473. if (arg1.length() != 16) {
  474. cliPrintHelp(argv[0],stderr);
  475. return 2;
  476. }
  477. requestHeaders["Content-Type"] = "application/json";
  478. requestHeaders["Content-Length"] = "2";
  479. unsigned int scode = Http::POST(
  480. 1024 * 1024 * 16,
  481. 60000,
  482. (const struct sockaddr *)&addr,
  483. (std::string("/network/") + arg1).c_str(),
  484. requestHeaders,
  485. "{}",
  486. 2,
  487. responseHeaders,
  488. responseBody);
  489. if (scode == 200) {
  490. if (json) {
  491. printf("%s",cliFixJsonCRs(responseBody).c_str());
  492. } else {
  493. printf("200 join OK" ZT_EOL_S);
  494. }
  495. return 0;
  496. } else {
  497. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  498. return 1;
  499. }
  500. } else if (command == "leave") {
  501. if (arg1.length() != 16) {
  502. cliPrintHelp(argv[0],stderr);
  503. return 2;
  504. }
  505. unsigned int scode = Http::DEL(
  506. 1024 * 1024 * 16,
  507. 60000,
  508. (const struct sockaddr *)&addr,
  509. (std::string("/network/") + arg1).c_str(),
  510. requestHeaders,
  511. responseHeaders,
  512. responseBody);
  513. if (scode == 200) {
  514. if (json) {
  515. printf("%s",cliFixJsonCRs(responseBody).c_str());
  516. } else {
  517. printf("200 leave OK" ZT_EOL_S);
  518. }
  519. return 0;
  520. } else {
  521. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  522. return 1;
  523. }
  524. } else if (command == "set") {
  525. if (arg1.length() != 16) {
  526. cliPrintHelp(argv[0],stderr);
  527. return 2;
  528. }
  529. std::size_t eqidx = arg2.find('=');
  530. if (eqidx != std::string::npos) {
  531. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")) {
  532. char jsons[1024];
  533. Utils::snprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  534. arg2.substr(0,eqidx).c_str(),
  535. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  536. char cl[128];
  537. Utils::snprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  538. requestHeaders["Content-Type"] = "application/json";
  539. requestHeaders["Content-Length"] = cl;
  540. unsigned int scode = Http::POST(
  541. 1024 * 1024 * 16,
  542. 60000,
  543. (const struct sockaddr *)&addr,
  544. (std::string("/network/") + arg1).c_str(),
  545. requestHeaders,
  546. jsons,
  547. strlen(jsons),
  548. responseHeaders,
  549. responseBody);
  550. if (scode == 200) {
  551. printf("%s",cliFixJsonCRs(responseBody).c_str());
  552. return 0;
  553. } else {
  554. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  555. return 1;
  556. }
  557. }
  558. } else {
  559. cliPrintHelp(argv[0],stderr);
  560. return 2;
  561. }
  562. } else {
  563. cliPrintHelp(argv[0],stderr);
  564. return 0;
  565. }
  566. return 0;
  567. }
  568. /****************************************************************************/
  569. /* zerotier-idtool personality */
  570. /****************************************************************************/
  571. static void idtoolPrintHelp(FILE *out,const char *pn)
  572. {
  573. fprintf(out,
  574. "%s version %d.%d.%d" ZT_EOL_S,
  575. PROGRAM_NAME,
  576. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  577. fprintf(out,
  578. COPYRIGHT_NOTICE ZT_EOL_S
  579. LICENSE_GRANT ZT_EOL_S);
  580. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  581. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  582. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  583. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  584. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  585. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  586. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)" ZT_EOL_S);
  587. }
  588. static Identity getIdFromArg(char *arg)
  589. {
  590. Identity id;
  591. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  592. if (id.fromString(arg))
  593. return id;
  594. } else { // identity is to be read from a file
  595. std::string idser;
  596. if (OSUtils::readFile(arg,idser)) {
  597. if (id.fromString(idser))
  598. return id;
  599. }
  600. }
  601. return Identity();
  602. }
  603. #ifdef __WINDOWS__
  604. static int idtool(int argc, _TCHAR* argv[])
  605. #else
  606. static int idtool(int argc,char **argv)
  607. #endif
  608. {
  609. if (argc < 2) {
  610. idtoolPrintHelp(stdout,argv[0]);
  611. return 1;
  612. }
  613. if (!strcmp(argv[1],"generate")) {
  614. uint64_t vanity = 0;
  615. int vanityBits = 0;
  616. if (argc >= 5) {
  617. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  618. vanityBits = 4 * strlen(argv[4]);
  619. if (vanityBits > 40)
  620. vanityBits = 40;
  621. }
  622. Identity id;
  623. for(;;) {
  624. id.generate();
  625. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  626. if (vanityBits > 0) {
  627. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  628. }
  629. break;
  630. } else {
  631. fprintf(stderr,"vanity address: tried %.10llx looking for first %d bits of %.10llx\n",(unsigned long long)id.address().toInt(),vanityBits,(unsigned long long)(vanity << (40 - vanityBits)));
  632. }
  633. }
  634. std::string idser = id.toString(true);
  635. if (argc >= 3) {
  636. if (!OSUtils::writeFile(argv[2],idser)) {
  637. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  638. return 1;
  639. } else printf("%s written" ZT_EOL_S,argv[2]);
  640. if (argc >= 4) {
  641. idser = id.toString(false);
  642. if (!OSUtils::writeFile(argv[3],idser)) {
  643. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  644. return 1;
  645. } else printf("%s written" ZT_EOL_S,argv[3]);
  646. }
  647. } else printf("%s",idser.c_str());
  648. } else if (!strcmp(argv[1],"validate")) {
  649. if (argc < 3) {
  650. idtoolPrintHelp(stdout,argv[0]);
  651. return 1;
  652. }
  653. Identity id = getIdFromArg(argv[2]);
  654. if (!id) {
  655. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  656. return 1;
  657. }
  658. if (!id.locallyValidate()) {
  659. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  660. return 1;
  661. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  662. } else if (!strcmp(argv[1],"getpublic")) {
  663. if (argc < 3) {
  664. idtoolPrintHelp(stdout,argv[0]);
  665. return 1;
  666. }
  667. Identity id = getIdFromArg(argv[2]);
  668. if (!id) {
  669. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  670. return 1;
  671. }
  672. printf("%s",id.toString(false).c_str());
  673. } else if (!strcmp(argv[1],"sign")) {
  674. if (argc < 4) {
  675. idtoolPrintHelp(stdout,argv[0]);
  676. return 1;
  677. }
  678. Identity id = getIdFromArg(argv[2]);
  679. if (!id) {
  680. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  681. return 1;
  682. }
  683. if (!id.hasPrivate()) {
  684. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  685. return 1;
  686. }
  687. std::string inf;
  688. if (!OSUtils::readFile(argv[3],inf)) {
  689. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  690. return 1;
  691. }
  692. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  693. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  694. } else if (!strcmp(argv[1],"verify")) {
  695. if (argc < 4) {
  696. idtoolPrintHelp(stdout,argv[0]);
  697. return 1;
  698. }
  699. Identity id = getIdFromArg(argv[2]);
  700. if (!id) {
  701. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  702. return 1;
  703. }
  704. std::string inf;
  705. if (!OSUtils::readFile(argv[3],inf)) {
  706. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  707. return 1;
  708. }
  709. std::string signature(Utils::unhex(argv[4]));
  710. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  711. printf("%s signature valid" ZT_EOL_S,argv[3]);
  712. } else {
  713. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  714. return 1;
  715. }
  716. } else if (!strcmp(argv[1],"mkcom")) {
  717. if (argc < 3) {
  718. idtoolPrintHelp(stdout,argv[0]);
  719. return 1;
  720. }
  721. Identity id = getIdFromArg(argv[2]);
  722. if ((!id)||(!id.hasPrivate())) {
  723. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s" ZT_EOL_S,argv[2]);
  724. return 1;
  725. }
  726. CertificateOfMembership com;
  727. for(int a=3;a<argc;++a) {
  728. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  729. if (params.size() == 3) {
  730. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  731. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  732. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  733. com.setQualifier(qId,qValue,qMaxDelta);
  734. }
  735. }
  736. if (!com.sign(id)) {
  737. fprintf(stderr,"Signature of certificate of membership failed." ZT_EOL_S);
  738. return 1;
  739. }
  740. printf("%s",com.toString().c_str());
  741. } else {
  742. idtoolPrintHelp(stdout,argv[0]);
  743. return 1;
  744. }
  745. return 0;
  746. }
  747. /****************************************************************************/
  748. /* Unix helper functions and signal handlers */
  749. /****************************************************************************/
  750. #ifdef __UNIX_LIKE__
  751. static void _sighandlerHup(int sig)
  752. {
  753. }
  754. static void _sighandlerQuit(int sig)
  755. {
  756. OneService *s = zt1Service;
  757. if (s)
  758. s->terminate();
  759. else exit(0);
  760. }
  761. #endif
  762. /****************************************************************************/
  763. /* Windows helper functions and signal handlers */
  764. /****************************************************************************/
  765. #ifdef __WINDOWS__
  766. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  767. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  768. {
  769. switch(dwCtrlType) {
  770. case CTRL_C_EVENT:
  771. case CTRL_BREAK_EVENT:
  772. case CTRL_CLOSE_EVENT:
  773. case CTRL_SHUTDOWN_EVENT:
  774. OneService *s = zt1Service;
  775. if (s)
  776. s->terminate();
  777. return TRUE;
  778. }
  779. return FALSE;
  780. }
  781. static void _winPokeAHole()
  782. {
  783. char myPath[MAX_PATH];
  784. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  785. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  786. STARTUPINFOA startupInfo;
  787. PROCESS_INFORMATION processInfo;
  788. startupInfo.cb = sizeof(startupInfo);
  789. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  790. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  791. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall delete rule name=\"ZeroTier One\" program=\"") + myPath + "\"").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  792. WaitForSingleObject(processInfo.hProcess,INFINITE);
  793. CloseHandle(processInfo.hProcess);
  794. CloseHandle(processInfo.hThread);
  795. }
  796. startupInfo.cb = sizeof(startupInfo);
  797. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  798. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  799. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=in action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  800. WaitForSingleObject(processInfo.hProcess,INFINITE);
  801. CloseHandle(processInfo.hProcess);
  802. CloseHandle(processInfo.hThread);
  803. }
  804. startupInfo.cb = sizeof(startupInfo);
  805. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  806. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  807. if (CreateProcessA(NULL,(LPSTR)(std::string("C:\\Windows\\System32\\netsh.exe advfirewall firewall add rule name=\"ZeroTier One\" dir=out action=allow program=\"") + myPath + "\" enable=yes").c_str(),NULL,NULL,FALSE,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  808. WaitForSingleObject(processInfo.hProcess,INFINITE);
  809. CloseHandle(processInfo.hProcess);
  810. CloseHandle(processInfo.hThread);
  811. }
  812. }
  813. }
  814. // Returns true if this is running as the local administrator
  815. static BOOL IsCurrentUserLocalAdministrator(void)
  816. {
  817. BOOL fReturn = FALSE;
  818. DWORD dwStatus;
  819. DWORD dwAccessMask;
  820. DWORD dwAccessDesired;
  821. DWORD dwACLSize;
  822. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  823. PACL pACL = NULL;
  824. PSID psidAdmin = NULL;
  825. HANDLE hToken = NULL;
  826. HANDLE hImpersonationToken = NULL;
  827. PRIVILEGE_SET ps;
  828. GENERIC_MAPPING GenericMapping;
  829. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  830. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  831. const DWORD ACCESS_READ = 1;
  832. const DWORD ACCESS_WRITE = 2;
  833. __try
  834. {
  835. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  836. {
  837. if (GetLastError() != ERROR_NO_TOKEN)
  838. __leave;
  839. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  840. __leave;
  841. }
  842. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  843. __leave;
  844. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  845. SECURITY_BUILTIN_DOMAIN_RID,
  846. DOMAIN_ALIAS_RID_ADMINS,
  847. 0, 0, 0, 0, 0, 0, &psidAdmin))
  848. __leave;
  849. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  850. if (psdAdmin == NULL)
  851. __leave;
  852. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  853. __leave;
  854. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  855. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  856. if (pACL == NULL)
  857. __leave;
  858. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  859. __leave;
  860. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  861. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  862. __leave;
  863. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  864. __leave;
  865. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  866. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  867. if (!IsValidSecurityDescriptor(psdAdmin))
  868. __leave;
  869. dwAccessDesired = ACCESS_READ;
  870. GenericMapping.GenericRead = ACCESS_READ;
  871. GenericMapping.GenericWrite = ACCESS_WRITE;
  872. GenericMapping.GenericExecute = 0;
  873. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  874. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  875. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  876. &fReturn))
  877. {
  878. fReturn = FALSE;
  879. __leave;
  880. }
  881. }
  882. __finally
  883. {
  884. // Clean up.
  885. if (pACL) LocalFree(pACL);
  886. if (psdAdmin) LocalFree(psdAdmin);
  887. if (psidAdmin) FreeSid(psidAdmin);
  888. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  889. if (hToken) CloseHandle (hToken);
  890. }
  891. return fReturn;
  892. }
  893. #endif // __WINDOWS__
  894. /****************************************************************************/
  895. /* main() and friends */
  896. /****************************************************************************/
  897. static void printHelp(const char *cn,FILE *out)
  898. {
  899. fprintf(out,
  900. "%s version %d.%d.%d" ZT_EOL_S,
  901. PROGRAM_NAME,
  902. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  903. fprintf(out,
  904. COPYRIGHT_NOTICE ZT_EOL_S
  905. LICENSE_GRANT ZT_EOL_S);
  906. std::string updateUrl(OneService::autoUpdateUrl());
  907. if (updateUrl.length())
  908. fprintf(out,"Automatic updates enabled:" ZT_EOL_S" %s" ZT_EOL_S" (all updates are securely authenticated by 256-bit ECDSA signature)" ZT_EOL_S"" ZT_EOL_S,updateUrl.c_str());
  909. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  910. fprintf(out,"Available switches:" ZT_EOL_S);
  911. fprintf(out," -h - Display this help" ZT_EOL_S);
  912. fprintf(out," -v - Show version" ZT_EOL_S);
  913. fprintf(out," -U - Run as unprivileged user (skip privilege check)" ZT_EOL_S);
  914. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  915. #ifdef __UNIX_LIKE__
  916. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  917. #endif // __UNIX_LIKE__
  918. #ifdef __WINDOWS__
  919. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  920. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  921. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  922. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  923. #endif // __WINDOWS__
  924. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  925. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  926. }
  927. #ifdef __WINDOWS__
  928. int _tmain(int argc, _TCHAR* argv[])
  929. #else
  930. int main(int argc,char **argv)
  931. #endif
  932. {
  933. #ifdef __UNIX_LIKE__
  934. signal(SIGHUP,&_sighandlerHup);
  935. signal(SIGPIPE,SIG_IGN);
  936. signal(SIGUSR1,SIG_IGN);
  937. signal(SIGUSR2,SIG_IGN);
  938. signal(SIGALRM,SIG_IGN);
  939. signal(SIGINT,&_sighandlerQuit);
  940. signal(SIGTERM,&_sighandlerQuit);
  941. signal(SIGQUIT,&_sighandlerQuit);
  942. /* Ensure that there are no inherited file descriptors open from a previous
  943. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  944. * of it do not return, and should not do anything otherwise bad. */
  945. {
  946. int mfd = STDIN_FILENO;
  947. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  948. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  949. for(int f=mfd+1;f<1024;++f)
  950. ::close(f);
  951. }
  952. bool runAsDaemon = false;
  953. #endif // __UNIX_LIKE__
  954. #ifdef __WINDOWS__
  955. {
  956. WSADATA wsaData;
  957. WSAStartup(MAKEWORD(2,2),&wsaData);
  958. }
  959. #ifdef ZT_WIN_RUN_IN_CONSOLE
  960. bool winRunFromCommandLine = true;
  961. #else
  962. bool winRunFromCommandLine = false;
  963. #endif
  964. #endif // __WINDOWS__
  965. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  966. return idtool(argc,argv);
  967. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  968. return cli(argc,argv);
  969. std::string homeDir;
  970. unsigned int port = ZT_DEFAULT_PORT;
  971. bool skipRootCheck = false;
  972. for(int i=1;i<argc;++i) {
  973. if (argv[i][0] == '-') {
  974. switch(argv[i][1]) {
  975. case 'p': // port -- for both UDP and TCP, packets and control plane
  976. port = Utils::strToUInt(argv[i] + 2);
  977. if (port > 0xffff) {
  978. printHelp(argv[0],stdout);
  979. return 1;
  980. }
  981. break;
  982. #ifdef __UNIX_LIKE__
  983. case 'd': // Run in background as daemon
  984. runAsDaemon = true;
  985. break;
  986. #endif // __UNIX_LIKE__
  987. case 'U':
  988. skipRootCheck = true;
  989. break;
  990. case 'v': // Display version
  991. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  992. return 0;
  993. case 'i': // Invoke idtool personality
  994. if (argv[i][2]) {
  995. printHelp(argv[0],stdout);
  996. return 0;
  997. } else return idtool(argc,argv);
  998. case 'q': // Invoke cli personality
  999. if (argv[i][2]) {
  1000. printHelp(argv[0],stdout);
  1001. return 0;
  1002. } else return cli(argc,argv);
  1003. #ifdef __WINDOWS__
  1004. case 'C': // Run from command line instead of as Windows service
  1005. winRunFromCommandLine = true;
  1006. break;
  1007. case 'I': { // Install this binary as a Windows service
  1008. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1009. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1010. return 1;
  1011. }
  1012. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1013. if (ret.length()) {
  1014. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1015. return 3;
  1016. }
  1017. return 0;
  1018. } break;
  1019. case 'R': { // Uninstall this binary as Windows service
  1020. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1021. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1022. return 1;
  1023. }
  1024. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1025. if (ret.length()) {
  1026. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1027. return 3;
  1028. }
  1029. return 0;
  1030. } break;
  1031. case 'D': {
  1032. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1033. if (err.length() > 0) {
  1034. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1035. return 3;
  1036. }
  1037. return 0;
  1038. } break;
  1039. #endif // __WINDOWS__
  1040. case 'h':
  1041. case '?':
  1042. default:
  1043. printHelp(argv[0],stdout);
  1044. return 0;
  1045. }
  1046. } else {
  1047. if (homeDir.length()) {
  1048. printHelp(argv[0],stdout);
  1049. return 0;
  1050. } else {
  1051. homeDir = argv[i];
  1052. }
  1053. }
  1054. }
  1055. if (!homeDir.length())
  1056. homeDir = OneService::platformDefaultHomePath();
  1057. if (!homeDir.length()) {
  1058. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1059. return 1;
  1060. } else {
  1061. std::vector<std::string> hpsp(Utils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1062. std::string ptmp;
  1063. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1064. ptmp.push_back(ZT_PATH_SEPARATOR);
  1065. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1066. if (ptmp.length() > 0)
  1067. ptmp.push_back(ZT_PATH_SEPARATOR);
  1068. ptmp.append(*pi);
  1069. if ((*pi != ".")&&(*pi != "..")) {
  1070. if (!OSUtils::mkdir(ptmp))
  1071. throw std::runtime_error("home path does not exist, and could not create");
  1072. }
  1073. }
  1074. }
  1075. #ifdef __UNIX_LIKE__
  1076. #ifndef ZT_ONE_NO_ROOT_CHECK
  1077. if ((!skipRootCheck)&&(getuid() != 0)) {
  1078. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1079. return 1;
  1080. }
  1081. #endif // !ZT_ONE_NO_ROOT_CHECK
  1082. if (runAsDaemon) {
  1083. long p = (long)fork();
  1084. if (p < 0) {
  1085. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1086. return 1;
  1087. } else if (p > 0)
  1088. return 0; // forked
  1089. // else p == 0, so we are daemonized
  1090. }
  1091. #endif // __UNIX_LIKE__
  1092. #ifdef __WINDOWS__
  1093. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1094. // when tap instances are created.
  1095. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1096. if (winRunFromCommandLine) {
  1097. // Running in "interactive" mode (mostly for debugging)
  1098. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1099. if (!skipRootCheck) {
  1100. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1101. return 1;
  1102. }
  1103. } else {
  1104. _winPokeAHole();
  1105. }
  1106. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1107. // continues on to ordinary command line execution code below...
  1108. } else {
  1109. // Running from service manager
  1110. _winPokeAHole();
  1111. ZeroTierOneService zt1Service;
  1112. if (CServiceBase::Run(zt1Service) == TRUE) {
  1113. return 0;
  1114. } else {
  1115. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1116. return 1;
  1117. }
  1118. }
  1119. #endif // __WINDOWS__
  1120. #ifdef __UNIX_LIKE__
  1121. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1122. {
  1123. // Write .pid file to home folder
  1124. FILE *pf = fopen(pidPath.c_str(),"w");
  1125. if (pf) {
  1126. fprintf(pf,"%ld",(long)getpid());
  1127. fclose(pf);
  1128. }
  1129. }
  1130. #endif // __UNIX_LIKE__
  1131. unsigned int returnValue = 0;
  1132. for(;;) {
  1133. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1134. switch(zt1Service->run()) {
  1135. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1136. case OneService::ONE_NORMAL_TERMINATION:
  1137. break;
  1138. case OneService::ONE_UNRECOVERABLE_ERROR:
  1139. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  1140. returnValue = 1;
  1141. break;
  1142. case OneService::ONE_IDENTITY_COLLISION: {
  1143. delete zt1Service;
  1144. zt1Service = (OneService *)0;
  1145. std::string oldid;
  1146. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1147. if (oldid.length()) {
  1148. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1149. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1150. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1151. }
  1152. } continue; // restart!
  1153. }
  1154. break; // terminate loop -- normally we don't keep restarting
  1155. }
  1156. delete zt1Service;
  1157. zt1Service = (OneService *)0;
  1158. #ifdef __UNIX_LIKE__
  1159. OSUtils::rm(pidPath.c_str());
  1160. #endif
  1161. return returnValue;
  1162. }