main.cpp 25 KB

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