main.cpp 20 KB

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