main.cpp 19 KB

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