main.cpp 28 KB

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