main.cpp 19 KB

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