main.cpp 25 KB

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