main.cpp 19 KB

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