one.cpp 36 KB

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