main.cpp 27 KB

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