main.cpp 20 KB

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