one.cpp 24 KB

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