main.cpp 28 KB

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