one.cpp 39 KB

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