main.cpp 21 KB

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