one.cpp 38 KB

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