one.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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 "osdep/OSUtils.hpp"
  61. #include "service/OneService.hpp"
  62. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  63. #include "controller/SqliteNetworkController.hpp"
  64. #endif
  65. #define ZT1_AUTHTOKEN_SECRET_PATH "authtoken.secret"
  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 (Utils::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 (!Utils::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 (!Utils::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 (!Utils::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 (!Utils::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. Node *n = node;
  241. if (n)
  242. n->resync();
  243. }
  244. static void _sighandlerQuit(int sig)
  245. {
  246. Node *n = node;
  247. if (n)
  248. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  249. else exit(0);
  250. }
  251. #endif
  252. /****************************************************************************/
  253. /* Windows helper functions and signal handlers */
  254. /****************************************************************************/
  255. #ifdef __WINDOWS__
  256. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  257. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  258. {
  259. switch(dwCtrlType) {
  260. case CTRL_C_EVENT:
  261. case CTRL_BREAK_EVENT:
  262. case CTRL_CLOSE_EVENT:
  263. case CTRL_SHUTDOWN_EVENT:
  264. Node *n = node;
  265. if (n)
  266. n->terminate(Node::NODE_NORMAL_TERMINATION,"terminated by signal");
  267. return TRUE;
  268. }
  269. return FALSE;
  270. }
  271. // Pokes a hole in the Windows firewall (advfirewall) for the running program
  272. static void _winPokeAHole()
  273. {
  274. char myPath[MAX_PATH];
  275. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  276. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  277. STARTUPINFOA startupInfo;
  278. PROCESS_INFORMATION processInfo;
  279. startupInfo.cb = sizeof(startupInfo);
  280. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  281. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  282. 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)) {
  283. WaitForSingleObject(processInfo.hProcess,INFINITE);
  284. CloseHandle(processInfo.hProcess);
  285. CloseHandle(processInfo.hThread);
  286. }
  287. startupInfo.cb = sizeof(startupInfo);
  288. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  289. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  290. 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)) {
  291. WaitForSingleObject(processInfo.hProcess,INFINITE);
  292. CloseHandle(processInfo.hProcess);
  293. CloseHandle(processInfo.hThread);
  294. }
  295. startupInfo.cb = sizeof(startupInfo);
  296. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  297. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  298. 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)) {
  299. WaitForSingleObject(processInfo.hProcess,INFINITE);
  300. CloseHandle(processInfo.hProcess);
  301. CloseHandle(processInfo.hThread);
  302. }
  303. }
  304. }
  305. // Returns true if this is running as the local administrator
  306. static BOOL IsCurrentUserLocalAdministrator(void)
  307. {
  308. BOOL fReturn = FALSE;
  309. DWORD dwStatus;
  310. DWORD dwAccessMask;
  311. DWORD dwAccessDesired;
  312. DWORD dwACLSize;
  313. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  314. PACL pACL = NULL;
  315. PSID psidAdmin = NULL;
  316. HANDLE hToken = NULL;
  317. HANDLE hImpersonationToken = NULL;
  318. PRIVILEGE_SET ps;
  319. GENERIC_MAPPING GenericMapping;
  320. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  321. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  322. const DWORD ACCESS_READ = 1;
  323. const DWORD ACCESS_WRITE = 2;
  324. __try
  325. {
  326. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  327. {
  328. if (GetLastError() != ERROR_NO_TOKEN)
  329. __leave;
  330. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  331. __leave;
  332. }
  333. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  334. __leave;
  335. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  336. SECURITY_BUILTIN_DOMAIN_RID,
  337. DOMAIN_ALIAS_RID_ADMINS,
  338. 0, 0, 0, 0, 0, 0, &psidAdmin))
  339. __leave;
  340. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  341. if (psdAdmin == NULL)
  342. __leave;
  343. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  344. __leave;
  345. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  346. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  347. if (pACL == NULL)
  348. __leave;
  349. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  350. __leave;
  351. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  352. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  353. __leave;
  354. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  355. __leave;
  356. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  357. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  358. if (!IsValidSecurityDescriptor(psdAdmin))
  359. __leave;
  360. dwAccessDesired = ACCESS_READ;
  361. GenericMapping.GenericRead = ACCESS_READ;
  362. GenericMapping.GenericWrite = ACCESS_WRITE;
  363. GenericMapping.GenericExecute = 0;
  364. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  365. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  366. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  367. &fReturn))
  368. {
  369. fReturn = FALSE;
  370. __leave;
  371. }
  372. }
  373. __finally
  374. {
  375. // Clean up.
  376. if (pACL) LocalFree(pACL);
  377. if (psdAdmin) LocalFree(psdAdmin);
  378. if (psidAdmin) FreeSid(psidAdmin);
  379. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  380. if (hToken) CloseHandle (hToken);
  381. }
  382. return fReturn;
  383. }
  384. #endif // __WINDOWS__
  385. /****************************************************************************/
  386. /* main() and friends */
  387. /****************************************************************************/
  388. static void printHelp(const char *cn,FILE *out)
  389. {
  390. 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);
  391. fprintf(out,"Licensed under the GNU General Public License v3"ZT_EOL_S""ZT_EOL_S);
  392. fprintf(out,"Usage: %s [-switches] [home directory] [-q <query>]"ZT_EOL_S""ZT_EOL_S,cn);
  393. fprintf(out,"Available switches:"ZT_EOL_S);
  394. fprintf(out," -h - Display this help"ZT_EOL_S);
  395. fprintf(out," -v - Show version"ZT_EOL_S);
  396. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993)"ZT_EOL_S);
  397. //fprintf(out," -T<path> - Override root topology, do not authenticate or update"ZT_EOL_S);
  398. #ifdef __UNIX_LIKE__
  399. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  400. #endif // __UNIX_LIKE__
  401. fprintf(out," -q - Send a query to a running service (zerotier-cli)"ZT_EOL_S);
  402. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  403. #ifdef __WINDOWS__
  404. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  405. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  406. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  407. fprintf(out," -D - Load tap driver into system driver store (Windows)"ZT_EOL_S);
  408. #endif // __WINDOWS__
  409. }
  410. #ifdef __WINDOWS__
  411. int _tmain(int argc, _TCHAR* argv[])
  412. #else
  413. int main(int argc,char **argv)
  414. #endif
  415. {
  416. #ifdef __UNIX_LIKE__
  417. signal(SIGHUP,&_sighandlerHup);
  418. signal(SIGPIPE,SIG_IGN);
  419. signal(SIGUSR1,SIG_IGN);
  420. signal(SIGUSR2,SIG_IGN);
  421. signal(SIGALRM,SIG_IGN);
  422. signal(SIGINT,&_sighandlerQuit);
  423. signal(SIGTERM,&_sighandlerQuit);
  424. signal(SIGQUIT,&_sighandlerQuit);
  425. /* Ensure that there are no inherited file descriptors open from a previous
  426. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  427. * of it do not return, and should not do anything otherwise bad. */
  428. {
  429. int mfd = STDIN_FILENO;
  430. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  431. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  432. for(int f=mfd+1;f<1024;++f)
  433. ::close(f);
  434. }
  435. bool runAsDaemon = false;
  436. #endif // __UNIX_LIKE__
  437. #ifdef __WINDOWS__
  438. WSADATA wsaData;
  439. WSAStartup(MAKEWORD(2,2),&wsaData);
  440. #ifdef ZT_WIN_RUN_IN_CONSOLE
  441. bool winRunFromCommandLine = true;
  442. #else
  443. bool winRunFromCommandLine = false;
  444. #endif
  445. #endif // __WINDOWS__
  446. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  447. return cli(argc,argv);
  448. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  449. return idtool(argc,argv);
  450. std::string overrideRootTopology;
  451. std::string homeDir;
  452. unsigned int port = ZT1_DEFAULT_PORT;
  453. for(int i=1;i<argc;++i) {
  454. if (argv[i][0] == '-') {
  455. switch(argv[i][1]) {
  456. case 'p': // port -- for both UDP and TCP, packets and control plane
  457. port = Utils::strToUInt(argv[i] + 2);
  458. if ((port > 0xffff)||(port == 0)) {
  459. printHelp(argv[0],stdout);
  460. return 1;
  461. }
  462. break;
  463. case 't': // TCP port -- ignore, since we now bind to both UDP and TCP on the same port
  464. break;
  465. #ifdef __UNIX_LIKE__
  466. case 'd': // Run in background as daemon
  467. runAsDaemon = true;
  468. break;
  469. #endif // __UNIX_LIKE__
  470. case 'T': // Override root topology
  471. if (argv[i][2]) {
  472. if (!OSUtils::readFile(argv[i] + 2,overrideRootTopology)) {
  473. fprintf(stderr,"%s: cannot read root topology from %s"ZT_EOL_S,argv[0],argv[i] + 2);
  474. return 1;
  475. }
  476. } else {
  477. printHelp(argv[0],stdout);
  478. return 1;
  479. }
  480. break;
  481. case 'v': // Display version
  482. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  483. return 0;
  484. case 'q': // Invoke cli personality
  485. if (argv[i][2]) {
  486. printHelp(argv[0],stdout);
  487. return 0;
  488. } else return cli(argc,argv);
  489. case 'i': // Invoke idtool personality
  490. if (argv[i][2]) {
  491. printHelp(argv[0],stdout);
  492. return 0;
  493. } else return idtool(argc,argv);
  494. #ifdef __WINDOWS__
  495. case 'C': // Run from command line instead of as Windows service
  496. winRunFromCommandLine = true;
  497. break;
  498. case 'I': { // Install this binary as a Windows service
  499. if (IsCurrentUserLocalAdministrator() != TRUE) {
  500. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  501. return 1;
  502. }
  503. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  504. if (ret.length()) {
  505. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  506. return 3;
  507. }
  508. return 0;
  509. } break;
  510. case 'R': { // Uninstall this binary as Windows service
  511. if (IsCurrentUserLocalAdministrator() != TRUE) {
  512. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  513. return 1;
  514. }
  515. std::string ret(UninstallService(ZT_SERVICE_NAME));
  516. if (ret.length()) {
  517. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  518. return 3;
  519. }
  520. return 0;
  521. } break;
  522. #if 0
  523. case 'D': { // Install Windows driver (since PNPUTIL.EXE seems to be weirdly unreliable)
  524. std::string pathToInf;
  525. #ifdef _WIN64
  526. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x64\\zttap200.inf";
  527. #else
  528. pathToInf = ZT_DEFAULTS.defaultHomePath + "\\tap-windows\\x86\\zttap200.inf";
  529. #endif
  530. 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);
  531. BOOL needReboot = FALSE;
  532. if (DiInstallDriverA(NULL,pathToInf.c_str(),DIIRFLAG_FORCE_INF,&needReboot)) {
  533. printf("%s: driver successfully installed from %s"ZT_EOL_S,argv[0],pathToInf.c_str());
  534. return 0;
  535. } else {
  536. printf("%s: failed installing %s: %d"ZT_EOL_S,argv[0],pathToInf.c_str(),(int)GetLastError());
  537. return 3;
  538. }
  539. } break;
  540. #endif // __WINDOWS__
  541. #endif
  542. case 'h':
  543. case '?':
  544. default:
  545. printHelp(argv[0],stdout);
  546. return 0;
  547. }
  548. } else {
  549. if (homeDir.length()) {
  550. printHelp(argv[0],stdout);
  551. return 0;
  552. } else {
  553. homeDir = argv[i];
  554. }
  555. }
  556. }
  557. if (!homeDir.length())
  558. homeDir = OneService::platformDefaultHomePath();
  559. if (!homeDir.length()) {
  560. fprintf(stderr,"%s: no home path specified and no platform default available"ZT_EOL_S,argv[0]);
  561. return 1;
  562. } else {
  563. std::vector<std::string> hpsp(Utils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  564. std::string ptmp;
  565. if (homeDir[0] == ZT_PATH_SEPARATOR)
  566. ptmp.push_back(ZT_PATH_SEPARATOR);
  567. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  568. if (ptmp.length() > 0)
  569. ptmp.push_back(ZT_PATH_SEPARATOR);
  570. ptmp.append(*pi);
  571. if ((*pi != ".")&&(*pi != "..")) {
  572. if (!OSUtils::mkdir(ptmp))
  573. throw std::runtime_error("home path does not exist, and could not create");
  574. }
  575. }
  576. }
  577. std::string authToken;
  578. {
  579. std::string authTokenPath(homeDir + ZT_PATH_SEPARATOR_S + ZT1_AUTHTOKEN_SECRET_PATH);
  580. if (!OSUtils::readFile(authTokenPath.c_str(),authToken)) {
  581. unsigned char foo[24];
  582. Utils::getSecureRandom(foo,sizeof(foo));
  583. authToken = "";
  584. for(unsigned int i=0;i<sizeof(foo);++i)
  585. authToken.push_back("abcdefghijklmnopqrstuvwxyz0123456789"[(unsigned long)foo[i] % 36]);
  586. if (!OSUtils::writeFile(authTokenPath.c_str(),authToken)) {
  587. fprintf(stderr,"%s: cannot create authtoken.secret"ZT_EOL_S,argv[0]);
  588. return 1;
  589. } else OSUtils::lockDownFile(authTokenPath.c_str(),false);
  590. }
  591. }
  592. authToken = Utils::trim(authToken);
  593. #ifdef __UNIX_LIKE__
  594. if (getuid() != 0) {
  595. fprintf(stderr,"%s: must be run as root (uid 0)"ZT_EOL_S,argv[0]);
  596. return 1;
  597. }
  598. if (runAsDaemon) {
  599. long p = (long)fork();
  600. if (p < 0) {
  601. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  602. return 1;
  603. } else if (p > 0)
  604. return 0; // forked
  605. // else p == 0, so we are daemonized
  606. }
  607. {
  608. // Write .pid file to home folder
  609. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT1_PID_PATH);
  610. FILE *pf = fopen(pidPath.c_str(),"w");
  611. if (pf) {
  612. fprintf(pf,"%ld",(long)getpid());
  613. fclose(pf);
  614. }
  615. }
  616. #endif // __UNIX_LIKE__
  617. #ifdef __WINDOWS__
  618. if (winRunFromCommandLine) {
  619. // Running in "interactive" mode (mostly for debugging)
  620. if (IsCurrentUserLocalAdministrator() != TRUE) {
  621. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  622. return 1;
  623. }
  624. _winPokeAHole();
  625. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  626. // continues on to ordinary command line execution code below...
  627. } else {
  628. // Running from service manager
  629. _winPokeAHole();
  630. ZeroTierOneService zt1Service;
  631. if (CServiceBase::Run(zt1Service) == TRUE) {
  632. return 0;
  633. } else {
  634. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  635. return 1;
  636. }
  637. }
  638. #endif // __WINDOWS__
  639. NetworkController *controller = (NetworkController *)0;
  640. #ifdef ZT_ENABLE_NETWORK_CONTROLLER
  641. try {
  642. controller = new SqliteNetworkController((homeDir + ZT_PATH_SEPARATOR_S + ZT1_CONTROLLER_DB_PATH).c_str());
  643. } catch (std::exception &exc) {
  644. fprintf(stderr,"%s: failure initializing SqliteNetworkController: %s"ZT_EOL_S,exc.what());
  645. return 1;
  646. } catch ( ... ) {
  647. fprintf(stderr,"%s: failure initializing SqliteNetworkController: unknown exception"ZT_EOL_S);
  648. return 1;
  649. }
  650. #endif // ZT_ENABLE_NETWORK_CONTROLLER
  651. unsigned int returnValue = 0;
  652. try {
  653. for(;;) {
  654. zt1Service = OneService::newInstance(homeDir.c_str(),port,controller,(overrideRootTopology.length() > 0) ? overrideRootTopology.c_str() : (const char *)0);
  655. switch(zt1Service->run()) {
  656. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  657. case OneService::ONE_NORMAL_TERMINATION:
  658. break;
  659. case OneService::ONE_UNRECOVERABLE_ERROR:
  660. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  661. returnValue = 1;
  662. break;
  663. case OneService::ONE_IDENTITY_COLLISION: {
  664. delete zt1Service;
  665. zt1Service = (OneService *)0;
  666. std::string oldid;
  667. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  668. if (oldid.length()) {
  669. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  670. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  671. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  672. }
  673. } continue; // restart!
  674. }
  675. break; // terminate loop -- normally we don't keep restarting
  676. }
  677. } catch (std::exception &exc) {
  678. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],exc.what());
  679. returnValue = 1;
  680. } catch ( ... ) {
  681. fprintf(stderr,"%s: fatal error: unknown exception"ZT_EOL_S,argv[0]);
  682. returnValue = 1;
  683. }
  684. delete zt1Service;
  685. zt1Service = (OneService *)0;
  686. delete controller;
  687. return returnValue;
  688. }