main.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <time.h>
  31. #include <errno.h>
  32. #include <string>
  33. #include <stdexcept>
  34. #include "node/Constants.hpp"
  35. #ifdef __WINDOWS__
  36. #include <WinSock2.h>
  37. #include <Windows.h>
  38. #include <tchar.h>
  39. #include <wchar.h>
  40. #include <lmcons.h>
  41. #include <newdev.h>
  42. #include "windows/ZeroTierOne/ServiceInstaller.h"
  43. #include "windows/ZeroTierOne/ServiceBase.h"
  44. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  45. #else
  46. #include <unistd.h>
  47. #include <pwd.h>
  48. #include <fcntl.h>
  49. #include <sys/types.h>
  50. #include <sys/stat.h>
  51. #include <signal.h>
  52. #endif
  53. #include "node/Constants.hpp"
  54. #include "node/Defaults.hpp"
  55. #include "node/Utils.hpp"
  56. #include "node/Node.hpp"
  57. #include "node/Condition.hpp"
  58. #include "node/C25519.hpp"
  59. #include "node/Identity.hpp"
  60. using namespace ZeroTier;
  61. static Node *node = (Node *)0;
  62. static void printHelp(const char *cn,FILE *out)
  63. {
  64. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2014 ZeroTier Networks LLC"ZT_EOL_S,Node::versionMajor(),Node::versionMinor(),Node::versionRevision());
  65. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  66. #ifdef ZT_AUTO_UPDATE
  67. fprintf(out,"Auto-update enabled build, will update from URL:"ZT_EOL_S);
  68. fprintf(out," %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  69. fprintf(out,"Update authentication signing authorities: "ZT_EOL_S);
  70. int no = 0;
  71. for(std::map< Address,Identity >::const_iterator sa(ZT_DEFAULTS.updateAuthorities.begin());sa!=ZT_DEFAULTS.updateAuthorities.end();++sa) {
  72. if (no == 0)
  73. fprintf(out," %s",sa->first.toString().c_str());
  74. else fprintf(out,", %s",sa->first.toString().c_str());
  75. if (++no == 6) {
  76. fprintf(out,ZT_EOL_S);
  77. no = 0;
  78. }
  79. }
  80. fprintf(out,ZT_EOL_S""ZT_EOL_S);
  81. #else
  82. fprintf(out,"Auto-updates not enabled on this build. You must update manually."ZT_EOL_S""ZT_EOL_S);
  83. #endif
  84. fprintf(out,"Usage: %s [-switches] [home directory]"ZT_EOL_S""ZT_EOL_S,cn);
  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," -p<port> - Bind to this port for network I/O"ZT_EOL_S);
  89. fprintf(out," -c<port> - Bind to this port for local control packets"ZT_EOL_S);
  90. #ifdef __UNIX_LIKE__
  91. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  92. #endif
  93. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  94. fprintf(out," -i - Run idtool command (zerotier-idtool)"ZT_EOL_S);
  95. #ifdef __WINDOWS__
  96. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  97. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  98. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  99. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  100. #endif
  101. }
  102. namespace ZeroTierCLI { // ---------------------------------------------------
  103. static void printHelp(FILE *out,const char *exename)
  104. {
  105. fprintf(out,"Usage: %s [-switches] <command>"ZT_EOL_S,exename);
  106. fprintf(out,ZT_EOL_S);
  107. fprintf(out,"Available switches:"ZT_EOL_S);
  108. fprintf(out," -c<port> - Communicate with daemon over this local port"ZT_EOL_S);
  109. fprintf(out," -t<token> - Specify token on command line"ZT_EOL_S);
  110. fprintf(out," -T<file> - Read token from file"ZT_EOL_S);
  111. fprintf(out,ZT_EOL_S);
  112. fprintf(out,"Use the 'help' command to get help from ZeroTier One itself."ZT_EOL_S);
  113. }
  114. static volatile unsigned int numResults = 0;
  115. static Condition doneCondition;
  116. static void resultHandler(void *arg,unsigned long id,const char *line)
  117. {
  118. ++numResults;
  119. if (strlen(line))
  120. fprintf(stdout,"%s"ZT_EOL_S,line);
  121. else doneCondition.signal();
  122. }
  123. // Runs instead of rest of main() if process is called zerotier-cli or if
  124. // -q is specified as an option.
  125. #ifdef __WINDOWS__
  126. static int main(int argc,_TCHAR* argv[])
  127. #else
  128. static int main(int argc,char **argv)
  129. #endif
  130. {
  131. if (argc <= 1) {
  132. printHelp(stdout,argv[0]);
  133. return -1;
  134. }
  135. std::string authToken;
  136. std::string command;
  137. bool pastSwitches = false;
  138. unsigned int controlPort = 0;
  139. for(int i=1;i<argc;++i) {
  140. if ((argv[i][0] == '-')&&(!pastSwitches)) {
  141. if (strlen(argv[i]) <= 1) {
  142. printHelp(stdout,argv[0]);
  143. return -1;
  144. }
  145. switch(argv[i][1]) {
  146. case 'q': // does nothing, for invocation without binary path name aliasing
  147. if (argv[i][2]) {
  148. printHelp(argv[0],stderr);
  149. return 0;
  150. }
  151. break;
  152. case 'c':
  153. controlPort = Utils::strToUInt(argv[i] + 2);
  154. break;
  155. case 't':
  156. authToken.assign(argv[i] + 2);
  157. break;
  158. case 'T':
  159. if (!Utils::readFile(argv[i] + 2,authToken)) {
  160. fprintf(stdout,"FATAL ERROR: unable to read token from '%s'"ZT_EOL_S,argv[i] + 2);
  161. return -2;
  162. }
  163. break;
  164. case 'h':
  165. printHelp(stdout,argv[0]);
  166. return 0;
  167. default:
  168. return -1;
  169. }
  170. } else {
  171. pastSwitches = true;
  172. if (command.length())
  173. command.push_back(' ');
  174. command.append(argv[i]);
  175. }
  176. }
  177. if (!command.length()) {
  178. printHelp(stdout,argv[0]);
  179. return -1;
  180. }
  181. if (!authToken.length()) {
  182. if (!Utils::readFile(Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  183. if (!Utils::readFile(Node::LocalClient::authTokenDefaultSystemPath().c_str(),authToken)) {
  184. fprintf(stdout,"FATAL ERROR: no token specified on command line and could not read '%s' or '%s'"ZT_EOL_S,Node::LocalClient::authTokenDefaultSystemPath().c_str(),Node::LocalClient::authTokenDefaultUserPath().c_str());
  185. return -2;
  186. }
  187. }
  188. }
  189. if (!authToken.length()) {
  190. fprintf(stdout,"FATAL ERROR: could not find auth token"ZT_EOL_S);
  191. return -2;
  192. }
  193. Node::LocalClient client(authToken.c_str(),controlPort,&resultHandler,(void *)0);
  194. client.send(command.c_str());
  195. doneCondition.wait(1000);
  196. if (!numResults) {
  197. fprintf(stdout,"ERROR: no results received. Is ZeroTier One running?"ZT_EOL_S);
  198. return -1;
  199. }
  200. return 0;
  201. }
  202. } // namespace ZeroTierCLI ---------------------------------------------------
  203. namespace ZeroTierIdTool { // ------------------------------------------------
  204. static void printHelp(FILE *out,const char *pn)
  205. {
  206. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  207. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  208. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  209. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  210. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  211. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  212. }
  213. static Identity getIdFromArg(char *arg)
  214. {
  215. Identity id;
  216. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  217. if (id.fromString(arg))
  218. return id;
  219. } else { // identity is to be read from a file
  220. std::string idser;
  221. if (Utils::readFile(arg,idser)) {
  222. if (id.fromString(idser))
  223. return id;
  224. }
  225. }
  226. return Identity();
  227. }
  228. // Runs instead of rest of main() if process is called zerotier-idtool or if
  229. // -i is specified as an option.
  230. #ifdef __WINDOWS__
  231. static int main(int argc,_TCHAR* argv[])
  232. #else
  233. static int main(int argc,char **argv)
  234. #endif
  235. {
  236. if (argc < 2) {
  237. printHelp(stderr,argv[0]);
  238. return -1;
  239. }
  240. if (!strcmp(argv[1],"generate")) {
  241. Identity id;
  242. id.generate();
  243. std::string idser = id.toString(true);
  244. if (argc >= 3) {
  245. if (!Utils::writeFile(argv[2],idser)) {
  246. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  247. return -1;
  248. } else printf("%s written"ZT_EOL_S,argv[2]);
  249. if (argc >= 4) {
  250. idser = id.toString(false);
  251. if (!Utils::writeFile(argv[3],idser)) {
  252. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  253. return -1;
  254. } else printf("%s written"ZT_EOL_S,argv[3]);
  255. }
  256. } else printf("%s",idser.c_str());
  257. } else if (!strcmp(argv[1],"validate")) {
  258. if (argc < 3) {
  259. printHelp(stderr,argv[0]);
  260. return -1;
  261. }
  262. Identity id = getIdFromArg(argv[2]);
  263. if (!id) {
  264. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  265. return -1;
  266. }
  267. if (!id.locallyValidate()) {
  268. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  269. return -1;
  270. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  271. } else if (!strcmp(argv[1],"getpublic")) {
  272. if (argc < 3) {
  273. printHelp(stderr,argv[0]);
  274. return -1;
  275. }
  276. Identity id = getIdFromArg(argv[2]);
  277. if (!id) {
  278. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  279. return -1;
  280. }
  281. printf("%s",id.toString(false).c_str());
  282. } else if (!strcmp(argv[1],"sign")) {
  283. if (argc < 4) {
  284. printHelp(stderr,argv[0]);
  285. return -1;
  286. }
  287. Identity id = getIdFromArg(argv[2]);
  288. if (!id) {
  289. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  290. return -1;
  291. }
  292. if (!id.hasPrivate()) {
  293. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  294. return -1;
  295. }
  296. std::string inf;
  297. if (!Utils::readFile(argv[3],inf)) {
  298. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  299. return -1;
  300. }
  301. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  302. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  303. } else if (!strcmp(argv[1],"verify")) {
  304. if (argc < 4) {
  305. printHelp(stderr,argv[0]);
  306. return -1;
  307. }
  308. Identity id = getIdFromArg(argv[2]);
  309. if (!id) {
  310. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  311. return -1;
  312. }
  313. std::string inf;
  314. if (!Utils::readFile(argv[3],inf)) {
  315. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  316. return -1;
  317. }
  318. std::string signature(Utils::unhex(argv[4]));
  319. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  320. printf("%s signature valid"ZT_EOL_S,argv[3]);
  321. } else {
  322. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  323. return -1;
  324. }
  325. } else {
  326. printHelp(stderr,argv[0]);
  327. return -1;
  328. }
  329. return 0;
  330. }
  331. } // namespace ZeroTierIdTool ------------------------------------------------
  332. #ifdef __UNIX_LIKE__
  333. static void sighandlerHup(int sig)
  334. {
  335. Node *n = node;
  336. if (n)
  337. n->resync();
  338. }
  339. static void sighandlerQuit(int sig)
  340. {
  341. Node *n = node;
  342. if (n)
  343. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  344. else exit(0);
  345. }
  346. #endif
  347. #ifdef __WINDOWS__
  348. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  349. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  350. {
  351. switch(dwCtrlType) {
  352. case CTRL_C_EVENT:
  353. case CTRL_BREAK_EVENT:
  354. case CTRL_CLOSE_EVENT:
  355. case CTRL_SHUTDOWN_EVENT:
  356. Node *n = node;
  357. if (n)
  358. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  359. return TRUE;
  360. }
  361. return FALSE;
  362. }
  363. // Returns true if this is running as the local administrator
  364. static BOOL IsCurrentUserLocalAdministrator(void)
  365. {
  366. BOOL fReturn = FALSE;
  367. DWORD dwStatus;
  368. DWORD dwAccessMask;
  369. DWORD dwAccessDesired;
  370. DWORD dwACLSize;
  371. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  372. PACL pACL = NULL;
  373. PSID psidAdmin = NULL;
  374. HANDLE hToken = NULL;
  375. HANDLE hImpersonationToken = NULL;
  376. PRIVILEGE_SET ps;
  377. GENERIC_MAPPING GenericMapping;
  378. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  379. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  380. const DWORD ACCESS_READ = 1;
  381. const DWORD ACCESS_WRITE = 2;
  382. __try
  383. {
  384. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  385. {
  386. if (GetLastError() != ERROR_NO_TOKEN)
  387. __leave;
  388. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  389. __leave;
  390. }
  391. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  392. __leave;
  393. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  394. SECURITY_BUILTIN_DOMAIN_RID,
  395. DOMAIN_ALIAS_RID_ADMINS,
  396. 0, 0, 0, 0, 0, 0, &psidAdmin))
  397. __leave;
  398. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  399. if (psdAdmin == NULL)
  400. __leave;
  401. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  402. __leave;
  403. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  404. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  405. if (pACL == NULL)
  406. __leave;
  407. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  408. __leave;
  409. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  410. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  411. __leave;
  412. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  413. __leave;
  414. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  415. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  416. if (!IsValidSecurityDescriptor(psdAdmin))
  417. __leave;
  418. dwAccessDesired = ACCESS_READ;
  419. GenericMapping.GenericRead = ACCESS_READ;
  420. GenericMapping.GenericWrite = ACCESS_WRITE;
  421. GenericMapping.GenericExecute = 0;
  422. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  423. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  424. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  425. &fReturn))
  426. {
  427. fReturn = FALSE;
  428. __leave;
  429. }
  430. }
  431. __finally
  432. {
  433. // Clean up.
  434. if (pACL) LocalFree(pACL);
  435. if (psdAdmin) LocalFree(psdAdmin);
  436. if (psidAdmin) FreeSid(psidAdmin);
  437. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  438. if (hToken) CloseHandle (hToken);
  439. }
  440. return fReturn;
  441. }
  442. #endif // __WINDOWS__
  443. #ifdef __WINDOWS__
  444. int _tmain(int argc, _TCHAR* argv[])
  445. #else
  446. int main(int argc,char **argv)
  447. #endif
  448. {
  449. #ifdef __UNIX_LIKE__
  450. signal(SIGHUP,&sighandlerHup);
  451. signal(SIGPIPE,SIG_IGN);
  452. signal(SIGUSR1,SIG_IGN);
  453. signal(SIGUSR2,SIG_IGN);
  454. signal(SIGALRM,SIG_IGN);
  455. signal(SIGINT,&sighandlerQuit);
  456. signal(SIGTERM,&sighandlerQuit);
  457. signal(SIGQUIT,&sighandlerQuit);
  458. #endif
  459. #ifdef __WINDOWS__
  460. WSADATA wsaData;
  461. WSAStartup(MAKEWORD(2,2),&wsaData);
  462. #endif
  463. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  464. return ZeroTierCLI::main(argc,argv);
  465. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  466. return ZeroTierIdTool::main(argc,argv);
  467. const char *homeDir = (const char *)0;
  468. unsigned int port = 0;
  469. unsigned int controlPort = 0;
  470. #ifdef __UNIX_LIKE__
  471. bool runAsDaemon = false;
  472. #endif
  473. #ifdef __WINDOWS__
  474. bool winRunFromCommandLine = false;
  475. #endif
  476. for(int i=1;i<argc;++i) {
  477. if (argv[i][0] == '-') {
  478. switch(argv[i][1]) {
  479. case 'p':
  480. port = Utils::strToUInt(argv[i] + 2);
  481. if (port > 65535) {
  482. printHelp(argv[0],stderr);
  483. return 1;
  484. }
  485. break;
  486. #ifdef __UNIX_LIKE__
  487. case 'd':
  488. runAsDaemon = true;
  489. break;
  490. #endif
  491. case 'v':
  492. printf("%s"ZT_EOL_S,Node::versionString());
  493. return 0;
  494. case 'c':
  495. controlPort = Utils::strToUInt(argv[i] + 2);
  496. if (controlPort > 65535) {
  497. printHelp(argv[0],stderr);
  498. return 1;
  499. }
  500. break;
  501. case 'q':
  502. if (argv[i][2]) {
  503. printHelp(argv[0],stderr);
  504. return 0;
  505. } else return ZeroTierCLI::main(argc,argv);
  506. case 'i':
  507. if (argv[i][2]) {
  508. printHelp(argv[0],stderr);
  509. return 0;
  510. } else return ZeroTierIdTool::main(argc,argv);
  511. #ifdef __WINDOWS__
  512. case 'C':
  513. winRunFromCommandLine = true;
  514. break;
  515. case 'I': { // install self as service
  516. if (IsCurrentUserLocalAdministrator() != TRUE) {
  517. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  518. return 1;
  519. }
  520. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  521. if (ret.length()) {
  522. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  523. return 3;
  524. }
  525. return 0;
  526. } break;
  527. case 'R': { // uninstall self as service
  528. if (IsCurrentUserLocalAdministrator() != TRUE) {
  529. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  530. return 1;
  531. }
  532. std::string ret(UninstallService(ZT_SERVICE_NAME));
  533. if (ret.length()) {
  534. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  535. return 3;
  536. }
  537. return 0;
  538. } break;
  539. case 'D': { // install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
  540. std::string pathToInf;
  541. #ifdef _WIN64
  542. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
  543. #else
  544. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
  545. #endif
  546. BOOL needReboot = FALSE;
  547. if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
  548. fprintf(stderr,"%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
  549. return 0;
  550. } else {
  551. fprintf(stderr,"%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
  552. return 3;
  553. }
  554. } break;
  555. #endif // __WINDOWS__
  556. case 'h':
  557. case '?':
  558. default:
  559. printHelp(argv[0],stderr);
  560. return 0;
  561. }
  562. } else {
  563. if (homeDir) {
  564. printHelp(argv[0],stderr);
  565. return 0;
  566. }
  567. homeDir = argv[i];
  568. break;
  569. }
  570. }
  571. if ((!homeDir)||(strlen(homeDir) == 0))
  572. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  573. #ifdef __UNIX_LIKE__
  574. if (getuid() != 0) {
  575. fprintf(stderr,"%s: must be run as root (uid 0)\n",argv[0]);
  576. return 1;
  577. }
  578. if (runAsDaemon) {
  579. long p = (long)fork();
  580. if (p < 0) {
  581. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  582. return 1;
  583. } else if (p > 0)
  584. return 0; // forked
  585. // else p == 0, so we are daemonized
  586. }
  587. mkdir(homeDir,0755); // will fail if it already exists, but that's fine
  588. {
  589. // Write .pid file to home folder
  590. char pidpath[4096];
  591. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  592. FILE *pf = fopen(pidpath,"w");
  593. if (pf) {
  594. fprintf(pf,"%ld",(long)getpid());
  595. fclose(pf);
  596. }
  597. }
  598. #endif
  599. #ifdef __WINDOWS__
  600. if (winRunFromCommandLine) {
  601. // Running in "interactive" mode (mostly for debugging)
  602. if (IsCurrentUserLocalAdministrator() != TRUE) {
  603. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  604. return 1;
  605. }
  606. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  607. // continues on to ordinary command line execution code below...
  608. } else {
  609. // Running from service manager
  610. ZeroTierOneService zt1Service;
  611. if (CServiceBase::Run(zt1Service) == TRUE) {
  612. return 0;
  613. } else {
  614. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  615. return 1;
  616. }
  617. }
  618. #endif
  619. int exitCode = 0;
  620. try {
  621. node = new Node(homeDir,port,controlPort);
  622. switch(node->run()) {
  623. #ifdef __WINDOWS__
  624. case Node::NODE_RESTART_FOR_UPGRADE: {
  625. const char *upgPath = node->reasonForTermination();
  626. if (upgPath) {
  627. if (!ZeroTierOneService::doStartUpgrade(std::string(upgPath))) {
  628. exitCode = 3;
  629. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (doStartUpgrade failed)\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  630. }
  631. } else {
  632. exitCode = 3;
  633. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (no upgrade path provided)\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  634. }
  635. } break;
  636. #else // __UNIX_LIKE__
  637. case Node::NODE_RESTART_FOR_UPGRADE: {
  638. const char *upgPath = node->reasonForTermination();
  639. // On Unix-type OSes we exec() right into the upgrade. This in turn will
  640. // end with us being re-launched either via the upgrade itself or something
  641. // like OSX's launchd.
  642. if (upgPath) {
  643. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  644. ::execl(upgPath,upgPath,(char *)0);
  645. }
  646. exitCode = 3;
  647. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  648. } break;
  649. #endif
  650. case Node::NODE_UNRECOVERABLE_ERROR: {
  651. exitCode = 3;
  652. const char *termReason = node->reasonForTermination();
  653. fprintf(stderr,"%s: abnormal termination: %s\n",argv[0],(termReason) ? termReason : "(unknown reason)");
  654. } break;
  655. default:
  656. break;
  657. }
  658. delete node;
  659. node = (Node *)0;
  660. } catch ( ... ) {
  661. fprintf(stderr,"%s: unexpected exception!"ZT_EOL_S,argv[0]);
  662. exitCode = 3;
  663. }
  664. #ifdef __UNIX_LIKE__
  665. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  666. #endif
  667. return exitCode;
  668. }