one.cpp 38 KB

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