main.cpp 23 KB

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