one.cpp 38 KB

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