one.cpp 35 KB

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