main.cpp 28 KB

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