main.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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. static void printHelp(const char *cn,FILE *out)
  88. {
  89. 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());
  90. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  91. #ifdef ZT_AUTO_UPDATE
  92. fprintf(out,"Auto-update enabled build, will update from URL:"ZT_EOL_S);
  93. fprintf(out," %s"ZT_EOL_S,ZT_DEFAULTS.updateLatestNfoURL.c_str());
  94. fprintf(out,"Update authentication signing authorities: "ZT_EOL_S);
  95. int no = 0;
  96. for(std::map< Address,Identity >::const_iterator sa(ZT_DEFAULTS.updateAuthorities.begin());sa!=ZT_DEFAULTS.updateAuthorities.end();++sa) {
  97. if (no == 0)
  98. fprintf(out," %s",sa->first.toString().c_str());
  99. else fprintf(out,", %s",sa->first.toString().c_str());
  100. if (++no == 6) {
  101. fprintf(out,ZT_EOL_S);
  102. no = 0;
  103. }
  104. }
  105. fprintf(out,ZT_EOL_S""ZT_EOL_S);
  106. #else
  107. fprintf(out,"Auto-updates not enabled on this build. You must update manually."ZT_EOL_S""ZT_EOL_S);
  108. #endif
  109. fprintf(out,"Usage: %s [-switches] [home directory]"ZT_EOL_S""ZT_EOL_S,cn);
  110. fprintf(out,"Available switches:"ZT_EOL_S);
  111. fprintf(out," -h - Display this help"ZT_EOL_S);
  112. fprintf(out," -v - Show version"ZT_EOL_S);
  113. fprintf(out," -p<port> - Port for UDP (default: 9993)"ZT_EOL_S);
  114. fprintf(out," -t<port> - Port for TCP (default: disabled)"ZT_EOL_S);
  115. #ifdef __UNIX_LIKE__
  116. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  117. #endif
  118. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  119. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  120. #ifdef __WINDOWS__
  121. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  122. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  123. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  124. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  125. #endif
  126. }
  127. namespace ZeroTierCLI { // ---------------------------------------------------
  128. static void printHelp(FILE *out,const char *cn)
  129. {
  130. fprintf(out,"Usage: %s <command> (use 'help' for help)"ZT_EOL_S,cn);
  131. }
  132. static void _CBresultHandler(void *arg,const char *line)
  133. {
  134. if (line) {
  135. if ((line[0] == '.')&&(line[1] == (char)0))
  136. *((bool *)arg) = true;
  137. else fprintf(stdout,"%s"ZT_EOL_S,line);
  138. }
  139. }
  140. #ifdef __WINDOWS__
  141. static int main(int argc,_TCHAR* argv[])
  142. #else
  143. static int main(int argc,char **argv)
  144. #endif
  145. {
  146. if (argc < 2) {
  147. printHelp(stdout,argv[0]);
  148. return 1;
  149. }
  150. const char *hp = (const char *)0;
  151. std::string query;
  152. for(int i=1;i<argc;++i) {
  153. if (argv[i][0] == '-') {
  154. switch(argv[i][1]) {
  155. case 'q': // ignore -q since it's used to invoke this
  156. break;
  157. case 'h':
  158. default:
  159. printHelp(stdout,argv[0]);
  160. return 1;
  161. }
  162. } else {
  163. if (query.length())
  164. query.push_back(' ');
  165. query.append(argv[i]);
  166. }
  167. }
  168. if (!query.length()) {
  169. printHelp(stdout,argv[0]);
  170. return 1;
  171. }
  172. try {
  173. volatile bool done = false;
  174. Node::NodeControlClient client(hp,&_CBresultHandler,(void *)&done);
  175. const char *err = client.error();
  176. if (err) {
  177. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?) (%s)"ZT_EOL_S,argv[0],err);
  178. return 1;
  179. }
  180. client.send(query.c_str());
  181. while (!done)
  182. Thread::sleep(100); // ghetto
  183. } catch ( ... ) {
  184. fprintf(stderr,"%s: fatal error: unable to connect (is ZeroTier One running?)"ZT_EOL_S,argv[0]);
  185. return 1;
  186. }
  187. return 0;
  188. }
  189. } // namespace ZeroTierCLI ---------------------------------------------------
  190. namespace ZeroTierIdTool { // ------------------------------------------------
  191. static void printHelp(FILE *out,const char *pn)
  192. {
  193. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  194. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  195. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  196. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  197. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  198. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  199. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
  200. }
  201. static Identity getIdFromArg(char *arg)
  202. {
  203. Identity id;
  204. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  205. if (id.fromString(arg))
  206. return id;
  207. } else { // identity is to be read from a file
  208. std::string idser;
  209. if (Utils::readFile(arg,idser)) {
  210. if (id.fromString(idser))
  211. return id;
  212. }
  213. }
  214. return Identity();
  215. }
  216. #ifdef __WINDOWS__
  217. static int main(int argc,_TCHAR* argv[])
  218. #else
  219. static int main(int argc,char **argv)
  220. #endif
  221. {
  222. if (argc < 2) {
  223. printHelp(stdout,argv[0]);
  224. return 1;
  225. }
  226. if (!strcmp(argv[1],"generate")) {
  227. Identity id;
  228. id.generate();
  229. std::string idser = id.toString(true);
  230. if (argc >= 3) {
  231. if (!Utils::writeFile(argv[2],idser)) {
  232. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  233. return 1;
  234. } else printf("%s written"ZT_EOL_S,argv[2]);
  235. if (argc >= 4) {
  236. idser = id.toString(false);
  237. if (!Utils::writeFile(argv[3],idser)) {
  238. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  239. return 1;
  240. } else printf("%s written"ZT_EOL_S,argv[3]);
  241. }
  242. } else printf("%s",idser.c_str());
  243. } else if (!strcmp(argv[1],"validate")) {
  244. if (argc < 3) {
  245. printHelp(stdout,argv[0]);
  246. return 1;
  247. }
  248. Identity id = getIdFromArg(argv[2]);
  249. if (!id) {
  250. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  251. return 1;
  252. }
  253. if (!id.locallyValidate()) {
  254. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  255. return 1;
  256. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  257. } else if (!strcmp(argv[1],"getpublic")) {
  258. if (argc < 3) {
  259. printHelp(stdout,argv[0]);
  260. return 1;
  261. }
  262. Identity id = getIdFromArg(argv[2]);
  263. if (!id) {
  264. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  265. return 1;
  266. }
  267. printf("%s",id.toString(false).c_str());
  268. } else if (!strcmp(argv[1],"sign")) {
  269. if (argc < 4) {
  270. printHelp(stdout,argv[0]);
  271. return 1;
  272. }
  273. Identity id = getIdFromArg(argv[2]);
  274. if (!id) {
  275. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  276. return 1;
  277. }
  278. if (!id.hasPrivate()) {
  279. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  280. return 1;
  281. }
  282. std::string inf;
  283. if (!Utils::readFile(argv[3],inf)) {
  284. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  285. return 1;
  286. }
  287. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  288. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  289. } else if (!strcmp(argv[1],"verify")) {
  290. if (argc < 4) {
  291. printHelp(stdout,argv[0]);
  292. return 1;
  293. }
  294. Identity id = getIdFromArg(argv[2]);
  295. if (!id) {
  296. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  297. return 1;
  298. }
  299. std::string inf;
  300. if (!Utils::readFile(argv[3],inf)) {
  301. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  302. return 1;
  303. }
  304. std::string signature(Utils::unhex(argv[4]));
  305. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  306. printf("%s signature valid"ZT_EOL_S,argv[3]);
  307. } else {
  308. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  309. return 1;
  310. }
  311. } else if (!strcmp(argv[1],"mkcom")) {
  312. if (argc < 3) {
  313. printHelp(stdout,argv[0]);
  314. return 1;
  315. }
  316. Identity id = getIdFromArg(argv[2]);
  317. if ((!id)||(!id.hasPrivate())) {
  318. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
  319. return 1;
  320. }
  321. CertificateOfMembership com;
  322. for(int a=3;a<argc;++a) {
  323. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  324. if (params.size() == 3) {
  325. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  326. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  327. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  328. com.setQualifier(qId,qValue,qMaxDelta);
  329. }
  330. }
  331. if (!com.sign(id)) {
  332. fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
  333. return 1;
  334. }
  335. printf("%s",com.toString().c_str());
  336. } else {
  337. printHelp(stdout,argv[0]);
  338. return 1;
  339. }
  340. return 0;
  341. }
  342. } // namespace ZeroTierIdTool ------------------------------------------------
  343. #ifdef __UNIX_LIKE__
  344. static void sighandlerHup(int sig)
  345. {
  346. Node *n = node;
  347. if (n)
  348. n->resync();
  349. }
  350. static void sighandlerQuit(int sig)
  351. {
  352. Node *n = node;
  353. if (n)
  354. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  355. else exit(0);
  356. }
  357. #endif
  358. #ifdef __WINDOWS__
  359. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  360. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  361. {
  362. switch(dwCtrlType) {
  363. case CTRL_C_EVENT:
  364. case CTRL_BREAK_EVENT:
  365. case CTRL_CLOSE_EVENT:
  366. case CTRL_SHUTDOWN_EVENT:
  367. Node *n = node;
  368. if (n)
  369. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  370. return TRUE;
  371. }
  372. return FALSE;
  373. }
  374. // Pokes a hole in the Windows firewall (advfirewall) for the running program
  375. static void _winPokeAHole()
  376. {
  377. char myPath[MAX_PATH];
  378. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  379. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  380. STARTUPINFOA startupInfo;
  381. PROCESS_INFORMATION processInfo;
  382. startupInfo.cb = sizeof(startupInfo);
  383. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  384. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  385. 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)) {
  386. WaitForSingleObject(processInfo.hProcess,INFINITE);
  387. CloseHandle(processInfo.hProcess);
  388. CloseHandle(processInfo.hThread);
  389. }
  390. startupInfo.cb = sizeof(startupInfo);
  391. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  392. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  393. 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)) {
  394. WaitForSingleObject(processInfo.hProcess,INFINITE);
  395. CloseHandle(processInfo.hProcess);
  396. CloseHandle(processInfo.hThread);
  397. }
  398. startupInfo.cb = sizeof(startupInfo);
  399. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  400. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  401. 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)) {
  402. WaitForSingleObject(processInfo.hProcess,INFINITE);
  403. CloseHandle(processInfo.hProcess);
  404. CloseHandle(processInfo.hThread);
  405. }
  406. }
  407. }
  408. // Returns true if this is running as the local administrator
  409. static BOOL IsCurrentUserLocalAdministrator(void)
  410. {
  411. BOOL fReturn = FALSE;
  412. DWORD dwStatus;
  413. DWORD dwAccessMask;
  414. DWORD dwAccessDesired;
  415. DWORD dwACLSize;
  416. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  417. PACL pACL = NULL;
  418. PSID psidAdmin = NULL;
  419. HANDLE hToken = NULL;
  420. HANDLE hImpersonationToken = NULL;
  421. PRIVILEGE_SET ps;
  422. GENERIC_MAPPING GenericMapping;
  423. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  424. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  425. const DWORD ACCESS_READ = 1;
  426. const DWORD ACCESS_WRITE = 2;
  427. __try
  428. {
  429. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  430. {
  431. if (GetLastError() != ERROR_NO_TOKEN)
  432. __leave;
  433. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  434. __leave;
  435. }
  436. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  437. __leave;
  438. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  439. SECURITY_BUILTIN_DOMAIN_RID,
  440. DOMAIN_ALIAS_RID_ADMINS,
  441. 0, 0, 0, 0, 0, 0, &psidAdmin))
  442. __leave;
  443. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  444. if (psdAdmin == NULL)
  445. __leave;
  446. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  447. __leave;
  448. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  449. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  450. if (pACL == NULL)
  451. __leave;
  452. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  453. __leave;
  454. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  455. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  456. __leave;
  457. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  458. __leave;
  459. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  460. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  461. if (!IsValidSecurityDescriptor(psdAdmin))
  462. __leave;
  463. dwAccessDesired = ACCESS_READ;
  464. GenericMapping.GenericRead = ACCESS_READ;
  465. GenericMapping.GenericWrite = ACCESS_WRITE;
  466. GenericMapping.GenericExecute = 0;
  467. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  468. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  469. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  470. &fReturn))
  471. {
  472. fReturn = FALSE;
  473. __leave;
  474. }
  475. }
  476. __finally
  477. {
  478. // Clean up.
  479. if (pACL) LocalFree(pACL);
  480. if (psdAdmin) LocalFree(psdAdmin);
  481. if (psidAdmin) FreeSid(psidAdmin);
  482. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  483. if (hToken) CloseHandle (hToken);
  484. }
  485. return fReturn;
  486. }
  487. #endif // __WINDOWS__
  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(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(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. }