one.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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. static void cliPrintHelp(const char *pn,FILE *out)
  75. {
  76. fprintf(out,
  77. "%s version %d.%d.%d" ZT_EOL_S,
  78. PROGRAM_NAME,
  79. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  80. fprintf(out,
  81. COPYRIGHT_NOTICE ZT_EOL_S
  82. LICENSE_GRANT ZT_EOL_S);
  83. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]"ZT_EOL_S""ZT_EOL_S,pn);
  84. fprintf(out,"Available switches:"ZT_EOL_S);
  85. fprintf(out," -h - Display this help"ZT_EOL_S);
  86. fprintf(out," -v - Show version"ZT_EOL_S);
  87. fprintf(out," -j - Display full raw JSON output"ZT_EOL_S);
  88. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect"ZT_EOL_S);
  89. fprintf(out," -p<port> - HTTP port (default: auto)"ZT_EOL_S);
  90. fprintf(out," -T<token> - Authentication token (default: auto)"ZT_EOL_S);
  91. //fprintf(out," -H<ip> - HTTP server bind address (default: 127.0.0.1)"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. }
  99. static std::string cliFixJsonCRs(const std::string &s)
  100. {
  101. std::string r;
  102. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  103. if (*c == '\n')
  104. r.append(ZT_EOL_S);
  105. else r.push_back(*c);
  106. }
  107. return r;
  108. }
  109. #ifdef __WINDOWS__
  110. static int cli(int argc, _TCHAR* argv[])
  111. #else
  112. static int cli(int argc,char **argv)
  113. #endif
  114. {
  115. unsigned int port = 0;
  116. std::string homeDir;
  117. std::string command;
  118. std::string arg1;
  119. std::string authToken;
  120. std::string ip("127.0.0.1");
  121. bool json = false;
  122. for(int i=1;i<argc;++i) {
  123. if (argv[i][0] == '-') {
  124. switch(argv[i][1]) {
  125. case 'q': // ignore -q used to invoke this personality
  126. if (argv[i][2]) {
  127. cliPrintHelp(argv[0],stdout);
  128. return 1;
  129. }
  130. break;
  131. case 'j':
  132. if (argv[i][2]) {
  133. cliPrintHelp(argv[0],stdout);
  134. return 1;
  135. }
  136. json = true;
  137. break;
  138. case 'p':
  139. port = Utils::strToUInt(argv[i] + 2);
  140. if ((port > 0xffff)||(port == 0)) {
  141. cliPrintHelp(argv[0],stdout);
  142. return 1;
  143. }
  144. break;
  145. case 'D':
  146. if (argv[i][2]) {
  147. homeDir = argv[i] + 2;
  148. } else {
  149. cliPrintHelp(argv[0],stdout);
  150. return 1;
  151. }
  152. break;
  153. case 'H':
  154. if (argv[i][2]) {
  155. ip = argv[i] + 2;
  156. } else {
  157. cliPrintHelp(argv[0],stdout);
  158. return 1;
  159. }
  160. break;
  161. case 'T':
  162. if (argv[i][2]) {
  163. authToken = argv[i] + 2;
  164. } else {
  165. cliPrintHelp(argv[0],stdout);
  166. return 1;
  167. }
  168. break;
  169. case 'v':
  170. if (argv[i][2]) {
  171. cliPrintHelp(argv[0],stdout);
  172. return 1;
  173. }
  174. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  175. return 0;
  176. case 'h':
  177. case '?':
  178. default:
  179. cliPrintHelp(argv[0],stdout);
  180. return 0;
  181. }
  182. } else {
  183. 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 {
  525. cliPrintHelp(argv[0],stderr);
  526. return 0;
  527. }
  528. return 0;
  529. }
  530. /****************************************************************************/
  531. /* zerotier-idtool personality */
  532. /****************************************************************************/
  533. static void idtoolPrintHelp(FILE *out,const char *pn)
  534. {
  535. fprintf(out,
  536. "%s version %d.%d.%d" ZT_EOL_S,
  537. PROGRAM_NAME,
  538. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  539. fprintf(out,
  540. COPYRIGHT_NOTICE ZT_EOL_S
  541. LICENSE_GRANT ZT_EOL_S);
  542. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  543. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]"ZT_EOL_S);
  544. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  545. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  546. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  547. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  548. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
  549. }
  550. static Identity getIdFromArg(char *arg)
  551. {
  552. Identity id;
  553. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  554. if (id.fromString(arg))
  555. return id;
  556. } else { // identity is to be read from a file
  557. std::string idser;
  558. if (OSUtils::readFile(arg,idser)) {
  559. if (id.fromString(idser))
  560. return id;
  561. }
  562. }
  563. return Identity();
  564. }
  565. #ifdef __WINDOWS__
  566. static int idtool(int argc, _TCHAR* argv[])
  567. #else
  568. static int idtool(int argc,char **argv)
  569. #endif
  570. {
  571. if (argc < 2) {
  572. idtoolPrintHelp(stdout,argv[0]);
  573. return 1;
  574. }
  575. if (!strcmp(argv[1],"generate")) {
  576. uint64_t vanity = 0;
  577. int vanityBits = 0;
  578. if (argc >= 5) {
  579. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  580. vanityBits = 4 * strlen(argv[4]);
  581. if (vanityBits > 40)
  582. vanityBits = 40;
  583. }
  584. Identity id;
  585. for(;;) {
  586. id.generate();
  587. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  588. if (vanityBits > 0) {
  589. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  590. }
  591. break;
  592. } else {
  593. 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)));
  594. }
  595. }
  596. std::string idser = id.toString(true);
  597. if (argc >= 3) {
  598. if (!OSUtils::writeFile(argv[2],idser)) {
  599. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  600. return 1;
  601. } else printf("%s written"ZT_EOL_S,argv[2]);
  602. if (argc >= 4) {
  603. idser = id.toString(false);
  604. if (!OSUtils::writeFile(argv[3],idser)) {
  605. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  606. return 1;
  607. } else printf("%s written"ZT_EOL_S,argv[3]);
  608. }
  609. } else printf("%s",idser.c_str());
  610. } else if (!strcmp(argv[1],"validate")) {
  611. if (argc < 3) {
  612. idtoolPrintHelp(stdout,argv[0]);
  613. return 1;
  614. }
  615. Identity id = getIdFromArg(argv[2]);
  616. if (!id) {
  617. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  618. return 1;
  619. }
  620. if (!id.locallyValidate()) {
  621. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  622. return 1;
  623. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  624. } else if (!strcmp(argv[1],"getpublic")) {
  625. if (argc < 3) {
  626. idtoolPrintHelp(stdout,argv[0]);
  627. return 1;
  628. }
  629. Identity id = getIdFromArg(argv[2]);
  630. if (!id) {
  631. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  632. return 1;
  633. }
  634. printf("%s",id.toString(false).c_str());
  635. } else if (!strcmp(argv[1],"sign")) {
  636. if (argc < 4) {
  637. idtoolPrintHelp(stdout,argv[0]);
  638. return 1;
  639. }
  640. Identity id = getIdFromArg(argv[2]);
  641. if (!id) {
  642. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  643. return 1;
  644. }
  645. if (!id.hasPrivate()) {
  646. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  647. return 1;
  648. }
  649. std::string inf;
  650. if (!OSUtils::readFile(argv[3],inf)) {
  651. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  652. return 1;
  653. }
  654. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  655. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  656. } else if (!strcmp(argv[1],"verify")) {
  657. if (argc < 4) {
  658. idtoolPrintHelp(stdout,argv[0]);
  659. return 1;
  660. }
  661. Identity id = getIdFromArg(argv[2]);
  662. if (!id) {
  663. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  664. return 1;
  665. }
  666. std::string inf;
  667. if (!OSUtils::readFile(argv[3],inf)) {
  668. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  669. return 1;
  670. }
  671. std::string signature(Utils::unhex(argv[4]));
  672. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  673. printf("%s signature valid"ZT_EOL_S,argv[3]);
  674. } else {
  675. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  676. return 1;
  677. }
  678. } else if (!strcmp(argv[1],"mkcom")) {
  679. if (argc < 3) {
  680. idtoolPrintHelp(stdout,argv[0]);
  681. return 1;
  682. }
  683. Identity id = getIdFromArg(argv[2]);
  684. if ((!id)||(!id.hasPrivate())) {
  685. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
  686. return 1;
  687. }
  688. CertificateOfMembership com;
  689. for(int a=3;a<argc;++a) {
  690. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  691. if (params.size() == 3) {
  692. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  693. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  694. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  695. com.setQualifier(qId,qValue,qMaxDelta);
  696. }
  697. }
  698. if (!com.sign(id)) {
  699. fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
  700. return 1;
  701. }
  702. printf("%s",com.toString().c_str());
  703. } else {
  704. idtoolPrintHelp(stdout,argv[0]);
  705. return 1;
  706. }
  707. return 0;
  708. }
  709. /****************************************************************************/
  710. /* Unix helper functions and signal handlers */
  711. /****************************************************************************/
  712. #ifdef __UNIX_LIKE__
  713. static void _sighandlerHup(int sig)
  714. {
  715. }
  716. static void _sighandlerQuit(int sig)
  717. {
  718. OneService *s = zt1Service;
  719. if (s)
  720. s->terminate();
  721. else exit(0);
  722. }
  723. #endif
  724. /****************************************************************************/
  725. /* Windows helper functions and signal handlers */
  726. /****************************************************************************/
  727. #ifdef __WINDOWS__
  728. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  729. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  730. {
  731. switch(dwCtrlType) {
  732. case CTRL_C_EVENT:
  733. case CTRL_BREAK_EVENT:
  734. case CTRL_CLOSE_EVENT:
  735. case CTRL_SHUTDOWN_EVENT:
  736. OneService *s = zt1Service;
  737. if (s)
  738. s->terminate();
  739. return TRUE;
  740. }
  741. return FALSE;
  742. }
  743. static void _winPokeAHole()
  744. {
  745. char myPath[MAX_PATH];
  746. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  747. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  748. STARTUPINFOA startupInfo;
  749. PROCESS_INFORMATION processInfo;
  750. startupInfo.cb = sizeof(startupInfo);
  751. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  752. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  753. 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)) {
  754. WaitForSingleObject(processInfo.hProcess,INFINITE);
  755. CloseHandle(processInfo.hProcess);
  756. CloseHandle(processInfo.hThread);
  757. }
  758. startupInfo.cb = sizeof(startupInfo);
  759. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  760. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  761. 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)) {
  762. WaitForSingleObject(processInfo.hProcess,INFINITE);
  763. CloseHandle(processInfo.hProcess);
  764. CloseHandle(processInfo.hThread);
  765. }
  766. startupInfo.cb = sizeof(startupInfo);
  767. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  768. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  769. 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)) {
  770. WaitForSingleObject(processInfo.hProcess,INFINITE);
  771. CloseHandle(processInfo.hProcess);
  772. CloseHandle(processInfo.hThread);
  773. }
  774. }
  775. }
  776. // Returns true if this is running as the local administrator
  777. static BOOL IsCurrentUserLocalAdministrator(void)
  778. {
  779. BOOL fReturn = FALSE;
  780. DWORD dwStatus;
  781. DWORD dwAccessMask;
  782. DWORD dwAccessDesired;
  783. DWORD dwACLSize;
  784. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  785. PACL pACL = NULL;
  786. PSID psidAdmin = NULL;
  787. HANDLE hToken = NULL;
  788. HANDLE hImpersonationToken = NULL;
  789. PRIVILEGE_SET ps;
  790. GENERIC_MAPPING GenericMapping;
  791. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  792. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  793. const DWORD ACCESS_READ = 1;
  794. const DWORD ACCESS_WRITE = 2;
  795. __try
  796. {
  797. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  798. {
  799. if (GetLastError() != ERROR_NO_TOKEN)
  800. __leave;
  801. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  802. __leave;
  803. }
  804. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  805. __leave;
  806. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  807. SECURITY_BUILTIN_DOMAIN_RID,
  808. DOMAIN_ALIAS_RID_ADMINS,
  809. 0, 0, 0, 0, 0, 0, &psidAdmin))
  810. __leave;
  811. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  812. if (psdAdmin == NULL)
  813. __leave;
  814. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  815. __leave;
  816. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  817. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  818. if (pACL == NULL)
  819. __leave;
  820. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  821. __leave;
  822. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  823. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  824. __leave;
  825. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  826. __leave;
  827. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  828. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  829. if (!IsValidSecurityDescriptor(psdAdmin))
  830. __leave;
  831. dwAccessDesired = ACCESS_READ;
  832. GenericMapping.GenericRead = ACCESS_READ;
  833. GenericMapping.GenericWrite = ACCESS_WRITE;
  834. GenericMapping.GenericExecute = 0;
  835. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  836. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  837. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  838. &fReturn))
  839. {
  840. fReturn = FALSE;
  841. __leave;
  842. }
  843. }
  844. __finally
  845. {
  846. // Clean up.
  847. if (pACL) LocalFree(pACL);
  848. if (psdAdmin) LocalFree(psdAdmin);
  849. if (psidAdmin) FreeSid(psidAdmin);
  850. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  851. if (hToken) CloseHandle (hToken);
  852. }
  853. return fReturn;
  854. }
  855. #endif // __WINDOWS__
  856. /****************************************************************************/
  857. /* main() and friends */
  858. /****************************************************************************/
  859. static void printHelp(const char *cn,FILE *out)
  860. {
  861. fprintf(out,
  862. "%s version %d.%d.%d" ZT_EOL_S,
  863. PROGRAM_NAME,
  864. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  865. fprintf(out,
  866. COPYRIGHT_NOTICE ZT_EOL_S
  867. LICENSE_GRANT ZT_EOL_S);
  868. std::string updateUrl(OneService::autoUpdateUrl());
  869. if (updateUrl.length())
  870. 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());
  871. fprintf(out,"Usage: %s [-switches] [home directory]"ZT_EOL_S""ZT_EOL_S,cn);
  872. fprintf(out,"Available switches:"ZT_EOL_S);
  873. fprintf(out," -h - Display this help"ZT_EOL_S);
  874. fprintf(out," -v - Show version"ZT_EOL_S);
  875. fprintf(out," -U - Run as unprivileged user (skip privilege check)"ZT_EOL_S);
  876. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)"ZT_EOL_S);
  877. #ifdef __UNIX_LIKE__
  878. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  879. #endif // __UNIX_LIKE__
  880. #ifdef __WINDOWS__
  881. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  882. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  883. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  884. fprintf(out," -D - Remove all instances of Windows tap device (Windows)"ZT_EOL_S);
  885. #endif // __WINDOWS__
  886. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  887. fprintf(out," -q - Query API (zerotier-cli)"ZT_EOL_S);
  888. }
  889. #ifdef __WINDOWS__
  890. int _tmain(int argc, _TCHAR* argv[])
  891. #else
  892. int main(int argc,char **argv)
  893. #endif
  894. {
  895. #ifdef __UNIX_LIKE__
  896. signal(SIGHUP,&_sighandlerHup);
  897. signal(SIGPIPE,SIG_IGN);
  898. signal(SIGUSR1,SIG_IGN);
  899. signal(SIGUSR2,SIG_IGN);
  900. signal(SIGALRM,SIG_IGN);
  901. signal(SIGINT,&_sighandlerQuit);
  902. signal(SIGTERM,&_sighandlerQuit);
  903. signal(SIGQUIT,&_sighandlerQuit);
  904. /* Ensure that there are no inherited file descriptors open from a previous
  905. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  906. * of it do not return, and should not do anything otherwise bad. */
  907. {
  908. int mfd = STDIN_FILENO;
  909. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  910. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  911. for(int f=mfd+1;f<1024;++f)
  912. ::close(f);
  913. }
  914. bool runAsDaemon = false;
  915. #endif // __UNIX_LIKE__
  916. #ifdef __WINDOWS__
  917. {
  918. WSADATA wsaData;
  919. WSAStartup(MAKEWORD(2,2),&wsaData);
  920. }
  921. #ifdef ZT_WIN_RUN_IN_CONSOLE
  922. bool winRunFromCommandLine = true;
  923. #else
  924. bool winRunFromCommandLine = false;
  925. #endif
  926. #endif // __WINDOWS__
  927. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  928. return idtool(argc,argv);
  929. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  930. return cli(argc,argv);
  931. std::string homeDir;
  932. unsigned int port = ZT_DEFAULT_PORT;
  933. bool skipRootCheck = false;
  934. for(int i=1;i<argc;++i) {
  935. if (argv[i][0] == '-') {
  936. switch(argv[i][1]) {
  937. case 'p': // port -- for both UDP and TCP, packets and control plane
  938. port = Utils::strToUInt(argv[i] + 2);
  939. if (port > 0xffff) {
  940. printHelp(argv[0],stdout);
  941. return 1;
  942. }
  943. break;
  944. #ifdef __UNIX_LIKE__
  945. case 'd': // Run in background as daemon
  946. runAsDaemon = true;
  947. break;
  948. #endif // __UNIX_LIKE__
  949. case 'U':
  950. skipRootCheck = true;
  951. break;
  952. case 'v': // Display version
  953. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  954. return 0;
  955. case 'i': // Invoke idtool personality
  956. if (argv[i][2]) {
  957. printHelp(argv[0],stdout);
  958. return 0;
  959. } else return idtool(argc,argv);
  960. case 'q': // Invoke cli personality
  961. if (argv[i][2]) {
  962. printHelp(argv[0],stdout);
  963. return 0;
  964. } else return cli(argc,argv);
  965. #ifdef __WINDOWS__
  966. case 'C': // Run from command line instead of as Windows service
  967. winRunFromCommandLine = true;
  968. break;
  969. case 'I': { // Install this binary as a Windows service
  970. if (IsCurrentUserLocalAdministrator() != TRUE) {
  971. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  972. return 1;
  973. }
  974. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  975. if (ret.length()) {
  976. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  977. return 3;
  978. }
  979. return 0;
  980. } break;
  981. case 'R': { // Uninstall this binary as Windows service
  982. if (IsCurrentUserLocalAdministrator() != TRUE) {
  983. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  984. return 1;
  985. }
  986. std::string ret(UninstallService(ZT_SERVICE_NAME));
  987. if (ret.length()) {
  988. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  989. return 3;
  990. }
  991. return 0;
  992. } break;
  993. case 'D': {
  994. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  995. if (err.length() > 0) {
  996. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s"ZT_EOL_S,argv[0],err.c_str());
  997. return 3;
  998. }
  999. return 0;
  1000. } break;
  1001. #endif // __WINDOWS__
  1002. case 'h':
  1003. case '?':
  1004. default:
  1005. printHelp(argv[0],stdout);
  1006. return 0;
  1007. }
  1008. } else {
  1009. if (homeDir.length()) {
  1010. printHelp(argv[0],stdout);
  1011. return 0;
  1012. } else {
  1013. homeDir = argv[i];
  1014. }
  1015. }
  1016. }
  1017. if (!homeDir.length())
  1018. homeDir = OneService::platformDefaultHomePath();
  1019. if (!homeDir.length()) {
  1020. fprintf(stderr,"%s: no home path specified and no platform default available"ZT_EOL_S,argv[0]);
  1021. return 1;
  1022. } else {
  1023. std::vector<std::string> hpsp(Utils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1024. std::string ptmp;
  1025. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1026. ptmp.push_back(ZT_PATH_SEPARATOR);
  1027. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1028. if (ptmp.length() > 0)
  1029. ptmp.push_back(ZT_PATH_SEPARATOR);
  1030. ptmp.append(*pi);
  1031. if ((*pi != ".")&&(*pi != "..")) {
  1032. if (!OSUtils::mkdir(ptmp))
  1033. throw std::runtime_error("home path does not exist, and could not create");
  1034. }
  1035. }
  1036. }
  1037. #ifdef __UNIX_LIKE__
  1038. #ifndef ZT_ONE_NO_ROOT_CHECK
  1039. if ((!skipRootCheck)&&(getuid() != 0)) {
  1040. fprintf(stderr,"%s: must be run as root (uid 0)"ZT_EOL_S,argv[0]);
  1041. return 1;
  1042. }
  1043. #endif // !ZT_ONE_NO_ROOT_CHECK
  1044. if (runAsDaemon) {
  1045. long p = (long)fork();
  1046. if (p < 0) {
  1047. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  1048. return 1;
  1049. } else if (p > 0)
  1050. return 0; // forked
  1051. // else p == 0, so we are daemonized
  1052. }
  1053. #endif // __UNIX_LIKE__
  1054. #ifdef __WINDOWS__
  1055. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1056. // when tap instances are created.
  1057. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1058. if (winRunFromCommandLine) {
  1059. // Running in "interactive" mode (mostly for debugging)
  1060. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1061. if (!skipRootCheck) {
  1062. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  1063. return 1;
  1064. }
  1065. } else {
  1066. _winPokeAHole();
  1067. }
  1068. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1069. // continues on to ordinary command line execution code below...
  1070. } else {
  1071. // Running from service manager
  1072. _winPokeAHole();
  1073. ZeroTierOneService zt1Service;
  1074. if (CServiceBase::Run(zt1Service) == TRUE) {
  1075. return 0;
  1076. } else {
  1077. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  1078. return 1;
  1079. }
  1080. }
  1081. #endif // __WINDOWS__
  1082. #ifdef __UNIX_LIKE__
  1083. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1084. {
  1085. // Write .pid file to home folder
  1086. FILE *pf = fopen(pidPath.c_str(),"w");
  1087. if (pf) {
  1088. fprintf(pf,"%ld",(long)getpid());
  1089. fclose(pf);
  1090. }
  1091. }
  1092. #endif // __UNIX_LIKE__
  1093. unsigned int returnValue = 0;
  1094. for(;;) {
  1095. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1096. switch(zt1Service->run()) {
  1097. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1098. case OneService::ONE_NORMAL_TERMINATION:
  1099. break;
  1100. case OneService::ONE_UNRECOVERABLE_ERROR:
  1101. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  1102. returnValue = 1;
  1103. break;
  1104. case OneService::ONE_IDENTITY_COLLISION: {
  1105. delete zt1Service;
  1106. zt1Service = (OneService *)0;
  1107. std::string oldid;
  1108. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1109. if (oldid.length()) {
  1110. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1111. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1112. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1113. }
  1114. } continue; // restart!
  1115. }
  1116. break; // terminate loop -- normally we don't keep restarting
  1117. }
  1118. delete zt1Service;
  1119. zt1Service = (OneService *)0;
  1120. #ifdef __UNIX_LIKE__
  1121. OSUtils::rm(pidPath.c_str());
  1122. #endif
  1123. return returnValue;
  1124. }