one.cpp 23 KB

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