one.cpp 39 KB

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