one.cpp 39 KB

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