one.cpp 30 KB

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