main.cpp 25 KB

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