main.cpp 19 KB

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