2
0

main.cpp 20 KB

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