main.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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/C25519.hpp"
  58. #include "node/Identity.hpp"
  59. #include "node/Thread.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. #ifdef __UNIX_LIKE__
  90. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  91. #endif
  92. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  93. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  94. #ifdef __WINDOWS__
  95. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  96. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  97. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  98. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  99. #endif
  100. }
  101. namespace ZeroTierCLI { // ---------------------------------------------------
  102. static void printHelp(FILE *out,const char *cn)
  103. {
  104. fprintf(out,"Usage: %s <command> (use 'help' for help)"ZT_EOL_S,cn);
  105. }
  106. static void _CBresultHandler(void *arg,const char *line)
  107. {
  108. if (line) {
  109. if ((line[0] == '.')&&(line[1] == (char)0))
  110. *((bool *)arg) = true;
  111. else fprintf(stdout,"%s"ZT_EOL_S,line);
  112. }
  113. }
  114. #ifdef __WINDOWS__
  115. static int main(int argc,_TCHAR* argv[])
  116. #else
  117. static int main(int argc,char **argv)
  118. #endif
  119. {
  120. if (argc < 2) {
  121. printHelp(stdout,argv[0]);
  122. return 1;
  123. }
  124. const char *hp = (const char *)0;
  125. std::string query;
  126. for(int i=1;i<argc;++i) {
  127. if (argv[i][0] == '-') {
  128. switch(argv[i][1]) {
  129. case 'q': // ignore -q since it's used to invoke this
  130. break;
  131. case 'h':
  132. default:
  133. printHelp(stdout,argv[0]);
  134. return 1;
  135. }
  136. } else {
  137. if (query.length())
  138. query.push_back(' ');
  139. query.append(argv[i]);
  140. }
  141. }
  142. if (!query.length()) {
  143. printHelp(stdout,argv[0]);
  144. return 1;
  145. }
  146. try {
  147. volatile bool done = false;
  148. Node::NodeControlClient client(hp,&_CBresultHandler,(void *)&done);
  149. if (client.error()) {
  150. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?)"ZT_EOL_S,argv[0]);
  151. return 1;
  152. }
  153. client.send(query.c_str());
  154. while (!done)
  155. Thread::sleep(100); // ghetto
  156. } catch ( ... ) {
  157. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?)"ZT_EOL_S,argv[0]);
  158. return 1;
  159. }
  160. return 0;
  161. }
  162. } // namespace ZeroTierCLI ---------------------------------------------------
  163. namespace ZeroTierIdTool { // ------------------------------------------------
  164. static void printHelp(FILE *out,const char *pn)
  165. {
  166. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  167. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  168. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  169. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  170. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  171. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  172. }
  173. static Identity getIdFromArg(char *arg)
  174. {
  175. Identity id;
  176. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  177. if (id.fromString(arg))
  178. return id;
  179. } else { // identity is to be read from a file
  180. std::string idser;
  181. if (Utils::readFile(arg,idser)) {
  182. if (id.fromString(idser))
  183. return id;
  184. }
  185. }
  186. return Identity();
  187. }
  188. #ifdef __WINDOWS__
  189. static int main(int argc,_TCHAR* argv[])
  190. #else
  191. static int main(int argc,char **argv)
  192. #endif
  193. {
  194. if (argc < 2) {
  195. printHelp(stdout,argv[0]);
  196. return 1;
  197. }
  198. if (!strcmp(argv[1],"generate")) {
  199. Identity id;
  200. id.generate();
  201. std::string idser = id.toString(true);
  202. if (argc >= 3) {
  203. if (!Utils::writeFile(argv[2],idser)) {
  204. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  205. return 1;
  206. } else printf("%s written"ZT_EOL_S,argv[2]);
  207. if (argc >= 4) {
  208. idser = id.toString(false);
  209. if (!Utils::writeFile(argv[3],idser)) {
  210. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  211. return 1;
  212. } else printf("%s written"ZT_EOL_S,argv[3]);
  213. }
  214. } else printf("%s",idser.c_str());
  215. } else if (!strcmp(argv[1],"validate")) {
  216. if (argc < 3) {
  217. printHelp(stdout,argv[0]);
  218. return 1;
  219. }
  220. Identity id = getIdFromArg(argv[2]);
  221. if (!id) {
  222. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  223. return 1;
  224. }
  225. if (!id.locallyValidate()) {
  226. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  227. return 1;
  228. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  229. } else if (!strcmp(argv[1],"getpublic")) {
  230. if (argc < 3) {
  231. printHelp(stdout,argv[0]);
  232. return 1;
  233. }
  234. Identity id = getIdFromArg(argv[2]);
  235. if (!id) {
  236. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  237. return 1;
  238. }
  239. printf("%s",id.toString(false).c_str());
  240. } else if (!strcmp(argv[1],"sign")) {
  241. if (argc < 4) {
  242. printHelp(stdout,argv[0]);
  243. return 1;
  244. }
  245. Identity id = getIdFromArg(argv[2]);
  246. if (!id) {
  247. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  248. return 1;
  249. }
  250. if (!id.hasPrivate()) {
  251. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  252. return 1;
  253. }
  254. std::string inf;
  255. if (!Utils::readFile(argv[3],inf)) {
  256. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  257. return 1;
  258. }
  259. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  260. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  261. } else if (!strcmp(argv[1],"verify")) {
  262. if (argc < 4) {
  263. printHelp(stdout,argv[0]);
  264. return 1;
  265. }
  266. Identity id = getIdFromArg(argv[2]);
  267. if (!id) {
  268. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  269. return 1;
  270. }
  271. std::string inf;
  272. if (!Utils::readFile(argv[3],inf)) {
  273. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  274. return 1;
  275. }
  276. std::string signature(Utils::unhex(argv[4]));
  277. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  278. printf("%s signature valid"ZT_EOL_S,argv[3]);
  279. } else {
  280. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  281. return 1;
  282. }
  283. } else {
  284. printHelp(stdout,argv[0]);
  285. return 1;
  286. }
  287. return 0;
  288. }
  289. } // namespace ZeroTierIdTool ------------------------------------------------
  290. #ifdef __UNIX_LIKE__
  291. static void sighandlerHup(int sig)
  292. {
  293. Node *n = node;
  294. if (n)
  295. n->resync();
  296. }
  297. static void sighandlerQuit(int sig)
  298. {
  299. Node *n = node;
  300. if (n)
  301. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  302. else exit(0);
  303. }
  304. #endif
  305. #ifdef __WINDOWS__
  306. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  307. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  308. {
  309. switch(dwCtrlType) {
  310. case CTRL_C_EVENT:
  311. case CTRL_BREAK_EVENT:
  312. case CTRL_CLOSE_EVENT:
  313. case CTRL_SHUTDOWN_EVENT:
  314. Node *n = node;
  315. if (n)
  316. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  317. return TRUE;
  318. }
  319. return FALSE;
  320. }
  321. // Returns true if this is running as the local administrator
  322. static BOOL IsCurrentUserLocalAdministrator(void)
  323. {
  324. BOOL fReturn = FALSE;
  325. DWORD dwStatus;
  326. DWORD dwAccessMask;
  327. DWORD dwAccessDesired;
  328. DWORD dwACLSize;
  329. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  330. PACL pACL = NULL;
  331. PSID psidAdmin = NULL;
  332. HANDLE hToken = NULL;
  333. HANDLE hImpersonationToken = NULL;
  334. PRIVILEGE_SET ps;
  335. GENERIC_MAPPING GenericMapping;
  336. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  337. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  338. const DWORD ACCESS_READ = 1;
  339. const DWORD ACCESS_WRITE = 2;
  340. __try
  341. {
  342. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  343. {
  344. if (GetLastError() != ERROR_NO_TOKEN)
  345. __leave;
  346. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  347. __leave;
  348. }
  349. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  350. __leave;
  351. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  352. SECURITY_BUILTIN_DOMAIN_RID,
  353. DOMAIN_ALIAS_RID_ADMINS,
  354. 0, 0, 0, 0, 0, 0, &psidAdmin))
  355. __leave;
  356. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  357. if (psdAdmin == NULL)
  358. __leave;
  359. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  360. __leave;
  361. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  362. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  363. if (pACL == NULL)
  364. __leave;
  365. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  366. __leave;
  367. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  368. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  369. __leave;
  370. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  371. __leave;
  372. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  373. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  374. if (!IsValidSecurityDescriptor(psdAdmin))
  375. __leave;
  376. dwAccessDesired = ACCESS_READ;
  377. GenericMapping.GenericRead = ACCESS_READ;
  378. GenericMapping.GenericWrite = ACCESS_WRITE;
  379. GenericMapping.GenericExecute = 0;
  380. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  381. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  382. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  383. &fReturn))
  384. {
  385. fReturn = FALSE;
  386. __leave;
  387. }
  388. }
  389. __finally
  390. {
  391. // Clean up.
  392. if (pACL) LocalFree(pACL);
  393. if (psdAdmin) LocalFree(psdAdmin);
  394. if (psidAdmin) FreeSid(psidAdmin);
  395. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  396. if (hToken) CloseHandle (hToken);
  397. }
  398. return fReturn;
  399. }
  400. #endif // __WINDOWS__
  401. #ifdef __WINDOWS__
  402. int _tmain(int argc, _TCHAR* argv[])
  403. #else
  404. int main(int argc,char **argv)
  405. #endif
  406. {
  407. #ifdef __UNIX_LIKE__
  408. signal(SIGHUP,&sighandlerHup);
  409. signal(SIGPIPE,SIG_IGN);
  410. signal(SIGUSR1,SIG_IGN);
  411. signal(SIGUSR2,SIG_IGN);
  412. signal(SIGALRM,SIG_IGN);
  413. signal(SIGINT,&sighandlerQuit);
  414. signal(SIGTERM,&sighandlerQuit);
  415. signal(SIGQUIT,&sighandlerQuit);
  416. #endif
  417. #ifdef __WINDOWS__
  418. WSADATA wsaData;
  419. WSAStartup(MAKEWORD(2,2),&wsaData);
  420. #endif
  421. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  422. return ZeroTierCLI::main(argc,argv);
  423. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  424. return ZeroTierIdTool::main(argc,argv);
  425. const char *homeDir = (const char *)0;
  426. unsigned int port = 0;
  427. #ifdef __UNIX_LIKE__
  428. bool runAsDaemon = false;
  429. #endif
  430. #ifdef __WINDOWS__
  431. bool winRunFromCommandLine = false;
  432. #endif
  433. for(int i=1;i<argc;++i) {
  434. if (argv[i][0] == '-') {
  435. switch(argv[i][1]) {
  436. case 'p':
  437. port = Utils::strToUInt(argv[i] + 2);
  438. if (port > 65535) {
  439. printHelp(argv[0],stdout);
  440. return 1;
  441. }
  442. break;
  443. #ifdef __UNIX_LIKE__
  444. case 'd':
  445. runAsDaemon = true;
  446. break;
  447. #endif
  448. case 'v':
  449. printf("%s"ZT_EOL_S,Node::versionString());
  450. return 0;
  451. case 'q':
  452. if (argv[i][2]) {
  453. printHelp(argv[0],stdout);
  454. return 0;
  455. } else return ZeroTierCLI::main(argc,argv);
  456. case 'i':
  457. if (argv[i][2]) {
  458. printHelp(argv[0],stdout);
  459. return 0;
  460. } else return ZeroTierIdTool::main(argc,argv);
  461. #ifdef __WINDOWS__
  462. case 'C':
  463. winRunFromCommandLine = true;
  464. break;
  465. case 'I': { // install self as service
  466. if (IsCurrentUserLocalAdministrator() != TRUE) {
  467. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  468. return 1;
  469. }
  470. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  471. if (ret.length()) {
  472. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  473. return 3;
  474. }
  475. return 0;
  476. } break;
  477. case 'R': { // uninstall self as service
  478. if (IsCurrentUserLocalAdministrator() != TRUE) {
  479. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  480. return 1;
  481. }
  482. std::string ret(UninstallService(ZT_SERVICE_NAME));
  483. if (ret.length()) {
  484. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  485. return 3;
  486. }
  487. return 0;
  488. } break;
  489. case 'D': { // install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
  490. std::string pathToInf;
  491. #ifdef _WIN64
  492. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
  493. #else
  494. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
  495. #endif
  496. printf("Installing ZeroTier One virtual Ethernet port driver."ZT_EOL_S""ZT_EOL_S"NOTE: If you don't see a confirmation window to allow driver installation,"ZT_EOL_S"check to make sure it didn't appear under the installer."ZT_EOL_S);
  497. BOOL needReboot = FALSE;
  498. if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
  499. printf("%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
  500. return 0;
  501. } else {
  502. printf("%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
  503. return 3;
  504. }
  505. } break;
  506. #endif // __WINDOWS__
  507. case 'h':
  508. case '?':
  509. default:
  510. printHelp(argv[0],stdout);
  511. return 0;
  512. }
  513. } else {
  514. if (homeDir) {
  515. printHelp(argv[0],stdout);
  516. return 0;
  517. }
  518. homeDir = argv[i];
  519. break;
  520. }
  521. }
  522. if ((!homeDir)||(strlen(homeDir) == 0))
  523. homeDir = ZT_DEFAULTS.defaultHomePath.c_str();
  524. #ifdef __UNIX_LIKE__
  525. if (getuid() != 0) {
  526. fprintf(stderr,"%s: must be run as root (uid 0)\n",argv[0]);
  527. return 1;
  528. }
  529. if (runAsDaemon) {
  530. long p = (long)fork();
  531. if (p < 0) {
  532. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  533. return 1;
  534. } else if (p > 0)
  535. return 0; // forked
  536. // else p == 0, so we are daemonized
  537. }
  538. mkdir(homeDir,0755); // will fail if it already exists, but that's fine
  539. {
  540. // Write .pid file to home folder
  541. char pidpath[4096];
  542. Utils::snprintf(pidpath,sizeof(pidpath),"%s/zerotier-one.pid",homeDir);
  543. FILE *pf = fopen(pidpath,"w");
  544. if (pf) {
  545. fprintf(pf,"%ld",(long)getpid());
  546. fclose(pf);
  547. }
  548. }
  549. #endif
  550. #ifdef __WINDOWS__
  551. if (winRunFromCommandLine) {
  552. // Running in "interactive" mode (mostly for debugging)
  553. if (IsCurrentUserLocalAdministrator() != TRUE) {
  554. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  555. return 1;
  556. }
  557. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  558. // continues on to ordinary command line execution code below...
  559. } else {
  560. // Running from service manager
  561. ZeroTierOneService zt1Service;
  562. if (CServiceBase::Run(zt1Service) == TRUE) {
  563. return 0;
  564. } else {
  565. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  566. return 1;
  567. }
  568. }
  569. #endif
  570. int exitCode = 0;
  571. bool needsReset = false;
  572. try {
  573. node = new Node(homeDir,port,port,needsReset);
  574. switch(node->run()) {
  575. #ifdef __WINDOWS__
  576. case Node::NODE_RESTART_FOR_UPGRADE: {
  577. const char *upgPath = node->reasonForTermination();
  578. if (upgPath) {
  579. if (!ZeroTierOneService::doStartUpgrade(std::string(upgPath))) {
  580. exitCode = 3;
  581. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (doStartUpgrade failed)\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  582. }
  583. } else {
  584. exitCode = 3;
  585. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s (no upgrade path provided)\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  586. }
  587. } break;
  588. #else // __UNIX_LIKE__
  589. case Node::NODE_RESTART_FOR_UPGRADE: {
  590. const char *upgPath = node->reasonForTermination();
  591. // On Unix-type OSes we exec() right into the upgrade. This in turn will
  592. // end with us being re-launched either via the upgrade itself or something
  593. // like OSX's launchd.
  594. if (upgPath) {
  595. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  596. ::execl(upgPath,upgPath,(char *)0);
  597. }
  598. exitCode = 3;
  599. fprintf(stderr,"%s: abnormal termination: unable to execute update at %s\n",argv[0],(upgPath) ? upgPath : "(unknown path)");
  600. } break;
  601. #endif
  602. case Node::NODE_UNRECOVERABLE_ERROR: {
  603. exitCode = 3;
  604. const char *termReason = node->reasonForTermination();
  605. fprintf(stderr,"%s: abnormal termination: %s\n",argv[0],(termReason) ? termReason : "(unknown reason)");
  606. } break;
  607. default:
  608. break;
  609. }
  610. delete node;
  611. node = (Node *)0;
  612. } catch ( ... ) {
  613. fprintf(stderr,"%s: unexpected exception!"ZT_EOL_S,argv[0]);
  614. exitCode = 3;
  615. }
  616. #ifdef __UNIX_LIKE__
  617. Utils::rm((std::string(homeDir)+"/zerotier-one.pid").c_str());
  618. #endif
  619. return exitCode;
  620. }