one.cpp 39 KB

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