one.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include "node/Constants.hpp"
  25. #ifdef __WINDOWS__
  26. #include <WinSock2.h>
  27. #include <Windows.h>
  28. #include <tchar.h>
  29. #include <wchar.h>
  30. #include <lmcons.h>
  31. #include <newdev.h>
  32. #include <atlbase.h>
  33. #include "osdep/WindowsEthernetTap.hpp"
  34. #include "windows/ZeroTierOne/ServiceInstaller.h"
  35. #include "windows/ZeroTierOne/ServiceBase.h"
  36. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  37. #else
  38. #include <unistd.h>
  39. #include <pwd.h>
  40. #include <fcntl.h>
  41. #include <sys/types.h>
  42. #include <sys/stat.h>
  43. #include <signal.h>
  44. #endif
  45. #include <string>
  46. #include <stdexcept>
  47. #include "version.h"
  48. #include "include/ZeroTierOne.h"
  49. #include "ext/json-parser/json.h"
  50. #include "node/Identity.hpp"
  51. #include "node/CertificateOfMembership.hpp"
  52. #include "node/Utils.hpp"
  53. #include "node/NetworkController.hpp"
  54. #include "osdep/OSUtils.hpp"
  55. #include "osdep/Http.hpp"
  56. #include "service/OneService.hpp"
  57. #define ZT_PID_PATH "zerotier-one.pid"
  58. using namespace ZeroTier;
  59. static OneService *volatile zt1Service = (OneService *)0;
  60. #define PROGRAM_NAME "ZeroTier One"
  61. #define COPYRIGHT_NOTICE "Copyright © 2011–2016 ZeroTier, Inc."
  62. #define LICENSE_GRANT \
  63. "This is free software: you may copy, modify, and/or distribute this" ZT_EOL_S \
  64. "work under the terms of the GNU General Public License, version 3 or" ZT_EOL_S \
  65. "later as published by the Free Software Foundation." ZT_EOL_S \
  66. "No warranty expressed or implied." ZT_EOL_S
  67. /****************************************************************************/
  68. /* zerotier-cli personality */
  69. /****************************************************************************/
  70. static void cliPrintHelp(const char *pn,FILE *out)
  71. {
  72. fprintf(out,
  73. "%s version %d.%d.%d" ZT_EOL_S,
  74. PROGRAM_NAME,
  75. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  76. fprintf(out,
  77. COPYRIGHT_NOTICE ZT_EOL_S
  78. LICENSE_GRANT ZT_EOL_S);
  79. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]"ZT_EOL_S""ZT_EOL_S,pn);
  80. fprintf(out,"Available switches:"ZT_EOL_S);
  81. fprintf(out," -h - Display this help"ZT_EOL_S);
  82. fprintf(out," -v - Show version"ZT_EOL_S);
  83. fprintf(out," -j - Display full raw JSON output"ZT_EOL_S);
  84. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect"ZT_EOL_S);
  85. fprintf(out," -p<port> - HTTP port (default: auto)"ZT_EOL_S);
  86. fprintf(out," -T<token> - Authentication token (default: auto)"ZT_EOL_S);
  87. //fprintf(out," -H<ip> - HTTP server bind address (default: 127.0.0.1)"ZT_EOL_S);
  88. fprintf(out,ZT_EOL_S"Available commands:"ZT_EOL_S);
  89. fprintf(out," info - Display status info"ZT_EOL_S);
  90. fprintf(out," listpeers - List all peers"ZT_EOL_S);
  91. fprintf(out," listnetworks - List all networks"ZT_EOL_S);
  92. fprintf(out," join <network> - Join a network"ZT_EOL_S);
  93. fprintf(out," leave <network> - Leave a network"ZT_EOL_S);
  94. }
  95. static std::string cliFixJsonCRs(const std::string &s)
  96. {
  97. std::string r;
  98. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  99. if (*c == '\n')
  100. r.append(ZT_EOL_S);
  101. else r.push_back(*c);
  102. }
  103. return r;
  104. }
  105. #ifdef __WINDOWS__
  106. static int cli(int argc, _TCHAR* argv[])
  107. #else
  108. static int cli(int argc,char **argv)
  109. #endif
  110. {
  111. unsigned int port = 0;
  112. std::string homeDir;
  113. std::string command;
  114. std::string arg1;
  115. std::string authToken;
  116. std::string ip("127.0.0.1");
  117. bool json = false;
  118. for(int i=1;i<argc;++i) {
  119. if (argv[i][0] == '-') {
  120. switch(argv[i][1]) {
  121. case 'q': // ignore -q used to invoke this personality
  122. if (argv[i][2]) {
  123. cliPrintHelp(argv[0],stdout);
  124. return 1;
  125. }
  126. break;
  127. case 'j':
  128. if (argv[i][2]) {
  129. cliPrintHelp(argv[0],stdout);
  130. return 1;
  131. }
  132. json = true;
  133. break;
  134. case 'p':
  135. port = Utils::strToUInt(argv[i] + 2);
  136. if ((port > 0xffff)||(port == 0)) {
  137. cliPrintHelp(argv[0],stdout);
  138. return 1;
  139. }
  140. break;
  141. case 'D':
  142. if (argv[i][2]) {
  143. homeDir = argv[i] + 2;
  144. } else {
  145. cliPrintHelp(argv[0],stdout);
  146. return 1;
  147. }
  148. break;
  149. case 'H':
  150. if (argv[i][2]) {
  151. ip = argv[i] + 2;
  152. } else {
  153. cliPrintHelp(argv[0],stdout);
  154. return 1;
  155. }
  156. break;
  157. case 'T':
  158. if (argv[i][2]) {
  159. authToken = argv[i] + 2;
  160. } else {
  161. cliPrintHelp(argv[0],stdout);
  162. return 1;
  163. }
  164. break;
  165. case 'v':
  166. if (argv[i][2]) {
  167. cliPrintHelp(argv[0],stdout);
  168. return 1;
  169. }
  170. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  171. return 0;
  172. case 'h':
  173. case '?':
  174. default:
  175. cliPrintHelp(argv[0],stdout);
  176. return 0;
  177. }
  178. } else {
  179. if (command.length())
  180. arg1 = argv[i];
  181. else command = argv[i];
  182. }
  183. }
  184. if (!homeDir.length())
  185. homeDir = OneService::platformDefaultHomePath();
  186. if ((!port)||(!authToken.length())) {
  187. if (!homeDir.length()) {
  188. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect"ZT_EOL_S,argv[0]);
  189. return 2;
  190. }
  191. if (!port) {
  192. std::string portStr;
  193. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  194. port = Utils::strToUInt(portStr.c_str());
  195. if ((port == 0)||(port > 0xffff)) {
  196. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s"ZT_EOL_S,argv[0],homeDir.c_str());
  197. return 2;
  198. }
  199. }
  200. if (!authToken.length()) {
  201. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  202. #ifdef __UNIX_LIKE__
  203. if (!authToken.length()) {
  204. const char *hd = getenv("HOME");
  205. if (hd) {
  206. char p[4096];
  207. #ifdef __APPLE__
  208. Utils::snprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  209. #else
  210. Utils::snprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  211. #endif
  212. OSUtils::readFile(p,authToken);
  213. }
  214. }
  215. #endif
  216. if (!authToken.length()) {
  217. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s"ZT_EOL_S,argv[0],homeDir.c_str());
  218. return 2;
  219. }
  220. }
  221. }
  222. InetAddress addr;
  223. {
  224. char addrtmp[256];
  225. Utils::snprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  226. addr = InetAddress(addrtmp);
  227. }
  228. std::map<std::string,std::string> requestHeaders;
  229. std::map<std::string,std::string> responseHeaders;
  230. std::string responseBody;
  231. requestHeaders["X-ZT1-Auth"] = authToken;
  232. if ((command.length() > 0)&&(command[0] == '/')) {
  233. unsigned int scode = Http::GET(
  234. 1024 * 1024 * 16,
  235. 60000,
  236. (const struct sockaddr *)&addr,
  237. command.c_str(),
  238. requestHeaders,
  239. responseHeaders,
  240. responseBody);
  241. if (scode == 200) {
  242. printf("%s",cliFixJsonCRs(responseBody).c_str());
  243. return 0;
  244. } else {
  245. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  246. return 1;
  247. }
  248. } else if ((command == "info")||(command == "status")) {
  249. unsigned int scode = Http::GET(
  250. 1024 * 1024 * 16,
  251. 60000,
  252. (const struct sockaddr *)&addr,
  253. "/status",
  254. requestHeaders,
  255. responseHeaders,
  256. responseBody);
  257. if (scode == 200) {
  258. if (json) {
  259. printf("%s",cliFixJsonCRs(responseBody).c_str());
  260. return 0;
  261. } else {
  262. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  263. bool good = false;
  264. if (j) {
  265. if (j->type == json_object) {
  266. const char *address = (const char *)0;
  267. bool online = false;
  268. const char *version = (const char *)0;
  269. for(unsigned int k=0;k<j->u.object.length;++k) {
  270. if ((!strcmp(j->u.object.values[k].name,"address"))&&(j->u.object.values[k].value->type == json_string))
  271. address = j->u.object.values[k].value->u.string.ptr;
  272. else if ((!strcmp(j->u.object.values[k].name,"version"))&&(j->u.object.values[k].value->type == json_string))
  273. version = j->u.object.values[k].value->u.string.ptr;
  274. else if ((!strcmp(j->u.object.values[k].name,"online"))&&(j->u.object.values[k].value->type == json_boolean))
  275. online = (j->u.object.values[k].value->u.boolean != 0);
  276. }
  277. if ((address)&&(version)) {
  278. printf("200 info %s %s %s"ZT_EOL_S,address,(online ? "ONLINE" : "OFFLINE"),version);
  279. good = true;
  280. }
  281. }
  282. json_value_free(j);
  283. }
  284. if (good) {
  285. return 0;
  286. } else {
  287. printf("%u %s invalid JSON response"ZT_EOL_S,scode,command.c_str());
  288. return 1;
  289. }
  290. }
  291. } else {
  292. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  293. return 1;
  294. }
  295. } else if (command == "listpeers") {
  296. unsigned int scode = Http::GET(
  297. 1024 * 1024 * 16,
  298. 60000,
  299. (const struct sockaddr *)&addr,
  300. "/peer",
  301. requestHeaders,
  302. responseHeaders,
  303. responseBody);
  304. if (scode == 200) {
  305. if (json) {
  306. printf("%s",cliFixJsonCRs(responseBody).c_str());
  307. return 0;
  308. } else {
  309. printf("200 listpeers <ztaddr> <paths> <latency> <version> <role>"ZT_EOL_S);
  310. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  311. if (j) {
  312. if (j->type == json_array) {
  313. for(unsigned int p=0;p<j->u.array.length;++p) {
  314. json_value *jp = j->u.array.values[p];
  315. if (jp->type == json_object) {
  316. const char *address = (const char *)0;
  317. std::string paths;
  318. int64_t latency = 0;
  319. int64_t versionMajor = -1,versionMinor = -1,versionRev = -1;
  320. const char *role = (const char *)0;
  321. for(unsigned int k=0;k<jp->u.object.length;++k) {
  322. if ((!strcmp(jp->u.object.values[k].name,"address"))&&(jp->u.object.values[k].value->type == json_string))
  323. address = jp->u.object.values[k].value->u.string.ptr;
  324. else if ((!strcmp(jp->u.object.values[k].name,"versionMajor"))&&(jp->u.object.values[k].value->type == json_integer))
  325. versionMajor = jp->u.object.values[k].value->u.integer;
  326. else if ((!strcmp(jp->u.object.values[k].name,"versionMinor"))&&(jp->u.object.values[k].value->type == json_integer))
  327. versionMinor = jp->u.object.values[k].value->u.integer;
  328. else if ((!strcmp(jp->u.object.values[k].name,"versionRev"))&&(jp->u.object.values[k].value->type == json_integer))
  329. versionRev = jp->u.object.values[k].value->u.integer;
  330. else if ((!strcmp(jp->u.object.values[k].name,"role"))&&(jp->u.object.values[k].value->type == json_string))
  331. role = jp->u.object.values[k].value->u.string.ptr;
  332. else if ((!strcmp(jp->u.object.values[k].name,"latency"))&&(jp->u.object.values[k].value->type == json_integer))
  333. latency = jp->u.object.values[k].value->u.integer;
  334. else if ((!strcmp(jp->u.object.values[k].name,"paths"))&&(jp->u.object.values[k].value->type == json_array)) {
  335. for(unsigned int pp=0;pp<jp->u.object.values[k].value->u.array.length;++pp) {
  336. json_value *jpath = jp->u.object.values[k].value->u.array.values[pp];
  337. if (jpath->type == json_object) {
  338. const char *paddr = (const char *)0;
  339. int64_t lastSend = 0;
  340. int64_t lastReceive = 0;
  341. bool preferred = false;
  342. bool active = false;
  343. for(unsigned int kk=0;kk<jpath->u.object.length;++kk) {
  344. if ((!strcmp(jpath->u.object.values[kk].name,"address"))&&(jpath->u.object.values[kk].value->type == json_string))
  345. paddr = jpath->u.object.values[kk].value->u.string.ptr;
  346. else if ((!strcmp(jpath->u.object.values[kk].name,"lastSend"))&&(jpath->u.object.values[kk].value->type == json_integer))
  347. lastSend = jpath->u.object.values[kk].value->u.integer;
  348. else if ((!strcmp(jpath->u.object.values[kk].name,"lastReceive"))&&(jpath->u.object.values[kk].value->type == json_integer))
  349. lastReceive = jpath->u.object.values[kk].value->u.integer;
  350. else if ((!strcmp(jpath->u.object.values[kk].name,"preferred"))&&(jpath->u.object.values[kk].value->type == json_boolean))
  351. preferred = (jpath->u.object.values[kk].value->u.boolean != 0);
  352. else if ((!strcmp(jpath->u.object.values[kk].name,"active"))&&(jpath->u.object.values[kk].value->type == json_boolean))
  353. active = (jpath->u.object.values[kk].value->u.boolean != 0);
  354. }
  355. if ((paddr)&&(active)) {
  356. int64_t now = (int64_t)OSUtils::now();
  357. if (lastSend > 0)
  358. lastSend = now - lastSend;
  359. if (lastReceive > 0)
  360. lastReceive = now - lastReceive;
  361. char pathtmp[256];
  362. Utils::snprintf(pathtmp,sizeof(pathtmp),"%s;%lld;%lld;%s",
  363. paddr,
  364. lastSend,
  365. lastReceive,
  366. (preferred ? "preferred" : "active"));
  367. if (paths.length())
  368. paths.push_back(',');
  369. paths.append(pathtmp);
  370. }
  371. }
  372. }
  373. }
  374. }
  375. if ((address)&&(role)) {
  376. char verstr[64];
  377. if ((versionMajor >= 0)&&(versionMinor >= 0)&&(versionRev >= 0))
  378. Utils::snprintf(verstr,sizeof(verstr),"%lld.%lld.%lld",versionMajor,versionMinor,versionRev);
  379. else {
  380. verstr[0] = '-';
  381. verstr[1] = (char)0;
  382. }
  383. printf("200 listpeers %s %s %lld %s %s"ZT_EOL_S,address,(paths.length()) ? paths.c_str() : "-",(long long)latency,verstr,role);
  384. }
  385. }
  386. }
  387. }
  388. json_value_free(j);
  389. }
  390. return 0;
  391. }
  392. } else {
  393. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  394. return 1;
  395. }
  396. } else if (command == "listnetworks") {
  397. unsigned int scode = Http::GET(
  398. 1024 * 1024 * 16,
  399. 60000,
  400. (const struct sockaddr *)&addr,
  401. "/network",
  402. requestHeaders,
  403. responseHeaders,
  404. responseBody);
  405. if (scode == 200) {
  406. if (json) {
  407. printf("%s",cliFixJsonCRs(responseBody).c_str());
  408. return 0;
  409. } else {
  410. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>"ZT_EOL_S);
  411. json_value *j = json_parse(responseBody.c_str(),responseBody.length());
  412. if (j) {
  413. if (j->type == json_array) {
  414. for(unsigned int p=0;p<j->u.array.length;++p) {
  415. json_value *jn = j->u.array.values[p];
  416. if (jn->type == json_object) {
  417. const char *nwid = (const char *)0;
  418. const char *name = "";
  419. const char *mac = (const char *)0;
  420. const char *status = (const char *)0;
  421. const char *type = (const char *)0;
  422. const char *portDeviceName = "";
  423. std::string ips;
  424. for(unsigned int k=0;k<jn->u.object.length;++k) {
  425. if ((!strcmp(jn->u.object.values[k].name,"nwid"))&&(jn->u.object.values[k].value->type == json_string))
  426. nwid = jn->u.object.values[k].value->u.string.ptr;
  427. else if ((!strcmp(jn->u.object.values[k].name,"name"))&&(jn->u.object.values[k].value->type == json_string))
  428. name = jn->u.object.values[k].value->u.string.ptr;
  429. else if ((!strcmp(jn->u.object.values[k].name,"mac"))&&(jn->u.object.values[k].value->type == json_string))
  430. mac = jn->u.object.values[k].value->u.string.ptr;
  431. else if ((!strcmp(jn->u.object.values[k].name,"status"))&&(jn->u.object.values[k].value->type == json_string))
  432. status = jn->u.object.values[k].value->u.string.ptr;
  433. else if ((!strcmp(jn->u.object.values[k].name,"type"))&&(jn->u.object.values[k].value->type == json_string))
  434. type = jn->u.object.values[k].value->u.string.ptr;
  435. else if ((!strcmp(jn->u.object.values[k].name,"portDeviceName"))&&(jn->u.object.values[k].value->type == json_string))
  436. portDeviceName = jn->u.object.values[k].value->u.string.ptr;
  437. else if ((!strcmp(jn->u.object.values[k].name,"assignedAddresses"))&&(jn->u.object.values[k].value->type == json_array)) {
  438. for(unsigned int a=0;a<jn->u.object.values[k].value->u.array.length;++a) {
  439. json_value *aa = jn->u.object.values[k].value->u.array.values[a];
  440. if (aa->type == json_string) {
  441. if (ips.length())
  442. ips.push_back(',');
  443. ips.append(aa->u.string.ptr);
  444. }
  445. }
  446. }
  447. }
  448. if ((nwid)&&(mac)&&(status)&&(type)) {
  449. printf("200 listnetworks %s %s %s %s %s %s %s"ZT_EOL_S,
  450. nwid,
  451. (((name)&&(name[0])) ? name : "-"),
  452. mac,
  453. status,
  454. type,
  455. (((portDeviceName)&&(portDeviceName[0])) ? portDeviceName : "-"),
  456. ((ips.length() > 0) ? ips.c_str() : "-"));
  457. }
  458. }
  459. }
  460. }
  461. json_value_free(j);
  462. }
  463. }
  464. } else {
  465. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  466. return 1;
  467. }
  468. } else if (command == "join") {
  469. if (arg1.length() != 16) {
  470. cliPrintHelp(argv[0],stderr);
  471. return 2;
  472. }
  473. requestHeaders["Content-Type"] = "application/json";
  474. requestHeaders["Content-Length"] = "2";
  475. unsigned int scode = Http::POST(
  476. 1024 * 1024 * 16,
  477. 60000,
  478. (const struct sockaddr *)&addr,
  479. (std::string("/network/") + arg1).c_str(),
  480. requestHeaders,
  481. "{}",
  482. 2,
  483. responseHeaders,
  484. responseBody);
  485. if (scode == 200) {
  486. if (json) {
  487. printf("%s",cliFixJsonCRs(responseBody).c_str());
  488. } else {
  489. printf("200 join OK"ZT_EOL_S);
  490. }
  491. return 0;
  492. } else {
  493. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  494. return 1;
  495. }
  496. } else if (command == "leave") {
  497. if (arg1.length() != 16) {
  498. cliPrintHelp(argv[0],stderr);
  499. return 2;
  500. }
  501. unsigned int scode = Http::DEL(
  502. 1024 * 1024 * 16,
  503. 60000,
  504. (const struct sockaddr *)&addr,
  505. (std::string("/network/") + arg1).c_str(),
  506. requestHeaders,
  507. responseHeaders,
  508. responseBody);
  509. if (scode == 200) {
  510. if (json) {
  511. printf("%s",cliFixJsonCRs(responseBody).c_str());
  512. } else {
  513. printf("200 leave OK"ZT_EOL_S);
  514. }
  515. return 0;
  516. } else {
  517. printf("%u %s %s"ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  518. return 1;
  519. }
  520. } else {
  521. cliPrintHelp(argv[0],stderr);
  522. return 0;
  523. }
  524. return 0;
  525. }
  526. /****************************************************************************/
  527. /* zerotier-idtool personality */
  528. /****************************************************************************/
  529. static void idtoolPrintHelp(FILE *out,const char *pn)
  530. {
  531. fprintf(out,
  532. "%s version %d.%d.%d" ZT_EOL_S,
  533. PROGRAM_NAME,
  534. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  535. fprintf(out,
  536. COPYRIGHT_NOTICE ZT_EOL_S
  537. LICENSE_GRANT ZT_EOL_S);
  538. fprintf(out,"Usage: %s <command> [<args>]"ZT_EOL_S""ZT_EOL_S"Commands:"ZT_EOL_S,pn);
  539. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]"ZT_EOL_S);
  540. fprintf(out," validate <identity.secret/public>"ZT_EOL_S);
  541. fprintf(out," getpublic <identity.secret>"ZT_EOL_S);
  542. fprintf(out," sign <identity.secret> <file>"ZT_EOL_S);
  543. fprintf(out," verify <identity.secret/public> <file> <signature>"ZT_EOL_S);
  544. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)"ZT_EOL_S);
  545. }
  546. static Identity getIdFromArg(char *arg)
  547. {
  548. Identity id;
  549. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  550. if (id.fromString(arg))
  551. return id;
  552. } else { // identity is to be read from a file
  553. std::string idser;
  554. if (OSUtils::readFile(arg,idser)) {
  555. if (id.fromString(idser))
  556. return id;
  557. }
  558. }
  559. return Identity();
  560. }
  561. #ifdef __WINDOWS__
  562. static int idtool(int argc, _TCHAR* argv[])
  563. #else
  564. static int idtool(int argc,char **argv)
  565. #endif
  566. {
  567. if (argc < 2) {
  568. idtoolPrintHelp(stdout,argv[0]);
  569. return 1;
  570. }
  571. if (!strcmp(argv[1],"generate")) {
  572. uint64_t vanity = 0;
  573. int vanityBits = 0;
  574. if (argc >= 5) {
  575. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  576. vanityBits = 4 * strlen(argv[4]);
  577. if (vanityBits > 40)
  578. vanityBits = 40;
  579. }
  580. Identity id;
  581. for(;;) {
  582. id.generate();
  583. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  584. if (vanityBits > 0) {
  585. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  586. }
  587. break;
  588. } else {
  589. fprintf(stderr,"vanity address: tried %.10llx looking for first %d bits of %.10llx\n",(unsigned long long)id.address().toInt(),vanityBits,(unsigned long long)(vanity << (40 - vanityBits)));
  590. }
  591. }
  592. std::string idser = id.toString(true);
  593. if (argc >= 3) {
  594. if (!OSUtils::writeFile(argv[2],idser)) {
  595. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[2]);
  596. return 1;
  597. } else printf("%s written"ZT_EOL_S,argv[2]);
  598. if (argc >= 4) {
  599. idser = id.toString(false);
  600. if (!OSUtils::writeFile(argv[3],idser)) {
  601. fprintf(stderr,"Error writing to %s"ZT_EOL_S,argv[3]);
  602. return 1;
  603. } else printf("%s written"ZT_EOL_S,argv[3]);
  604. }
  605. } else printf("%s",idser.c_str());
  606. } else if (!strcmp(argv[1],"validate")) {
  607. if (argc < 3) {
  608. idtoolPrintHelp(stdout,argv[0]);
  609. return 1;
  610. }
  611. Identity id = getIdFromArg(argv[2]);
  612. if (!id) {
  613. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  614. return 1;
  615. }
  616. if (!id.locallyValidate()) {
  617. fprintf(stderr,"%s FAILED validation."ZT_EOL_S,argv[2]);
  618. return 1;
  619. } else printf("%s is a valid identity"ZT_EOL_S,argv[2]);
  620. } else if (!strcmp(argv[1],"getpublic")) {
  621. if (argc < 3) {
  622. idtoolPrintHelp(stdout,argv[0]);
  623. return 1;
  624. }
  625. Identity id = getIdFromArg(argv[2]);
  626. if (!id) {
  627. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  628. return 1;
  629. }
  630. printf("%s",id.toString(false).c_str());
  631. } else if (!strcmp(argv[1],"sign")) {
  632. if (argc < 4) {
  633. idtoolPrintHelp(stdout,argv[0]);
  634. return 1;
  635. }
  636. Identity id = getIdFromArg(argv[2]);
  637. if (!id) {
  638. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  639. return 1;
  640. }
  641. if (!id.hasPrivate()) {
  642. fprintf(stderr,"%s does not contain a private key (must use private to sign)"ZT_EOL_S,argv[2]);
  643. return 1;
  644. }
  645. std::string inf;
  646. if (!OSUtils::readFile(argv[3],inf)) {
  647. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  648. return 1;
  649. }
  650. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  651. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  652. } else if (!strcmp(argv[1],"verify")) {
  653. if (argc < 4) {
  654. idtoolPrintHelp(stdout,argv[0]);
  655. return 1;
  656. }
  657. Identity id = getIdFromArg(argv[2]);
  658. if (!id) {
  659. fprintf(stderr,"Identity argument invalid or file unreadable: %s"ZT_EOL_S,argv[2]);
  660. return 1;
  661. }
  662. std::string inf;
  663. if (!OSUtils::readFile(argv[3],inf)) {
  664. fprintf(stderr,"%s is not readable"ZT_EOL_S,argv[3]);
  665. return 1;
  666. }
  667. std::string signature(Utils::unhex(argv[4]));
  668. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  669. printf("%s signature valid"ZT_EOL_S,argv[3]);
  670. } else {
  671. fprintf(stderr,"%s signature check FAILED"ZT_EOL_S,argv[3]);
  672. return 1;
  673. }
  674. } else if (!strcmp(argv[1],"mkcom")) {
  675. if (argc < 3) {
  676. idtoolPrintHelp(stdout,argv[0]);
  677. return 1;
  678. }
  679. Identity id = getIdFromArg(argv[2]);
  680. if ((!id)||(!id.hasPrivate())) {
  681. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s"ZT_EOL_S,argv[2]);
  682. return 1;
  683. }
  684. CertificateOfMembership com;
  685. for(int a=3;a<argc;++a) {
  686. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  687. if (params.size() == 3) {
  688. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  689. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  690. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  691. com.setQualifier(qId,qValue,qMaxDelta);
  692. }
  693. }
  694. if (!com.sign(id)) {
  695. fprintf(stderr,"Signature of certificate of membership failed."ZT_EOL_S);
  696. return 1;
  697. }
  698. printf("%s",com.toString().c_str());
  699. } else {
  700. idtoolPrintHelp(stdout,argv[0]);
  701. return 1;
  702. }
  703. return 0;
  704. }
  705. /****************************************************************************/
  706. /* Unix helper functions and signal handlers */
  707. /****************************************************************************/
  708. #ifdef __UNIX_LIKE__
  709. static void _sighandlerHup(int sig)
  710. {
  711. }
  712. static void _sighandlerQuit(int sig)
  713. {
  714. OneService *s = zt1Service;
  715. if (s)
  716. s->terminate();
  717. else exit(0);
  718. }
  719. #endif
  720. /****************************************************************************/
  721. /* Windows helper functions and signal handlers */
  722. /****************************************************************************/
  723. #ifdef __WINDOWS__
  724. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  725. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  726. {
  727. switch(dwCtrlType) {
  728. case CTRL_C_EVENT:
  729. case CTRL_BREAK_EVENT:
  730. case CTRL_CLOSE_EVENT:
  731. case CTRL_SHUTDOWN_EVENT:
  732. OneService *s = zt1Service;
  733. if (s)
  734. s->terminate();
  735. return TRUE;
  736. }
  737. return FALSE;
  738. }
  739. static void _winPokeAHole()
  740. {
  741. char myPath[MAX_PATH];
  742. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  743. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  744. STARTUPINFOA startupInfo;
  745. PROCESS_INFORMATION processInfo;
  746. startupInfo.cb = sizeof(startupInfo);
  747. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  748. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  749. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  750. WaitForSingleObject(processInfo.hProcess,INFINITE);
  751. CloseHandle(processInfo.hProcess);
  752. CloseHandle(processInfo.hThread);
  753. }
  754. startupInfo.cb = sizeof(startupInfo);
  755. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  756. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  757. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  758. WaitForSingleObject(processInfo.hProcess,INFINITE);
  759. CloseHandle(processInfo.hProcess);
  760. CloseHandle(processInfo.hThread);
  761. }
  762. startupInfo.cb = sizeof(startupInfo);
  763. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  764. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  765. 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,CREATE_NO_WINDOW,NULL,NULL,&startupInfo,&processInfo)) {
  766. WaitForSingleObject(processInfo.hProcess,INFINITE);
  767. CloseHandle(processInfo.hProcess);
  768. CloseHandle(processInfo.hThread);
  769. }
  770. }
  771. }
  772. // Returns true if this is running as the local administrator
  773. static BOOL IsCurrentUserLocalAdministrator(void)
  774. {
  775. BOOL fReturn = FALSE;
  776. DWORD dwStatus;
  777. DWORD dwAccessMask;
  778. DWORD dwAccessDesired;
  779. DWORD dwACLSize;
  780. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  781. PACL pACL = NULL;
  782. PSID psidAdmin = NULL;
  783. HANDLE hToken = NULL;
  784. HANDLE hImpersonationToken = NULL;
  785. PRIVILEGE_SET ps;
  786. GENERIC_MAPPING GenericMapping;
  787. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  788. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  789. const DWORD ACCESS_READ = 1;
  790. const DWORD ACCESS_WRITE = 2;
  791. __try
  792. {
  793. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  794. {
  795. if (GetLastError() != ERROR_NO_TOKEN)
  796. __leave;
  797. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  798. __leave;
  799. }
  800. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  801. __leave;
  802. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  803. SECURITY_BUILTIN_DOMAIN_RID,
  804. DOMAIN_ALIAS_RID_ADMINS,
  805. 0, 0, 0, 0, 0, 0, &psidAdmin))
  806. __leave;
  807. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  808. if (psdAdmin == NULL)
  809. __leave;
  810. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  811. __leave;
  812. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  813. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  814. if (pACL == NULL)
  815. __leave;
  816. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  817. __leave;
  818. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  819. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  820. __leave;
  821. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  822. __leave;
  823. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  824. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  825. if (!IsValidSecurityDescriptor(psdAdmin))
  826. __leave;
  827. dwAccessDesired = ACCESS_READ;
  828. GenericMapping.GenericRead = ACCESS_READ;
  829. GenericMapping.GenericWrite = ACCESS_WRITE;
  830. GenericMapping.GenericExecute = 0;
  831. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  832. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  833. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  834. &fReturn))
  835. {
  836. fReturn = FALSE;
  837. __leave;
  838. }
  839. }
  840. __finally
  841. {
  842. // Clean up.
  843. if (pACL) LocalFree(pACL);
  844. if (psdAdmin) LocalFree(psdAdmin);
  845. if (psidAdmin) FreeSid(psidAdmin);
  846. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  847. if (hToken) CloseHandle (hToken);
  848. }
  849. return fReturn;
  850. }
  851. #endif // __WINDOWS__
  852. /****************************************************************************/
  853. /* main() and friends */
  854. /****************************************************************************/
  855. static void printHelp(const char *cn,FILE *out)
  856. {
  857. fprintf(out,
  858. "%s version %d.%d.%d" ZT_EOL_S,
  859. PROGRAM_NAME,
  860. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  861. fprintf(out,
  862. COPYRIGHT_NOTICE ZT_EOL_S
  863. LICENSE_GRANT ZT_EOL_S);
  864. std::string updateUrl(OneService::autoUpdateUrl());
  865. if (updateUrl.length())
  866. fprintf(out,"Automatic updates enabled:"ZT_EOL_S" %s"ZT_EOL_S" (all updates are securely authenticated by 256-bit ECDSA signature)"ZT_EOL_S""ZT_EOL_S,updateUrl.c_str());
  867. fprintf(out,"Usage: %s [-switches] [home directory]"ZT_EOL_S""ZT_EOL_S,cn);
  868. fprintf(out,"Available switches:"ZT_EOL_S);
  869. fprintf(out," -h - Display this help"ZT_EOL_S);
  870. fprintf(out," -v - Show version"ZT_EOL_S);
  871. fprintf(out," -U - Run as unprivileged user (skip privilege check)"ZT_EOL_S);
  872. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)"ZT_EOL_S);
  873. #ifdef __UNIX_LIKE__
  874. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)"ZT_EOL_S);
  875. #endif // __UNIX_LIKE__
  876. #ifdef __WINDOWS__
  877. fprintf(out," -C - Run from command line instead of as service (Windows)"ZT_EOL_S);
  878. fprintf(out," -I - Install Windows service (Windows)"ZT_EOL_S);
  879. fprintf(out," -R - Uninstall Windows service (Windows)"ZT_EOL_S);
  880. fprintf(out," -D - Remove all instances of Windows tap device (Windows)"ZT_EOL_S);
  881. #endif // __WINDOWS__
  882. fprintf(out," -i - Generate and manage identities (zerotier-idtool)"ZT_EOL_S);
  883. fprintf(out," -q - Query API (zerotier-cli)"ZT_EOL_S);
  884. }
  885. #ifdef __WINDOWS__
  886. int _tmain(int argc, _TCHAR* argv[])
  887. #else
  888. int main(int argc,char **argv)
  889. #endif
  890. {
  891. #ifdef __UNIX_LIKE__
  892. signal(SIGHUP,&_sighandlerHup);
  893. signal(SIGPIPE,SIG_IGN);
  894. signal(SIGUSR1,SIG_IGN);
  895. signal(SIGUSR2,SIG_IGN);
  896. signal(SIGALRM,SIG_IGN);
  897. signal(SIGINT,&_sighandlerQuit);
  898. signal(SIGTERM,&_sighandlerQuit);
  899. signal(SIGQUIT,&_sighandlerQuit);
  900. /* Ensure that there are no inherited file descriptors open from a previous
  901. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  902. * of it do not return, and should not do anything otherwise bad. */
  903. {
  904. int mfd = STDIN_FILENO;
  905. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  906. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  907. for(int f=mfd+1;f<1024;++f)
  908. ::close(f);
  909. }
  910. bool runAsDaemon = false;
  911. #endif // __UNIX_LIKE__
  912. #ifdef __WINDOWS__
  913. {
  914. WSADATA wsaData;
  915. WSAStartup(MAKEWORD(2,2),&wsaData);
  916. }
  917. #ifdef ZT_WIN_RUN_IN_CONSOLE
  918. bool winRunFromCommandLine = true;
  919. #else
  920. bool winRunFromCommandLine = false;
  921. #endif
  922. #endif // __WINDOWS__
  923. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  924. return idtool(argc,argv);
  925. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  926. return cli(argc,argv);
  927. std::string homeDir;
  928. unsigned int port = ZT_DEFAULT_PORT;
  929. bool skipRootCheck = false;
  930. for(int i=1;i<argc;++i) {
  931. if (argv[i][0] == '-') {
  932. switch(argv[i][1]) {
  933. case 'p': // port -- for both UDP and TCP, packets and control plane
  934. port = Utils::strToUInt(argv[i] + 2);
  935. if (port > 0xffff) {
  936. printHelp(argv[0],stdout);
  937. return 1;
  938. }
  939. break;
  940. #ifdef __UNIX_LIKE__
  941. case 'd': // Run in background as daemon
  942. runAsDaemon = true;
  943. break;
  944. #endif // __UNIX_LIKE__
  945. case 'U':
  946. skipRootCheck = true;
  947. break;
  948. case 'v': // Display version
  949. printf("%d.%d.%d"ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  950. return 0;
  951. case 'i': // Invoke idtool personality
  952. if (argv[i][2]) {
  953. printHelp(argv[0],stdout);
  954. return 0;
  955. } else return idtool(argc,argv);
  956. case 'q': // Invoke cli personality
  957. if (argv[i][2]) {
  958. printHelp(argv[0],stdout);
  959. return 0;
  960. } else return cli(argc,argv);
  961. #ifdef __WINDOWS__
  962. case 'C': // Run from command line instead of as Windows service
  963. winRunFromCommandLine = true;
  964. break;
  965. case 'I': { // Install this binary as a Windows service
  966. if (IsCurrentUserLocalAdministrator() != TRUE) {
  967. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  968. return 1;
  969. }
  970. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  971. if (ret.length()) {
  972. fprintf(stderr,"%s: unable to install service: %s"ZT_EOL_S,argv[0],ret.c_str());
  973. return 3;
  974. }
  975. return 0;
  976. } break;
  977. case 'R': { // Uninstall this binary as Windows service
  978. if (IsCurrentUserLocalAdministrator() != TRUE) {
  979. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  980. return 1;
  981. }
  982. std::string ret(UninstallService(ZT_SERVICE_NAME));
  983. if (ret.length()) {
  984. fprintf(stderr,"%s: unable to uninstall service: %s"ZT_EOL_S,argv[0],ret.c_str());
  985. return 3;
  986. }
  987. return 0;
  988. } break;
  989. case 'D': {
  990. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  991. if (err.length() > 0) {
  992. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s"ZT_EOL_S,argv[0],err.c_str());
  993. return 3;
  994. }
  995. return 0;
  996. } break;
  997. #endif // __WINDOWS__
  998. case 'h':
  999. case '?':
  1000. default:
  1001. printHelp(argv[0],stdout);
  1002. return 0;
  1003. }
  1004. } else {
  1005. if (homeDir.length()) {
  1006. printHelp(argv[0],stdout);
  1007. return 0;
  1008. } else {
  1009. homeDir = argv[i];
  1010. }
  1011. }
  1012. }
  1013. if (!homeDir.length())
  1014. homeDir = OneService::platformDefaultHomePath();
  1015. if (!homeDir.length()) {
  1016. fprintf(stderr,"%s: no home path specified and no platform default available"ZT_EOL_S,argv[0]);
  1017. return 1;
  1018. } else {
  1019. std::vector<std::string> hpsp(Utils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1020. std::string ptmp;
  1021. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1022. ptmp.push_back(ZT_PATH_SEPARATOR);
  1023. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1024. if (ptmp.length() > 0)
  1025. ptmp.push_back(ZT_PATH_SEPARATOR);
  1026. ptmp.append(*pi);
  1027. if ((*pi != ".")&&(*pi != "..")) {
  1028. if (!OSUtils::mkdir(ptmp))
  1029. throw std::runtime_error("home path does not exist, and could not create");
  1030. }
  1031. }
  1032. }
  1033. #ifdef __UNIX_LIKE__
  1034. #ifndef ZT_ONE_NO_ROOT_CHECK
  1035. if ((!skipRootCheck)&&(getuid() != 0)) {
  1036. fprintf(stderr,"%s: must be run as root (uid 0)"ZT_EOL_S,argv[0]);
  1037. return 1;
  1038. }
  1039. #endif // !ZT_ONE_NO_ROOT_CHECK
  1040. if (runAsDaemon) {
  1041. long p = (long)fork();
  1042. if (p < 0) {
  1043. fprintf(stderr,"%s: could not fork"ZT_EOL_S,argv[0]);
  1044. return 1;
  1045. } else if (p > 0)
  1046. return 0; // forked
  1047. // else p == 0, so we are daemonized
  1048. }
  1049. #endif // __UNIX_LIKE__
  1050. #ifdef __WINDOWS__
  1051. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1052. // when tap instances are created.
  1053. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1054. if (winRunFromCommandLine) {
  1055. // Running in "interactive" mode (mostly for debugging)
  1056. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1057. if (!skipRootCheck) {
  1058. fprintf(stderr,"%s: must be run as a local administrator."ZT_EOL_S,argv[0]);
  1059. return 1;
  1060. }
  1061. } else {
  1062. _winPokeAHole();
  1063. }
  1064. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1065. // continues on to ordinary command line execution code below...
  1066. } else {
  1067. // Running from service manager
  1068. _winPokeAHole();
  1069. ZeroTierOneService zt1Service;
  1070. if (CServiceBase::Run(zt1Service) == TRUE) {
  1071. return 0;
  1072. } else {
  1073. fprintf(stderr,"%s: unable to start service (try -h for help)"ZT_EOL_S,argv[0]);
  1074. return 1;
  1075. }
  1076. }
  1077. #endif // __WINDOWS__
  1078. #ifdef __UNIX_LIKE__
  1079. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1080. {
  1081. // Write .pid file to home folder
  1082. FILE *pf = fopen(pidPath.c_str(),"w");
  1083. if (pf) {
  1084. fprintf(pf,"%ld",(long)getpid());
  1085. fclose(pf);
  1086. }
  1087. }
  1088. #endif // __UNIX_LIKE__
  1089. unsigned int returnValue = 0;
  1090. for(;;) {
  1091. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1092. switch(zt1Service->run()) {
  1093. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1094. case OneService::ONE_NORMAL_TERMINATION:
  1095. break;
  1096. case OneService::ONE_UNRECOVERABLE_ERROR:
  1097. fprintf(stderr,"%s: fatal error: %s"ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  1098. returnValue = 1;
  1099. break;
  1100. case OneService::ONE_IDENTITY_COLLISION: {
  1101. delete zt1Service;
  1102. zt1Service = (OneService *)0;
  1103. std::string oldid;
  1104. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1105. if (oldid.length()) {
  1106. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1107. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1108. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1109. }
  1110. } continue; // restart!
  1111. }
  1112. break; // terminate loop -- normally we don't keep restarting
  1113. }
  1114. delete zt1Service;
  1115. zt1Service = (OneService *)0;
  1116. #ifdef __UNIX_LIKE__
  1117. OSUtils::rm(pidPath.c_str());
  1118. #endif
  1119. return returnValue;
  1120. }