one.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <time.h>
  32. #include <errno.h>
  33. #ifdef __WINDOWS__
  34. #include <WinSock2.h>
  35. #include <Windows.h>
  36. #include <tchar.h>
  37. #include <wchar.h>
  38. #include <lmcons.h>
  39. #include <newdev.h>
  40. #include <atlbase.h>
  41. #include "windows/ZeroTierOne/ServiceInstaller.h"
  42. #include "windows/ZeroTierOne/ServiceBase.h"
  43. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  44. #else
  45. #include <unistd.h>
  46. #include <pwd.h>
  47. #include <fcntl.h>
  48. #include <sys/types.h>
  49. #include <sys/stat.h>
  50. #include <signal.h>
  51. #endif
  52. #include <string>
  53. #include <stdexcept>
  54. #include "version.h"
  55. #include "include/ZeroTierOne.h"
  56. #include "node/Constants.hpp"
  57. #include "node/Identity.hpp"
  58. #include "node/CertificateOfMembership.hpp"
  59. #include "node/Utils.hpp"
  60. #include "node/NetworkController.hpp"
  61. #include "osdep/OSUtils.hpp"
  62. #include "service/OneService.hpp"
  63. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  64. #include "controller/SqliteNetworkController.hpp"
  65. #endif
  66. #define ZT1_PID_PATH "zerotier-one.pid"
  67. #define ZT1_CONTROLLER_DB_PATH "controller.db"
  68. using namespace ZeroTier;
  69. static OneService *volatile zt1Service = (OneService *)0;
  70. /****************************************************************************/
  71. /* zerotier-cli personality */
  72. /****************************************************************************/
  73. #ifdef __WINDOWS__
  74. int cli(int argc, _TCHAR* argv[])
  75. #else
  76. int cli(int argc,char **argv)
  77. #endif
  78. {
  79. }
  80. /****************************************************************************/
  81. /* zerotier-idtool personality */
  82. /****************************************************************************/
  83. static void idtoolPrintHelp(FILE *out,const char *pn)
  84. {
  85. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  86. fprintf(out," generate [<identity.secret>] [<identity.public>]"ZT_EOL_S);
  87. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  88. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  89. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  90. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  91. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
  92. }
  93. static Identity getIdFromArg(char *arg)
  94. {
  95. Identity id;
  96. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  97. if (id.fromString(arg))
  98. return id;
  99. } else { // identity is to be read from a file
  100. std::string idser;
  101. if (OSUtils::readFile(arg,idser)) {
  102. if (id.fromString(idser))
  103. return id;
  104. }
  105. }
  106. return Identity();
  107. }
  108. #ifdef __WINDOWS__
  109. int idtool(int argc, _TCHAR* argv[])
  110. #else
  111. int idtool(int argc,char **argv)
  112. #endif
  113. {
  114. if (argc < 2) {
  115. idtoolPrintHelp(stdout,argv[0]);
  116. return 1;
  117. }
  118. if (!strcmp(argv[1],"generate")) {
  119. Identity id;
  120. id.generate();
  121. std::string idser = id.toString(true);
  122. if (argc >= 3) {
  123. if (!OSUtils::writeFile(argv[2],idser)) {
  124. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  125. return 1;
  126. } else printf("%s written"ZT_EOL_S,argv[2]);
  127. if (argc >= 4) {
  128. idser = id.toString(false);
  129. if (!OSUtils::writeFile(argv[3],idser)) {
  130. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  131. return 1;
  132. } else printf("%s written"ZT_EOL_S,argv[3]);
  133. }
  134. } else printf("%s",idser.c_str());
  135. } else if (!strcmp(argv[1],"validate")) {
  136. if (argc < 3) {
  137. idtoolPrintHelp(stdout,argv[0]);
  138. return 1;
  139. }
  140. Identity id = getIdFromArg(argv[2]);
  141. if (!id) {
  142. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  143. return 1;
  144. }
  145. if (!id.locallyValidate()) {
  146. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  147. return 1;
  148. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  149. } else if (!strcmp(argv[1],"getpublic")) {
  150. if (argc < 3) {
  151. idtoolPrintHelp(stdout,argv[0]);
  152. return 1;
  153. }
  154. Identity id = getIdFromArg(argv[2]);
  155. if (!id) {
  156. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  157. return 1;
  158. }
  159. printf("%s",id.toString(false).c_str());
  160. } else if (!strcmp(argv[1],"sign")) {
  161. if (argc < 4) {
  162. idtoolPrintHelp(stdout,argv[0]);
  163. return 1;
  164. }
  165. Identity id = getIdFromArg(argv[2]);
  166. if (!id) {
  167. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  168. return 1;
  169. }
  170. if (!id.hasPrivate()) {
  171. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  172. return 1;
  173. }
  174. std::string inf;
  175. if (!OSUtils::readFile(argv[3],inf)) {
  176. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  177. return 1;
  178. }
  179. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  180. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  181. } else if (!strcmp(argv[1],"verify")) {
  182. if (argc < 4) {
  183. idtoolPrintHelp(stdout,argv[0]);
  184. return 1;
  185. }
  186. Identity id = getIdFromArg(argv[2]);
  187. if (!id) {
  188. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  189. return 1;
  190. }
  191. std::string inf;
  192. if (!OSUtils::readFile(argv[3],inf)) {
  193. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  194. return 1;
  195. }
  196. std::string signature(Utils::unhex(argv[4]));
  197. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  198. printf("%s signature valid"ZT_EOL_S,argv[3]);
  199. } else {
  200. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  201. return 1;
  202. }
  203. } else if (!strcmp(argv[1],"mkcom")) {
  204. if (argc < 3) {
  205. idtoolPrintHelp(stdout,argv[0]);
  206. return 1;
  207. }
  208. Identity id = getIdFromArg(argv[2]);
  209. if ((!id)||(!id.hasPrivate())) {
  210. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
  211. return 1;
  212. }
  213. CertificateOfMembership com;
  214. for(int a=3;a<argc;++a) {
  215. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  216. if (params.size() == 3) {
  217. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  218. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  219. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  220. com.setQualifier(qId,qValue,qMaxDelta);
  221. }
  222. }
  223. if (!com.sign(id)) {
  224. fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
  225. return 1;
  226. }
  227. printf("%s",com.toString().c_str());
  228. } else {
  229. idtoolPrintHelp(stdout,argv[0]);
  230. return 1;
  231. }
  232. return 0;
  233. }
  234. /****************************************************************************/
  235. /* Unix helper functions and signal handlers */
  236. /****************************************************************************/
  237. #ifdef __UNIX_LIKE__
  238. static void _sighandlerHup(int sig)
  239. {
  240. }
  241. static void _sighandlerQuit(int sig)
  242. {
  243. OneService *s = zt1Service;
  244. if (s)
  245. s->terminate();
  246. else exit(0);
  247. }
  248. #endif
  249. /****************************************************************************/
  250. /* Windows helper functions and signal handlers */
  251. /****************************************************************************/
  252. #ifdef __WINDOWS__
  253. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  254. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  255. {
  256. switch(dwCtrlType) {
  257. case CTRL_C_EVENT:
  258. case CTRL_BREAK_EVENT:
  259. case CTRL_CLOSE_EVENT:
  260. case CTRL_SHUTDOWN_EVENT:
  261. Node *n = node;
  262. if (n)
  263. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  264. return TRUE;
  265. }
  266. return FALSE;
  267. }
  268. // Pokes a hole in the Windows firewall (advfirewall) for the running program
  269. static void _winPokeAHole()
  270. {
  271. char myPath[MAX_PATH];
  272. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  273. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  274. STARTUPINFOA startupInfo;
  275. PROCESS_INFORMATION processInfo;
  276. startupInfo.cb = sizeof(startupInfo);
  277. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  278. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  279. 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)) {
  280. WaitForSingleObject(processInfo.hProcess,INFINITE);
  281. CloseHandle(processInfo.hProcess);
  282. CloseHandle(processInfo.hThread);
  283. }
  284. startupInfo.cb = sizeof(startupInfo);
  285. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  286. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  287. 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)) {
  288. WaitForSingleObject(processInfo.hProcess,INFINITE);
  289. CloseHandle(processInfo.hProcess);
  290. CloseHandle(processInfo.hThread);
  291. }
  292. startupInfo.cb = sizeof(startupInfo);
  293. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  294. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  295. 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)) {
  296. WaitForSingleObject(processInfo.hProcess,INFINITE);
  297. CloseHandle(processInfo.hProcess);
  298. CloseHandle(processInfo.hThread);
  299. }
  300. }
  301. }
  302. // Returns true if this is running as the local administrator
  303. static BOOL IsCurrentUserLocalAdministrator(void)
  304. {
  305. BOOL fReturn = FALSE;
  306. DWORD dwStatus;
  307. DWORD dwAccessMask;
  308. DWORD dwAccessDesired;
  309. DWORD dwACLSize;
  310. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  311. PACL pACL = NULL;
  312. PSID psidAdmin = NULL;
  313. HANDLE hToken = NULL;
  314. HANDLE hImpersonationToken = NULL;
  315. PRIVILEGE_SET ps;
  316. GENERIC_MAPPING GenericMapping;
  317. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  318. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  319. const DWORD ACCESS_READ = 1;
  320. const DWORD ACCESS_WRITE = 2;
  321. __try
  322. {
  323. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  324. {
  325. if (GetLastError() != ERROR_NO_TOKEN)
  326. __leave;
  327. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  328. __leave;
  329. }
  330. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  331. __leave;
  332. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  333. SECURITY_BUILTIN_DOMAIN_RID,
  334. DOMAIN_ALIAS_RID_ADMINS,
  335. 0, 0, 0, 0, 0, 0, &psidAdmin))
  336. __leave;
  337. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  338. if (psdAdmin == NULL)
  339. __leave;
  340. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  341. __leave;
  342. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  343. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  344. if (pACL == NULL)
  345. __leave;
  346. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  347. __leave;
  348. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  349. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  350. __leave;
  351. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  352. __leave;
  353. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  354. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  355. if (!IsValidSecurityDescriptor(psdAdmin))
  356. __leave;
  357. dwAccessDesired = ACCESS_READ;
  358. GenericMapping.GenericRead = ACCESS_READ;
  359. GenericMapping.GenericWrite = ACCESS_WRITE;
  360. GenericMapping.GenericExecute = 0;
  361. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  362. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  363. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  364. &fReturn))
  365. {
  366. fReturn = FALSE;
  367. __leave;
  368. }
  369. }
  370. __finally
  371. {
  372. // Clean up.
  373. if (pACL) LocalFree(pACL);
  374. if (psdAdmin) LocalFree(psdAdmin);
  375. if (psidAdmin) FreeSid(psidAdmin);
  376. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  377. if (hToken) CloseHandle (hToken);
  378. }
  379. return fReturn;
  380. }
  381. #endif // __WINDOWS__
  382. /****************************************************************************/
  383. /* main() and friends */
  384. /****************************************************************************/
  385. static void printHelp(const char *cn,FILE *out)
  386. {
  387. fprintf(out,"ZeroTier One version %d.%d.%d"ZT_EOL_S"(c)2011-2015 ZeroTier, Inc."ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  388. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  389. fprintf(out,"Usage: %s [-switches] [home directory] [-q <query>]"ZT_EOL_S""ZT_EOL_S,cn);
  390. fprintf(out,"Available switches:"ZT_EOL_S);
  391. fprintf(out," -h - Display this help"ZT_EOL_S);
  392. fprintf(out," -v - Show version"ZT_EOL_S);
  393. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993)"ZT_EOL_S);
  394. //fprintf(out," -T<path> - Override root topology, do not authenticate or update"ZT_EOL_S);
  395. #ifdef __UNIX_LIKE__
  396. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  397. #endif // __UNIX_LIKE__
  398. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  399. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  400. #ifdef __WINDOWS__
  401. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  402. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  403. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  404. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  405. #endif // __WINDOWS__
  406. }
  407. #ifdef __WINDOWS__
  408. int _tmain(int argc, _TCHAR* argv[])
  409. #else
  410. int main(int argc,char **argv)
  411. #endif
  412. {
  413. #ifdef __UNIX_LIKE__
  414. signal(SIGHUP,&_sighandlerHup);
  415. signal(SIGPIPE,SIG_IGN);
  416. signal(SIGUSR1,SIG_IGN);
  417. signal(SIGUSR2,SIG_IGN);
  418. signal(SIGALRM,SIG_IGN);
  419. signal(SIGINT,&_sighandlerQuit);
  420. signal(SIGTERM,&_sighandlerQuit);
  421. signal(SIGQUIT,&_sighandlerQuit);
  422. /* Ensure that there are no inherited file descriptors open from a previous
  423. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  424. * of it do not return, and should not do anything otherwise bad. */
  425. {
  426. int mfd = STDIN_FILENO;
  427. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  428. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  429. for(int f=mfd+1;f<1024;++f)
  430. ::close(f);
  431. }
  432. bool runAsDaemon = false;
  433. #endif // __UNIX_LIKE__
  434. #ifdef __WINDOWS__
  435. WSADATA wsaData;
  436. WSAStartup(MAKEWORD(2,2),&wsaData);
  437. #ifdef ZT_WIN_RUN_IN_CONSOLE
  438. bool winRunFromCommandLine = true;
  439. #else
  440. bool winRunFromCommandLine = false;
  441. #endif
  442. #endif // __WINDOWS__
  443. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  444. return cli(argc,argv);
  445. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  446. return idtool(argc,argv);
  447. std::string overrideRootTopology;
  448. std::string homeDir;
  449. unsigned int port = ZT1_DEFAULT_PORT;
  450. for(int i=1;i<argc;++i) {
  451. if (argv[i][0] == '-') {
  452. switch(argv[i][1]) {
  453. case 'p': // port -- for both UDP and TCP, packets and control plane
  454. port = Utils::strToUInt(argv[i] + 2);
  455. if ((port > 0xffff)||(port == 0)) {
  456. printHelp(argv[0],stdout);
  457. return 1;
  458. }
  459. break;
  460. case 't': // TCP port -- ignore, since we now bind to both UDP and TCP on the same port
  461. break;
  462. #ifdef __UNIX_LIKE__
  463. case 'd': // Run in background as daemon
  464. runAsDaemon = true;
  465. break;
  466. #endif // __UNIX_LIKE__
  467. case 'T': // Override root topology
  468. if (argv[i][2]) {
  469. if (!OSUtils::readFile(argv[i] + 2,overrideRootTopology)) {
  470. fprintf(stderr,"%s: cannot read root topology from %s"ZT_EOL_S,argv[0],argv[i] + 2);
  471. return 1;
  472. }
  473. } else {
  474. printHelp(argv[0],stdout);
  475. return 1;
  476. }
  477. break;
  478. case 'v': // Display version
  479. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  480. return 0;
  481. case 'q': // Invoke cli personality
  482. if (argv[i][2]) {
  483. printHelp(argv[0],stdout);
  484. return 0;
  485. } else return cli(argc,argv);
  486. case 'i': // Invoke idtool personality
  487. if (argv[i][2]) {
  488. printHelp(argv[0],stdout);
  489. return 0;
  490. } else return idtool(argc,argv);
  491. #ifdef __WINDOWS__
  492. case 'C': // Run from command line instead of as Windows service
  493. winRunFromCommandLine = true;
  494. break;
  495. case 'I': { // Install this binary as a Windows service
  496. if (IsCurrentUserLocalAdministrator() != TRUE) {
  497. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  498. return 1;
  499. }
  500. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  501. if (ret.length()) {
  502. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  503. return 3;
  504. }
  505. return 0;
  506. } break;
  507. case 'R': { // Uninstall this binary as Windows service
  508. if (IsCurrentUserLocalAdministrator() != TRUE) {
  509. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  510. return 1;
  511. }
  512. std::string ret(UninstallService(ZT_SERVICE_NAME));
  513. if (ret.length()) {
  514. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  515. return 3;
  516. }
  517. return 0;
  518. } break;
  519. #if 0
  520. case 'D': { // Install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
  521. std::string pathToInf;
  522. #ifdef _WIN64
  523. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
  524. #else
  525. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
  526. #endif
  527. 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);
  528. BOOL needReboot = FALSE;
  529. if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
  530. printf("%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
  531. return 0;
  532. } else {
  533. printf("%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
  534. return 3;
  535. }
  536. } break;
  537. #endif // __WINDOWS__
  538. #endif
  539. case 'h':
  540. case '?':
  541. default:
  542. printHelp(argv[0],stdout);
  543. return 0;
  544. }
  545. } else {
  546. if (homeDir.length()) {
  547. printHelp(argv[0],stdout);
  548. return 0;
  549. } else {
  550. homeDir = argv[i];
  551. }
  552. }
  553. }
  554. if (!homeDir.length())
  555. homeDir = OneService::platformDefaultHomePath();
  556. if (!homeDir.length()) {
  557. fprintf(stderr,"%s: no home path specified and no platform default available"ZT_EOL_S,argv[0]);
  558. return 1;
  559. } else {
  560. std::vector<std::string> hpsp(Utils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  561. std::string ptmp;
  562. if (homeDir[0] == ZT_PATH_SEPARATOR)
  563. ptmp.push_back(ZT_PATH_SEPARATOR);
  564. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  565. if (ptmp.length() > 0)
  566. ptmp.push_back(ZT_PATH_SEPARATOR);
  567. ptmp.append(*pi);
  568. if ((*pi != ".")&&(*pi != "..")) {
  569. if (!OSUtils::mkdir(ptmp))
  570. throw std::runtime_error("home path does not exist, and could not create");
  571. }
  572. }
  573. }
  574. #ifdef __UNIX_LIKE__
  575. if (getuid() != 0) {
  576. fprintf(stderr,"%s: must be run as root (uid 0)"ZT_EOL_S,argv[0]);
  577. return 1;
  578. }
  579. if (runAsDaemon) {
  580. long p = (long)fork();
  581. if (p < 0) {
  582. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  583. return 1;
  584. } else if (p > 0)
  585. return 0; // forked
  586. // else p == 0, so we are daemonized
  587. }
  588. #endif // __UNIX_LIKE__
  589. #ifdef __WINDOWS__
  590. if (winRunFromCommandLine) {
  591. // Running in "interactive" mode (mostly for debugging)
  592. if (IsCurrentUserLocalAdministrator() != TRUE) {
  593. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  594. return 1;
  595. }
  596. _winPokeAHole();
  597. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  598. // continues on to ordinary command line execution code below...
  599. } else {
  600. // Running from service manager
  601. _winPokeAHole();
  602. ZeroTierOneService zt1Service;
  603. if (CServiceBase::Run(zt1Service) == TRUE) {
  604. return 0;
  605. } else {
  606. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  607. return 1;
  608. }
  609. }
  610. #endif // __WINDOWS__
  611. NetworkController *controller = (NetworkController *)0;
  612. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  613. try {
  614. controller = new SqliteNetworkController((homeDir + ZT_PATH_SEPARATOR_S + ZT1_CONTROLLER_DB_PATH).c_str());
  615. } catch (std::exception &exc) {
  616. fprintf(stderr,"%s: failure initializing SqliteNetworkController: %s"ZT_EOL_S,argv[0],exc.what());
  617. return 1;
  618. } catch ( ... ) {
  619. fprintf(stderr,"%s: failure initializing SqliteNetworkController: unknown exception"ZT_EOL_S,argv[0]);
  620. return 1;
  621. }
  622. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  623. #ifdef __UNIX_LIKE__
  624. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT1_PID_PATH);
  625. {
  626. // Write .pid file to home folder
  627. FILE *pf = fopen(pidPath.c_str(),"w");
  628. if (pf) {
  629. fprintf(pf,"%ld",(long)getpid());
  630. fclose(pf);
  631. }
  632. }
  633. #endif // __UNIX_LIKE__
  634. unsigned int returnValue = 0;
  635. try {
  636. for(;;) {
  637. zt1Service = OneService::newInstance(homeDir.c_str(),port,controller,(overrideRootTopology.length() > 0) ? overrideRootTopology.c_str() : (const char *)0);
  638. switch(zt1Service->run()) {
  639. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  640. case OneService::ONE_NORMAL_TERMINATION:
  641. break;
  642. case OneService::ONE_UNRECOVERABLE_ERROR:
  643. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  644. returnValue = 1;
  645. break;
  646. case OneService::ONE_IDENTITY_COLLISION: {
  647. delete zt1Service;
  648. zt1Service = (OneService *)0;
  649. std::string oldid;
  650. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  651. if (oldid.length()) {
  652. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  653. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  654. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  655. }
  656. } continue; // restart!
  657. }
  658. break; // terminate loop -- normally we don't keep restarting
  659. }
  660. } catch (std::exception &exc) {
  661. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],exc.what());
  662. returnValue = 1;
  663. } catch ( ... ) {
  664. fprintf(stderr,"%s: fatal error: unknown exception"ZT_EOL_S,argv[0]);
  665. returnValue = 1;
  666. }
  667. delete zt1Service;
  668. zt1Service = (OneService *)0;
  669. delete controller;
  670. #ifdef __UNIX_LIKE__
  671. OSUtils::rm(pidPath.c_str());
  672. #endif
  673. return returnValue;
  674. }