one.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  1. /*
  2. * Copyright (c)2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdint.h>
  17. #include <time.h>
  18. #include <errno.h>
  19. #include "node/Constants.hpp"
  20. #ifdef __WINDOWS__
  21. #include <WinSock2.h>
  22. #include <Windows.h>
  23. #include <tchar.h>
  24. #include <wchar.h>
  25. #include <lmcons.h>
  26. #include <newdev.h>
  27. #include <atlbase.h>
  28. #include "osdep/WindowsEthernetTap.hpp"
  29. #include "windows/ZeroTierOne/ServiceInstaller.h"
  30. #include "windows/ZeroTierOne/ServiceBase.h"
  31. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  32. #else
  33. #include <unistd.h>
  34. #include <pwd.h>
  35. #include <fcntl.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. #include <sys/uio.h>
  39. #include <dirent.h>
  40. #include <signal.h>
  41. #ifdef __LINUX__
  42. #include <sys/prctl.h>
  43. #include <sys/syscall.h>
  44. #include <sys/wait.h>
  45. #ifndef ZT_NO_CAPABILITIES
  46. #include <linux/capability.h>
  47. #include <linux/securebits.h>
  48. #endif
  49. #endif
  50. #endif
  51. #include <string>
  52. #include <stdexcept>
  53. #include <iostream>
  54. #include <sstream>
  55. #include <algorithm>
  56. #include "version.h"
  57. #include "include/ZeroTierOne.h"
  58. #include "node/Identity.hpp"
  59. #include "node/CertificateOfMembership.hpp"
  60. #include "node/Utils.hpp"
  61. #include "node/NetworkController.hpp"
  62. #include "node/Buffer.hpp"
  63. #include "node/World.hpp"
  64. #include "osdep/OSUtils.hpp"
  65. #include "osdep/Http.hpp"
  66. #include "osdep/Thread.hpp"
  67. #include "node/BondController.hpp"
  68. #include "service/OneService.hpp"
  69. #include "ext/json/json.hpp"
  70. #define ZT_PID_PATH "zerotier-one.pid"
  71. using namespace ZeroTier;
  72. static OneService *volatile zt1Service = (OneService *)0;
  73. #define PROGRAM_NAME "ZeroTier One"
  74. #define COPYRIGHT_NOTICE "Copyright (c) 2020 ZeroTier, Inc."
  75. #define LICENSE_GRANT "Licensed under the ZeroTier BSL 1.1 (see LICENSE.txt)"
  76. /****************************************************************************/
  77. /* zerotier-cli personality */
  78. /****************************************************************************/
  79. // This is getting deprecated soon in favor of the stuff in cli/
  80. static void cliPrintHelp(const char *pn,FILE *out)
  81. {
  82. fprintf(out,
  83. "%s version %d.%d.%d build %d (platform %d arch %d)" ZT_EOL_S,
  84. PROGRAM_NAME,
  85. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION, ZEROTIER_ONE_VERSION_BUILD,
  86. ZT_BUILD_PLATFORM, ZT_BUILD_ARCHITECTURE);
  87. fprintf(out,
  88. COPYRIGHT_NOTICE ZT_EOL_S
  89. LICENSE_GRANT ZT_EOL_S);
  90. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  91. fprintf(out,"Available switches:" ZT_EOL_S);
  92. fprintf(out," -h - Display this help" ZT_EOL_S);
  93. fprintf(out," -v - Show version" ZT_EOL_S);
  94. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  95. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  96. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  97. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  98. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  99. fprintf(out," info - Display status info" ZT_EOL_S);
  100. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  101. fprintf(out," peers - List all peers (prettier)" ZT_EOL_S);
  102. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  103. fprintf(out," join <network ID> - Join a network" ZT_EOL_S);
  104. fprintf(out," leave <network ID> - Leave a network" ZT_EOL_S);
  105. fprintf(out," set <network ID> <setting> - Set a network setting" ZT_EOL_S);
  106. fprintf(out," get <network ID> <setting> - Get a network setting" ZT_EOL_S);
  107. fprintf(out," listmoons - List moons (federated root sets)" ZT_EOL_S);
  108. fprintf(out," orbit <world ID> <seed> - Join a moon via any member root" ZT_EOL_S);
  109. fprintf(out," deorbit <world ID> - Leave a moon" ZT_EOL_S);
  110. fprintf(out,ZT_EOL_S"Available settings:" ZT_EOL_S);
  111. fprintf(out," Settings to use with [get/set] may include property names from " ZT_EOL_S);
  112. fprintf(out," the JSON output of \"zerotier-cli -j listnetworks\". Additionally, " ZT_EOL_S);
  113. fprintf(out," (ip, ip4, ip6, ip6plane, and ip6prefix can be used). For instance:" ZT_EOL_S);
  114. fprintf(out," zerotier-cli get <network ID> ip6plane will return the 6PLANE address" ZT_EOL_S);
  115. fprintf(out," assigned to this node." ZT_EOL_S);
  116. }
  117. static std::string cliFixJsonCRs(const std::string &s)
  118. {
  119. std::string r;
  120. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  121. if (*c == '\n')
  122. r.append(ZT_EOL_S);
  123. else r.push_back(*c);
  124. }
  125. return r;
  126. }
  127. #ifdef __WINDOWS__
  128. static int cli(int argc, _TCHAR* argv[])
  129. #else
  130. static int cli(int argc,char **argv)
  131. #endif
  132. {
  133. unsigned int port = 0;
  134. std::string homeDir,command,arg1,arg2,authToken;
  135. std::string ip("127.0.0.1");
  136. bool json = false;
  137. for(int i=1;i<argc;++i) {
  138. if (argv[i][0] == '-') {
  139. switch(argv[i][1]) {
  140. case 'q': // ignore -q used to invoke this personality
  141. if (argv[i][2]) {
  142. cliPrintHelp(argv[0],stdout);
  143. return 1;
  144. }
  145. break;
  146. case 'j':
  147. if (argv[i][2]) {
  148. cliPrintHelp(argv[0],stdout);
  149. return 1;
  150. }
  151. json = true;
  152. break;
  153. case 'p':
  154. port = Utils::strToUInt(argv[i] + 2);
  155. if ((port > 0xffff)||(port == 0)) {
  156. cliPrintHelp(argv[0],stdout);
  157. return 1;
  158. }
  159. break;
  160. case 'D':
  161. if (argv[i][2]) {
  162. homeDir = argv[i] + 2;
  163. } else {
  164. cliPrintHelp(argv[0],stdout);
  165. return 1;
  166. }
  167. break;
  168. case 'H':
  169. if (argv[i][2]) {
  170. ip = argv[i] + 2;
  171. } else {
  172. cliPrintHelp(argv[0],stdout);
  173. return 1;
  174. }
  175. break;
  176. case 'T':
  177. if (argv[i][2]) {
  178. authToken = argv[i] + 2;
  179. } else {
  180. cliPrintHelp(argv[0],stdout);
  181. return 1;
  182. }
  183. break;
  184. case 'v':
  185. if (argv[i][2]) {
  186. cliPrintHelp(argv[0],stdout);
  187. return 1;
  188. }
  189. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  190. return 0;
  191. case 'h':
  192. case '?':
  193. default:
  194. cliPrintHelp(argv[0],stdout);
  195. return 0;
  196. }
  197. } else {
  198. if (arg1.length())
  199. arg2 = argv[i];
  200. else if (command.length())
  201. arg1 = argv[i];
  202. else command = argv[i];
  203. }
  204. }
  205. if (!homeDir.length())
  206. homeDir = OneService::platformDefaultHomePath();
  207. // TODO: cleanup this logic
  208. // A lot of generic CLI errors land here; missing admin rights cause a bit of this.
  209. if ((!port)||(!authToken.length())) {
  210. if (!homeDir.length()) {
  211. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  212. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  213. return 2;
  214. }
  215. if (!port) {
  216. std::string portStr;
  217. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  218. port = Utils::strToUInt(portStr.c_str());
  219. if ((port == 0)||(port > 0xffff)) {
  220. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  221. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  222. return 2;
  223. }
  224. }
  225. if (!authToken.length()) {
  226. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  227. #ifdef __UNIX_LIKE__
  228. if (!authToken.length()) {
  229. const char *hd = getenv("HOME");
  230. if (hd) {
  231. char p[4096];
  232. #ifdef __APPLE__
  233. OSUtils::ztsnprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  234. #else
  235. OSUtils::ztsnprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  236. #endif
  237. OSUtils::readFile(p,authToken);
  238. }
  239. }
  240. #endif
  241. if (!authToken.length()) {
  242. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  243. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  244. return 2;
  245. }
  246. }
  247. }
  248. InetAddress addr;
  249. {
  250. char addrtmp[256];
  251. OSUtils::ztsnprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  252. addr = InetAddress(addrtmp);
  253. }
  254. std::map<std::string,std::string> requestHeaders;
  255. std::map<std::string,std::string> responseHeaders;
  256. std::string responseBody;
  257. requestHeaders["X-ZT1-Auth"] = authToken;
  258. if ((command.length() > 0)&&(command[0] == '/')) {
  259. unsigned int scode = Http::GET(
  260. 1024 * 1024 * 16,
  261. 60000,
  262. (const struct sockaddr *)&addr,
  263. command.c_str(),
  264. requestHeaders,
  265. responseHeaders,
  266. responseBody);
  267. if (scode == 200) {
  268. printf("%s", cliFixJsonCRs(responseBody).c_str());
  269. return 0;
  270. } else {
  271. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  272. return 1;
  273. }
  274. } else if ((command == "info")||(command == "status")) {
  275. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  276. if (scode == 0) {
  277. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  278. return 1;
  279. }
  280. nlohmann::json j;
  281. try {
  282. j = OSUtils::jsonParse(responseBody);
  283. } catch (std::exception &exc) {
  284. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  285. return 1;
  286. } catch ( ... ) {
  287. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  288. return 1;
  289. }
  290. if (scode == 200) {
  291. if (json) {
  292. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  293. } else {
  294. if (j.is_object()) {
  295. printf("200 info %s %s %s" ZT_EOL_S,
  296. OSUtils::jsonString(j["address"],"-").c_str(),
  297. OSUtils::jsonString(j["version"],"-").c_str(),
  298. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  299. }
  300. }
  301. return 0;
  302. } else {
  303. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  304. return 1;
  305. }
  306. } else if (command == "listpeers") {
  307. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  308. if (scode == 0) {
  309. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  310. return 1;
  311. }
  312. nlohmann::json j;
  313. try {
  314. j = OSUtils::jsonParse(responseBody);
  315. } catch (std::exception &exc) {
  316. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  317. return 1;
  318. } catch ( ... ) {
  319. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  320. return 1;
  321. }
  322. if (scode == 200) {
  323. if (json) {
  324. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  325. } else {
  326. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  327. if (j.is_array()) {
  328. for(unsigned long k=0;k<j.size();++k) {
  329. nlohmann::json &p = j[k];
  330. std::string bestPath;
  331. nlohmann::json &paths = p["paths"];
  332. if (paths.is_array()) {
  333. for(unsigned long i=0;i<paths.size();++i) {
  334. nlohmann::json &path = paths[i];
  335. if (path["preferred"]) {
  336. char tmp[256];
  337. std::string addr = path["address"];
  338. const int64_t now = OSUtils::now();
  339. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s;%lld;%lld",addr.c_str(),now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"]);
  340. bestPath = tmp;
  341. break;
  342. }
  343. }
  344. }
  345. if (bestPath.length() == 0) bestPath = "-";
  346. char ver[128];
  347. int64_t vmaj = p["versionMajor"];
  348. int64_t vmin = p["versionMinor"];
  349. int64_t vrev = p["versionRev"];
  350. if (vmaj >= 0) {
  351. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  352. } else {
  353. ver[0] = '-';
  354. ver[1] = (char)0;
  355. }
  356. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  357. OSUtils::jsonString(p["address"],"-").c_str(),
  358. bestPath.c_str(),
  359. (int)OSUtils::jsonInt(p["latency"],0),
  360. ver,
  361. OSUtils::jsonString(p["role"],"-").c_str());
  362. }
  363. }
  364. }
  365. return 0;
  366. } else {
  367. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  368. return 1;
  369. }
  370. } else if (command == "peers") {
  371. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  372. if (scode == 0) {
  373. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  374. return 1;
  375. }
  376. nlohmann::json j;
  377. try {
  378. j = OSUtils::jsonParse(responseBody);
  379. } catch (std::exception &exc) {
  380. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  381. return 1;
  382. } catch ( ... ) {
  383. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  384. return 1;
  385. }
  386. if (scode == 200) {
  387. if (json) {
  388. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  389. } else {
  390. printf("200 peers\n<ztaddr> <ver> <role> <lat> <link> <lastTX> <lastRX> <path>" ZT_EOL_S);
  391. if (j.is_array()) {
  392. for(unsigned long k=0;k<j.size();++k) {
  393. nlohmann::json &p = j[k];
  394. std::string bestPath;
  395. nlohmann::json &paths = p["paths"];
  396. if (paths.is_array()) {
  397. for(unsigned long i=0;i<paths.size();++i) {
  398. nlohmann::json &path = paths[i];
  399. if (path["preferred"]) {
  400. char tmp[256];
  401. std::string addr = path["address"];
  402. const int64_t now = OSUtils::now();
  403. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%-8lld %-8lld %s",now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"],addr.c_str());
  404. bestPath = std::string("DIRECT ") + tmp;
  405. break;
  406. }
  407. }
  408. }
  409. if (bestPath.length() == 0) bestPath = "RELAY";
  410. char ver[128];
  411. int64_t vmaj = p["versionMajor"];
  412. int64_t vmin = p["versionMinor"];
  413. int64_t vrev = p["versionRev"];
  414. if (vmaj >= 0) {
  415. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  416. } else {
  417. ver[0] = '-';
  418. ver[1] = (char)0;
  419. }
  420. printf("%s %-6s %-6s %5d %s" ZT_EOL_S,
  421. OSUtils::jsonString(p["address"],"-").c_str(),
  422. ver,
  423. OSUtils::jsonString(p["role"],"-").c_str(),
  424. (int)OSUtils::jsonInt(p["latency"],0),
  425. bestPath.c_str());
  426. }
  427. }
  428. }
  429. return 0;
  430. } else {
  431. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  432. return 1;
  433. }
  434. } else if (command == "listbonds") {
  435. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  436. if (scode == 0) {
  437. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  438. return 1;
  439. }
  440. nlohmann::json j;
  441. try {
  442. j = OSUtils::jsonParse(responseBody);
  443. } catch (std::exception &exc) {
  444. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  445. return 1;
  446. } catch ( ... ) {
  447. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  448. return 1;
  449. }
  450. if (scode == 200) {
  451. if (json) {
  452. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  453. } else {
  454. bool bFoundBond = false;
  455. printf(" <peer> <bondtype> <status> <links>" ZT_EOL_S);
  456. if (j.is_array()) {
  457. for(unsigned long k=0;k<j.size();++k) {
  458. nlohmann::json &p = j[k];
  459. bool isBonded = p["isBonded"];
  460. int8_t bondingPolicy = p["bondingPolicy"];
  461. bool isHealthy = p["isHealthy"];
  462. int8_t numAliveLinks = p["numAliveLinks"];
  463. int8_t numTotalLinks = p["numTotalLinks"];
  464. if (isBonded) {
  465. bFoundBond = true;
  466. std::string healthStr;
  467. if (isHealthy) {
  468. healthStr = "HEALTHY";
  469. } else {
  470. healthStr = "DEGRADED";
  471. }
  472. std::string policyStr = "none";
  473. if (bondingPolicy >= ZT_BONDING_POLICY_NONE && bondingPolicy <= ZT_BONDING_POLICY_BALANCE_AWARE) {
  474. policyStr = BondController::getPolicyStrByCode(bondingPolicy);
  475. }
  476. printf("%10s %32s %8s %d/%d" ZT_EOL_S,
  477. OSUtils::jsonString(p ["address"],"-").c_str(),
  478. policyStr.c_str(),
  479. healthStr.c_str(),
  480. numAliveLinks,
  481. numTotalLinks);
  482. }
  483. }
  484. }
  485. if (!bFoundBond) {
  486. printf(" NONE\t\t\t\tNONE\t NONE NONE" ZT_EOL_S);
  487. }
  488. }
  489. return 0;
  490. } else {
  491. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  492. return 1;
  493. }
  494. } else if (command == "listnetworks") {
  495. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  496. if (scode == 0) {
  497. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  498. return 1;
  499. }
  500. nlohmann::json j;
  501. try {
  502. j = OSUtils::jsonParse(responseBody);
  503. } catch (std::exception &exc) {
  504. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  505. return 1;
  506. } catch ( ... ) {
  507. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  508. return 1;
  509. }
  510. if (scode == 200) {
  511. if (json) {
  512. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  513. } else {
  514. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  515. if (j.is_array()) {
  516. for(unsigned long i=0;i<j.size();++i) {
  517. nlohmann::json &n = j[i];
  518. if (n.is_object()) {
  519. std::string aa;
  520. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  521. if (assignedAddresses.is_array()) {
  522. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  523. nlohmann::json &addr = assignedAddresses[j];
  524. if (addr.is_string()) {
  525. if (aa.length() > 0) aa.push_back(',');
  526. aa.append(addr.get<std::string>());
  527. }
  528. }
  529. }
  530. if (aa.length() == 0) aa = "-";
  531. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  532. OSUtils::jsonString(n["nwid"],"-").c_str(),
  533. OSUtils::jsonString(n["name"],"-").c_str(),
  534. OSUtils::jsonString(n["mac"],"-").c_str(),
  535. OSUtils::jsonString(n["status"],"-").c_str(),
  536. OSUtils::jsonString(n["type"],"-").c_str(),
  537. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  538. aa.c_str());
  539. }
  540. }
  541. }
  542. }
  543. return 0;
  544. } else {
  545. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  546. return 1;
  547. }
  548. } else if (command == "join") {
  549. if (arg1.length() != 16) {
  550. printf("invalid network id" ZT_EOL_S);
  551. return 2;
  552. }
  553. requestHeaders["Content-Type"] = "application/json";
  554. requestHeaders["Content-Length"] = "2";
  555. unsigned int scode = Http::POST(
  556. 1024 * 1024 * 16,
  557. 60000,
  558. (const struct sockaddr *)&addr,
  559. (std::string("/network/") + arg1).c_str(),
  560. requestHeaders,
  561. "{}",
  562. 2,
  563. responseHeaders,
  564. responseBody);
  565. if (scode == 200) {
  566. if (json) {
  567. printf("%s",cliFixJsonCRs(responseBody).c_str());
  568. } else {
  569. printf("200 join OK" ZT_EOL_S);
  570. }
  571. return 0;
  572. } else {
  573. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  574. return 1;
  575. }
  576. } else if (command == "leave") {
  577. if (arg1.length() != 16) {
  578. printf("invalid network id" ZT_EOL_S);
  579. return 2;
  580. }
  581. unsigned int scode = Http::DEL(
  582. 1024 * 1024 * 16,
  583. 60000,
  584. (const struct sockaddr *)&addr,
  585. (std::string("/network/") + arg1).c_str(),
  586. requestHeaders,
  587. responseHeaders,
  588. responseBody);
  589. if (scode == 200) {
  590. if (json) {
  591. printf("%s",cliFixJsonCRs(responseBody).c_str());
  592. } else {
  593. printf("200 leave OK" ZT_EOL_S);
  594. }
  595. return 0;
  596. } else {
  597. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  598. return 1;
  599. }
  600. } else if (command == "listmoons") {
  601. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/moon",requestHeaders,responseHeaders,responseBody);
  602. if (scode == 0) {
  603. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  604. return 1;
  605. }
  606. nlohmann::json j;
  607. try {
  608. j = OSUtils::jsonParse(responseBody);
  609. } catch (std::exception &exc) {
  610. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  611. return 1;
  612. } catch ( ... ) {
  613. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  614. return 1;
  615. }
  616. if (scode == 200) {
  617. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  618. return 0;
  619. } else {
  620. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  621. return 1;
  622. }
  623. } else if (command == "orbit") {
  624. const uint64_t worldId = Utils::hexStrToU64(arg1.c_str());
  625. const uint64_t seed = Utils::hexStrToU64(arg2.c_str());
  626. if ((worldId)&&(seed)) {
  627. char jsons[1024];
  628. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"seed\":\"%s\"}",arg2.c_str());
  629. char cl[128];
  630. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  631. requestHeaders["Content-Type"] = "application/json";
  632. requestHeaders["Content-Length"] = cl;
  633. unsigned int scode = Http::POST(
  634. 1024 * 1024 * 16,
  635. 60000,
  636. (const struct sockaddr *)&addr,
  637. (std::string("/moon/") + arg1).c_str(),
  638. requestHeaders,
  639. jsons,
  640. (unsigned long)strlen(jsons),
  641. responseHeaders,
  642. responseBody);
  643. if (scode == 200) {
  644. printf("200 orbit OK" ZT_EOL_S);
  645. return 0;
  646. } else {
  647. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  648. return 1;
  649. }
  650. }
  651. } else if (command == "deorbit") {
  652. unsigned int scode = Http::DEL(
  653. 1024 * 1024 * 16,
  654. 60000,
  655. (const struct sockaddr *)&addr,
  656. (std::string("/moon/") + arg1).c_str(),
  657. requestHeaders,
  658. responseHeaders,
  659. responseBody);
  660. if (scode == 200) {
  661. if (json) {
  662. printf("%s",cliFixJsonCRs(responseBody).c_str());
  663. } else {
  664. printf("200 deorbit OK" ZT_EOL_S);
  665. }
  666. return 0;
  667. } else {
  668. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  669. return 1;
  670. }
  671. } else if (command == "set") {
  672. if (arg1.length() != 16) {
  673. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  674. return 2;
  675. }
  676. if (!arg2.length()) {
  677. fprintf(stderr,"invalid format: include a property name to set\n");
  678. return 2;
  679. }
  680. std::size_t eqidx = arg2.find('=');
  681. if (eqidx != std::string::npos) {
  682. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")||(arg2.substr(0,eqidx) == "allowDNS")) {
  683. char jsons[1024];
  684. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  685. arg2.substr(0,eqidx).c_str(),
  686. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  687. char cl[128];
  688. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  689. requestHeaders["Content-Type"] = "application/json";
  690. requestHeaders["Content-Length"] = cl;
  691. unsigned int scode = Http::POST(
  692. 1024 * 1024 * 16,
  693. 60000,
  694. (const struct sockaddr *)&addr,
  695. (std::string("/network/") + arg1).c_str(),
  696. requestHeaders,
  697. jsons,
  698. (unsigned long)strlen(jsons),
  699. responseHeaders,
  700. responseBody);
  701. if (scode == 200) {
  702. printf("%s",cliFixJsonCRs(responseBody).c_str());
  703. return 0;
  704. } else {
  705. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  706. return 1;
  707. }
  708. }
  709. } else {
  710. cliPrintHelp(argv[0],stderr);
  711. return 2;
  712. }
  713. } else if (command == "get") {
  714. if (arg1.length() != 16) {
  715. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  716. return 2;
  717. }
  718. if (!arg2.length()) {
  719. fprintf(stderr,"invalid format: include a property name to get\n");
  720. return 2;
  721. }
  722. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  723. if (scode == 0) {
  724. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  725. return 1;
  726. }
  727. nlohmann::json j;
  728. try {
  729. j = OSUtils::jsonParse(responseBody);
  730. } catch (std::exception &exc) {
  731. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  732. return 1;
  733. } catch ( ... ) {
  734. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  735. return 1;
  736. }
  737. bool bNetworkFound = false;
  738. if (j.is_array()) {
  739. for(unsigned long i=0;i<j.size();++i) {
  740. nlohmann::json &n = j[i];
  741. if (n.is_object()) {
  742. if (n["id"] == arg1) {
  743. bNetworkFound = true;
  744. std::string aa;
  745. if (arg2 != "ip" && arg2 != "ip4" && arg2 != "ip6" && arg2 != "ip6plane" && arg2 != "ip6prefix") {
  746. aa.append(OSUtils::jsonString(n[arg2],"-")); // Standard network property field
  747. if (aa == "-") {
  748. printf("error, unknown property name\n");
  749. break;
  750. }
  751. printf("%s\n",aa.c_str());
  752. break;
  753. }
  754. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  755. if (assignedAddresses.is_array()) {
  756. int matchingIdxs[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
  757. int addressCountOfType = 0;
  758. for (int k = 0; k<std::min(ZT_MAX_ZT_ASSIGNED_ADDRESSES, (int)assignedAddresses.size());++k) {
  759. nlohmann::json &addr = assignedAddresses[k];
  760. if ((arg2 == "ip4" && addr.get<std::string>().find(".") != std::string::npos)
  761. || ((arg2.find("ip6") == 0) && addr.get<std::string>().find(":") != std::string::npos)
  762. || (arg2 == "ip")
  763. ) {
  764. matchingIdxs[addressCountOfType++] = k;
  765. }
  766. }
  767. for (int k=0; k<addressCountOfType; k++) {
  768. nlohmann::json &addr = assignedAddresses[matchingIdxs[k]];
  769. if (!addr.is_string()) {
  770. continue;
  771. }
  772. if (arg2.find("ip6p") == 0) {
  773. if (arg2 == "ip6plane") {
  774. if (addr.get<std::string>().find("fc") == 0) {
  775. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  776. if (k < addressCountOfType-1) aa.append("\n");
  777. }
  778. }
  779. if (arg2 == "ip6prefix") {
  780. if (addr.get<std::string>().find("fc") == 0) {
  781. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")).substr(0,24));
  782. if (k < addressCountOfType-1) aa.append("\n");
  783. }
  784. }
  785. }
  786. else {
  787. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  788. if (k < addressCountOfType-1) aa.append("\n");
  789. }
  790. }
  791. }
  792. printf("%s\n",aa.c_str());
  793. }
  794. }
  795. }
  796. }
  797. if (!bNetworkFound) {
  798. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  799. }
  800. if (scode == 200) {
  801. return 0;
  802. } else {
  803. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  804. return 1;
  805. }
  806. } else if (command == "dump") {
  807. std::stringstream dump;
  808. dump << "zerotier version: " << ZEROTIER_ONE_VERSION_MAJOR << "."
  809. << ZEROTIER_ONE_VERSION_MINOR << "." << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S << ZT_EOL_S;
  810. // grab status
  811. dump << "status" << ZT_EOL_S << "------" << ZT_EOL_S;
  812. unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  813. if (scode != 200) {
  814. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  815. return 1;
  816. }
  817. dump << responseBody << ZT_EOL_S;
  818. responseHeaders.clear();
  819. responseBody = "";
  820. // grab network list
  821. dump << ZT_EOL_S << "networks" << ZT_EOL_S << "--------" << ZT_EOL_S;
  822. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  823. if (scode != 200) {
  824. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  825. return 1;
  826. }
  827. dump << responseBody << ZT_EOL_S;
  828. responseHeaders.clear();
  829. responseBody = "";
  830. // list peers
  831. dump << ZT_EOL_S << "peers" << ZT_EOL_S << "-----" << ZT_EOL_S;
  832. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  833. if (scode != 200) {
  834. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  835. return 1;
  836. }
  837. dump << responseBody << ZT_EOL_S;
  838. // get bonds
  839. dump << ZT_EOL_S << "bonds" << ZT_EOL_S << "-----" << ZT_EOL_S;
  840. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  841. if (scode != 200) {
  842. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  843. return 1;
  844. }
  845. dump << responseBody << ZT_EOL_S;
  846. responseHeaders.clear();
  847. responseBody = "";
  848. fprintf(stderr, "%s", dump.str().c_str());
  849. } else {
  850. cliPrintHelp(argv[0],stderr);
  851. return 0;
  852. }
  853. return 0;
  854. }
  855. /****************************************************************************/
  856. /* zerotier-idtool personality */
  857. /****************************************************************************/
  858. static void idtoolPrintHelp(FILE *out,const char *pn)
  859. {
  860. fprintf(out,
  861. "%s version %d.%d.%d" ZT_EOL_S,
  862. PROGRAM_NAME,
  863. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  864. fprintf(out,
  865. COPYRIGHT_NOTICE ZT_EOL_S
  866. LICENSE_GRANT ZT_EOL_S);
  867. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  868. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  869. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  870. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  871. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  872. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  873. fprintf(out," initmoon <identity.public of first seed>" ZT_EOL_S);
  874. fprintf(out," genmoon <moon json>" ZT_EOL_S);
  875. }
  876. static Identity getIdFromArg(char *arg)
  877. {
  878. Identity id;
  879. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  880. if (id.fromString(arg))
  881. return id;
  882. } else { // identity is to be read from a file
  883. std::string idser;
  884. if (OSUtils::readFile(arg,idser)) {
  885. if (id.fromString(idser.c_str()))
  886. return id;
  887. }
  888. }
  889. return Identity();
  890. }
  891. #ifdef __WINDOWS__
  892. static int idtool(int argc, _TCHAR* argv[])
  893. #else
  894. static int idtool(int argc,char **argv)
  895. #endif
  896. {
  897. if (argc < 2) {
  898. idtoolPrintHelp(stdout,argv[0]);
  899. return 1;
  900. }
  901. if (!strcmp(argv[1],"generate")) {
  902. uint64_t vanity = 0;
  903. int vanityBits = 0;
  904. if (argc >= 5) {
  905. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  906. vanityBits = 4 * (int)strlen(argv[4]);
  907. if (vanityBits > 40)
  908. vanityBits = 40;
  909. }
  910. Identity id;
  911. for(;;) {
  912. id.generate();
  913. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  914. if (vanityBits > 0) {
  915. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  916. }
  917. break;
  918. } else {
  919. 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)));
  920. }
  921. }
  922. char idtmp[1024];
  923. std::string idser = id.toString(true,idtmp);
  924. if (argc >= 3) {
  925. if (!OSUtils::writeFile(argv[2],idser)) {
  926. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  927. return 1;
  928. } else printf("%s written" ZT_EOL_S,argv[2]);
  929. if (argc >= 4) {
  930. idser = id.toString(false,idtmp);
  931. if (!OSUtils::writeFile(argv[3],idser)) {
  932. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  933. return 1;
  934. } else printf("%s written" ZT_EOL_S,argv[3]);
  935. }
  936. } else printf("%s",idser.c_str());
  937. } else if (!strcmp(argv[1],"validate")) {
  938. if (argc < 3) {
  939. idtoolPrintHelp(stdout,argv[0]);
  940. return 1;
  941. }
  942. Identity id = getIdFromArg(argv[2]);
  943. if (!id) {
  944. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  945. return 1;
  946. }
  947. if (!id.locallyValidate()) {
  948. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  949. return 1;
  950. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  951. } else if (!strcmp(argv[1],"getpublic")) {
  952. if (argc < 3) {
  953. idtoolPrintHelp(stdout,argv[0]);
  954. return 1;
  955. }
  956. Identity id = getIdFromArg(argv[2]);
  957. if (!id) {
  958. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  959. return 1;
  960. }
  961. char idtmp[1024];
  962. printf("%s",id.toString(false,idtmp));
  963. } else if (!strcmp(argv[1],"sign")) {
  964. if (argc < 4) {
  965. idtoolPrintHelp(stdout,argv[0]);
  966. return 1;
  967. }
  968. Identity id = getIdFromArg(argv[2]);
  969. if (!id) {
  970. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  971. return 1;
  972. }
  973. if (!id.hasPrivate()) {
  974. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  975. return 1;
  976. }
  977. std::string inf;
  978. if (!OSUtils::readFile(argv[3],inf)) {
  979. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  980. return 1;
  981. }
  982. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  983. char hexbuf[1024];
  984. printf("%s",Utils::hex(signature.data,ZT_C25519_SIGNATURE_LEN,hexbuf));
  985. } else if (!strcmp(argv[1],"verify")) {
  986. if (argc < 5) {
  987. idtoolPrintHelp(stdout,argv[0]);
  988. return 1;
  989. }
  990. Identity id = getIdFromArg(argv[2]);
  991. if (!id) {
  992. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  993. return 1;
  994. }
  995. std::string inf;
  996. if (!OSUtils::readFile(argv[3],inf)) {
  997. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  998. return 1;
  999. }
  1000. char buf[4096];
  1001. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  1002. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  1003. printf("%s signature valid" ZT_EOL_S,argv[3]);
  1004. } else {
  1005. signature.clear();
  1006. if (OSUtils::readFile(argv[4],signature)) {
  1007. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  1008. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  1009. printf("%s signature valid" ZT_EOL_S,argv[3]);
  1010. } else {
  1011. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  1012. return 1;
  1013. }
  1014. } else {
  1015. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  1016. return 1;
  1017. }
  1018. }
  1019. } else if (!strcmp(argv[1],"initmoon")) {
  1020. if (argc < 3) {
  1021. idtoolPrintHelp(stdout,argv[0]);
  1022. } else {
  1023. const Identity id = getIdFromArg(argv[2]);
  1024. if (!id) {
  1025. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  1026. return 1;
  1027. }
  1028. C25519::Pair kp(C25519::generate());
  1029. char idtmp[4096];
  1030. nlohmann::json mj;
  1031. mj["objtype"] = "world";
  1032. mj["worldType"] = "moon";
  1033. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,ZT_C25519_PUBLIC_KEY_LEN,idtmp);
  1034. mj["signingKey_SECRET"] = Utils::hex(kp.priv.data,ZT_C25519_PRIVATE_KEY_LEN,idtmp);
  1035. mj["id"] = id.address().toString(idtmp);
  1036. nlohmann::json seedj;
  1037. seedj["identity"] = id.toString(false,idtmp);
  1038. seedj["stableEndpoints"] = nlohmann::json::array();
  1039. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  1040. std::string mjd(OSUtils::jsonDump(mj));
  1041. printf("%s" ZT_EOL_S,mjd.c_str());
  1042. }
  1043. } else if (!strcmp(argv[1],"genmoon")) {
  1044. if (argc < 3) {
  1045. idtoolPrintHelp(stdout,argv[0]);
  1046. } else {
  1047. std::string buf;
  1048. if (!OSUtils::readFile(argv[2],buf)) {
  1049. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  1050. return 1;
  1051. }
  1052. nlohmann::json mj(OSUtils::jsonParse(buf));
  1053. const uint64_t id = Utils::hexStrToU64(OSUtils::jsonString(mj["id"],"0").c_str());
  1054. if (!id) {
  1055. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  1056. return 1;
  1057. }
  1058. World::Type t;
  1059. if (mj["worldType"] == "moon") {
  1060. t = World::TYPE_MOON;
  1061. } else if (mj["worldType"] == "planet") {
  1062. t = World::TYPE_PLANET;
  1063. } else {
  1064. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  1065. return 1;
  1066. }
  1067. C25519::Pair signingKey;
  1068. C25519::Public updatesMustBeSignedBy;
  1069. Utils::unhex(OSUtils::jsonString(mj["signingKey"],"").c_str(),signingKey.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  1070. Utils::unhex(OSUtils::jsonString(mj["signingKey_SECRET"],"").c_str(),signingKey.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  1071. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],"").c_str(),updatesMustBeSignedBy.data,ZT_C25519_PUBLIC_KEY_LEN);
  1072. std::vector<World::Root> roots;
  1073. nlohmann::json &rootsj = mj["roots"];
  1074. if (rootsj.is_array()) {
  1075. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  1076. nlohmann::json &r = rootsj[i];
  1077. if (r.is_object()) {
  1078. roots.push_back(World::Root());
  1079. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],"").c_str());
  1080. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  1081. if (stableEndpointsj.is_array()) {
  1082. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  1083. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"").c_str()));
  1084. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  1085. }
  1086. }
  1087. }
  1088. }
  1089. std::sort(roots.begin(),roots.end());
  1090. const int64_t now = OSUtils::now();
  1091. World w(World::make(t,id,now,updatesMustBeSignedBy,roots,signingKey));
  1092. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  1093. w.serialize(wbuf);
  1094. char fn[128];
  1095. OSUtils::ztsnprintf(fn,sizeof(fn),"%.16llx.moon",w.id());
  1096. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  1097. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  1098. }
  1099. } else {
  1100. idtoolPrintHelp(stdout,argv[0]);
  1101. return 1;
  1102. }
  1103. return 0;
  1104. }
  1105. /****************************************************************************/
  1106. /* Unix helper functions and signal handlers */
  1107. /****************************************************************************/
  1108. #ifdef __UNIX_LIKE__
  1109. static void _sighandlerHup(int sig)
  1110. {
  1111. }
  1112. static void _sighandlerQuit(int sig)
  1113. {
  1114. OneService *s = zt1Service;
  1115. if (s)
  1116. s->terminate();
  1117. else exit(0);
  1118. }
  1119. #endif
  1120. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  1121. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  1122. #ifndef PR_CAP_AMBIENT
  1123. #define PR_CAP_AMBIENT 47
  1124. #define PR_CAP_AMBIENT_IS_SET 1
  1125. #define PR_CAP_AMBIENT_RAISE 2
  1126. #define PR_CAP_AMBIENT_LOWER 3
  1127. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  1128. #endif
  1129. #define ZT_LINUX_USER "zerotier-one"
  1130. #define ZT_HAVE_DROP_PRIVILEGES 1
  1131. namespace {
  1132. // libc doesn't export capset, it is instead located in libcap
  1133. // We ignore libcap and call it manually.
  1134. struct cap_header_struct {
  1135. __u32 version;
  1136. int pid;
  1137. };
  1138. struct cap_data_struct {
  1139. __u32 effective;
  1140. __u32 permitted;
  1141. __u32 inheritable;
  1142. };
  1143. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  1144. static void _notDropping(const char *procName,const std::string &homeDir)
  1145. {
  1146. struct stat buf;
  1147. if (lstat(homeDir.c_str(),&buf) < 0) {
  1148. if (buf.st_uid != 0 || buf.st_gid != 0) {
  1149. fprintf(stderr, "%s: FATAL: failed to drop privileges and can't run as root since privileges were previously dropped (home directory not owned by root)" ZT_EOL_S,procName);
  1150. exit(1);
  1151. }
  1152. }
  1153. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  1154. }
  1155. static int _setCapabilities(int flags)
  1156. {
  1157. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  1158. cap_data_struct capdata;
  1159. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  1160. return _zt_capset(&capheader, &capdata);
  1161. }
  1162. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  1163. {
  1164. struct dirent de;
  1165. struct dirent *dptr;
  1166. lchown(path,uid,gid);
  1167. DIR *d = opendir(path);
  1168. if (!d)
  1169. return;
  1170. dptr = (struct dirent *)0;
  1171. for(;;) {
  1172. if (readdir_r(d,&de,&dptr) != 0)
  1173. break;
  1174. if (!dptr)
  1175. break;
  1176. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  1177. std::string p(path);
  1178. p.push_back(ZT_PATH_SEPARATOR);
  1179. p.append(dptr->d_name);
  1180. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  1181. }
  1182. }
  1183. closedir(d);
  1184. }
  1185. static void dropPrivileges(const char *procName,const std::string &homeDir)
  1186. {
  1187. if (getuid() != 0)
  1188. return;
  1189. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  1190. // and CAP_NET_RAW capabilities.
  1191. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  1192. if (!targetUser)
  1193. return;
  1194. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  1195. // Kernel has no support for ambient capabilities.
  1196. _notDropping(procName,homeDir);
  1197. return;
  1198. }
  1199. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  1200. _notDropping(procName,homeDir);
  1201. return;
  1202. }
  1203. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  1204. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  1205. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1206. _notDropping(procName,homeDir);
  1207. return;
  1208. }
  1209. int oldDumpable = prctl(PR_GET_DUMPABLE);
  1210. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  1211. // Disable ptracing. Otherwise there is a small window when previous
  1212. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  1213. // (this is mitigated anyway on most distros by ptrace_scope=1)
  1214. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1215. exit(1);
  1216. }
  1217. // Relinquish root
  1218. if (setgid(targetUser->pw_gid) < 0) {
  1219. perror("setgid");
  1220. exit(1);
  1221. }
  1222. if (setuid(targetUser->pw_uid) < 0) {
  1223. perror("setuid");
  1224. exit(1);
  1225. }
  1226. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1227. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  1228. exit(1);
  1229. }
  1230. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  1231. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1232. exit(1);
  1233. }
  1234. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  1235. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_ADMIN) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1236. exit(1);
  1237. }
  1238. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  1239. fprintf(stderr,"%s: FATAL: prctl(PR_CAP_AMBIENT,PR_CAP_AMBIENT_RAISE,CAP_NET_RAW) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1240. exit(1);
  1241. }
  1242. }
  1243. } // anonymous namespace
  1244. #endif // __LINUX__
  1245. /****************************************************************************/
  1246. /* Windows helper functions and signal handlers */
  1247. /****************************************************************************/
  1248. #ifdef __WINDOWS__
  1249. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  1250. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  1251. {
  1252. switch(dwCtrlType) {
  1253. case CTRL_C_EVENT:
  1254. case CTRL_BREAK_EVENT:
  1255. case CTRL_CLOSE_EVENT:
  1256. case CTRL_SHUTDOWN_EVENT:
  1257. OneService *s = zt1Service;
  1258. if (s)
  1259. s->terminate();
  1260. return TRUE;
  1261. }
  1262. return FALSE;
  1263. }
  1264. // TODO: revisit this with https://support.microsoft.com/en-us/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh
  1265. static void _winPokeAHole()
  1266. {
  1267. char myPath[MAX_PATH];
  1268. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1269. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1270. STARTUPINFOA startupInfo;
  1271. PROCESS_INFORMATION processInfo;
  1272. startupInfo.cb = sizeof(startupInfo);
  1273. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1274. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1275. 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)) {
  1276. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1277. CloseHandle(processInfo.hProcess);
  1278. CloseHandle(processInfo.hThread);
  1279. }
  1280. startupInfo.cb = sizeof(startupInfo);
  1281. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1282. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1283. 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)) {
  1284. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1285. CloseHandle(processInfo.hProcess);
  1286. CloseHandle(processInfo.hThread);
  1287. }
  1288. startupInfo.cb = sizeof(startupInfo);
  1289. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1290. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1291. 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)) {
  1292. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1293. CloseHandle(processInfo.hProcess);
  1294. CloseHandle(processInfo.hThread);
  1295. }
  1296. }
  1297. }
  1298. // Returns true if this is running as the local administrator
  1299. static BOOL IsCurrentUserLocalAdministrator(void)
  1300. {
  1301. BOOL fReturn = FALSE;
  1302. DWORD dwStatus;
  1303. DWORD dwAccessMask;
  1304. DWORD dwAccessDesired;
  1305. DWORD dwACLSize;
  1306. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1307. PACL pACL = NULL;
  1308. PSID psidAdmin = NULL;
  1309. HANDLE hToken = NULL;
  1310. HANDLE hImpersonationToken = NULL;
  1311. PRIVILEGE_SET ps;
  1312. GENERIC_MAPPING GenericMapping;
  1313. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1314. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1315. const DWORD ACCESS_READ = 1;
  1316. const DWORD ACCESS_WRITE = 2;
  1317. __try
  1318. {
  1319. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1320. {
  1321. if (GetLastError() != ERROR_NO_TOKEN)
  1322. __leave;
  1323. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1324. __leave;
  1325. }
  1326. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1327. __leave;
  1328. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1329. SECURITY_BUILTIN_DOMAIN_RID,
  1330. DOMAIN_ALIAS_RID_ADMINS,
  1331. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1332. __leave;
  1333. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1334. if (psdAdmin == NULL)
  1335. __leave;
  1336. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1337. __leave;
  1338. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1339. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1340. if (pACL == NULL)
  1341. __leave;
  1342. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1343. __leave;
  1344. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1345. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1346. __leave;
  1347. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1348. __leave;
  1349. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1350. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1351. if (!IsValidSecurityDescriptor(psdAdmin))
  1352. __leave;
  1353. dwAccessDesired = ACCESS_READ;
  1354. GenericMapping.GenericRead = ACCESS_READ;
  1355. GenericMapping.GenericWrite = ACCESS_WRITE;
  1356. GenericMapping.GenericExecute = 0;
  1357. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1358. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1359. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1360. &fReturn))
  1361. {
  1362. fReturn = FALSE;
  1363. __leave;
  1364. }
  1365. }
  1366. __finally
  1367. {
  1368. // Clean up.
  1369. if (pACL) LocalFree(pACL);
  1370. if (psdAdmin) LocalFree(psdAdmin);
  1371. if (psidAdmin) FreeSid(psidAdmin);
  1372. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1373. if (hToken) CloseHandle (hToken);
  1374. }
  1375. return fReturn;
  1376. }
  1377. #endif // __WINDOWS__
  1378. /****************************************************************************/
  1379. /* main() and friends */
  1380. /****************************************************************************/
  1381. static void printHelp(const char *cn,FILE *out)
  1382. {
  1383. fprintf(out,
  1384. "%s version %d.%d.%d" ZT_EOL_S,
  1385. PROGRAM_NAME,
  1386. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1387. fprintf(out,
  1388. COPYRIGHT_NOTICE ZT_EOL_S
  1389. LICENSE_GRANT ZT_EOL_S);
  1390. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1391. fprintf(out,"Available switches:" ZT_EOL_S);
  1392. fprintf(out," -h - Display this help" ZT_EOL_S);
  1393. fprintf(out," -v - Show version" ZT_EOL_S);
  1394. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1395. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1396. #ifdef __UNIX_LIKE__
  1397. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1398. #endif // __UNIX_LIKE__
  1399. #ifdef __WINDOWS__
  1400. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1401. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1402. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1403. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1404. #endif // __WINDOWS__
  1405. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1406. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1407. }
  1408. class _OneServiceRunner
  1409. {
  1410. public:
  1411. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1412. void threadMain()
  1413. throw()
  1414. {
  1415. try {
  1416. for(;;) {
  1417. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1418. switch(zt1Service->run()) {
  1419. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1420. case OneService::ONE_NORMAL_TERMINATION:
  1421. break;
  1422. case OneService::ONE_UNRECOVERABLE_ERROR:
  1423. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1424. returnValue = 1;
  1425. break;
  1426. case OneService::ONE_IDENTITY_COLLISION: {
  1427. delete zt1Service;
  1428. zt1Service = (OneService *)0;
  1429. std::string oldid;
  1430. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1431. if (oldid.length()) {
  1432. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1433. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1434. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1435. }
  1436. } continue; // restart!
  1437. }
  1438. break; // terminate loop -- normally we don't keep restarting
  1439. }
  1440. delete zt1Service;
  1441. zt1Service = (OneService *)0;
  1442. } catch ( ... ) {
  1443. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1444. returnValue = 1;
  1445. }
  1446. }
  1447. const char *progname;
  1448. unsigned int returnValue;
  1449. unsigned int port;
  1450. const std::string &homeDir;
  1451. };
  1452. #ifdef __WINDOWS__
  1453. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1454. #else
  1455. int main(int argc,char **argv)
  1456. #endif
  1457. {
  1458. #ifdef __UNIX_LIKE__
  1459. signal(SIGHUP,&_sighandlerHup);
  1460. signal(SIGPIPE,SIG_IGN);
  1461. signal(SIGIO,SIG_IGN);
  1462. signal(SIGUSR1,SIG_IGN);
  1463. signal(SIGUSR2,SIG_IGN);
  1464. signal(SIGALRM,SIG_IGN);
  1465. signal(SIGINT,&_sighandlerQuit);
  1466. signal(SIGTERM,&_sighandlerQuit);
  1467. signal(SIGQUIT,&_sighandlerQuit);
  1468. signal(SIGINT,&_sighandlerQuit);
  1469. /* Ensure that there are no inherited file descriptors open from a previous
  1470. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1471. * of it do not return, and should not do anything otherwise bad. */
  1472. {
  1473. int mfd = STDIN_FILENO;
  1474. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1475. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1476. for(int f=mfd+1;f<1024;++f)
  1477. ::close(f);
  1478. }
  1479. bool runAsDaemon = false;
  1480. #endif // __UNIX_LIKE__
  1481. #ifdef __WINDOWS__
  1482. {
  1483. WSADATA wsaData;
  1484. WSAStartup(MAKEWORD(2,2),&wsaData);
  1485. }
  1486. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1487. bool winRunFromCommandLine = true;
  1488. #else
  1489. bool winRunFromCommandLine = false;
  1490. #endif
  1491. #endif // __WINDOWS__
  1492. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1493. return idtool(argc,argv);
  1494. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1495. return cli(argc,argv);
  1496. std::string homeDir;
  1497. unsigned int port = ZT_DEFAULT_PORT;
  1498. bool skipRootCheck = false;
  1499. for(int i=1;i<argc;++i) {
  1500. if (argv[i][0] == '-') {
  1501. switch(argv[i][1]) {
  1502. case 'p': // port -- for both UDP and TCP, packets and control plane
  1503. port = Utils::strToUInt(argv[i] + 2);
  1504. if (port > 0xffff) {
  1505. printHelp(argv[0],stdout);
  1506. return 1;
  1507. }
  1508. break;
  1509. #ifdef __UNIX_LIKE__
  1510. case 'd': // Run in background as daemon
  1511. runAsDaemon = true;
  1512. break;
  1513. #endif // __UNIX_LIKE__
  1514. case 'U':
  1515. skipRootCheck = true;
  1516. break;
  1517. case 'v': // Display version
  1518. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1519. return 0;
  1520. case 'i': // Invoke idtool personality
  1521. if (argv[i][2]) {
  1522. printHelp(argv[0],stdout);
  1523. return 0;
  1524. } else return idtool(argc-1,argv+1);
  1525. case 'q': // Invoke cli personality
  1526. if (argv[i][2]) {
  1527. printHelp(argv[0],stdout);
  1528. return 0;
  1529. } else return cli(argc,argv);
  1530. #ifdef __WINDOWS__
  1531. case 'C': // Run from command line instead of as Windows service
  1532. winRunFromCommandLine = true;
  1533. break;
  1534. case 'I': { // Install this binary as a Windows service
  1535. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1536. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1537. return 1;
  1538. }
  1539. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1540. if (ret.length()) {
  1541. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1542. return 3;
  1543. }
  1544. return 0;
  1545. } break;
  1546. case 'R': { // Uninstall this binary as Windows service
  1547. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1548. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1549. return 1;
  1550. }
  1551. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1552. if (ret.length()) {
  1553. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1554. return 3;
  1555. }
  1556. return 0;
  1557. } break;
  1558. case 'D': {
  1559. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1560. if (err.length() > 0) {
  1561. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1562. return 3;
  1563. }
  1564. return 0;
  1565. } break;
  1566. #endif // __WINDOWS__
  1567. case 'h':
  1568. case '?':
  1569. default:
  1570. printHelp(argv[0],stdout);
  1571. return 0;
  1572. }
  1573. } else {
  1574. if (homeDir.length()) {
  1575. printHelp(argv[0],stdout);
  1576. return 0;
  1577. } else {
  1578. homeDir = argv[i];
  1579. }
  1580. }
  1581. }
  1582. if (!homeDir.length())
  1583. homeDir = OneService::platformDefaultHomePath();
  1584. if (!homeDir.length()) {
  1585. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1586. return 1;
  1587. } else {
  1588. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1589. std::string ptmp;
  1590. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1591. ptmp.push_back(ZT_PATH_SEPARATOR);
  1592. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1593. if (ptmp.length() > 0)
  1594. ptmp.push_back(ZT_PATH_SEPARATOR);
  1595. ptmp.append(*pi);
  1596. if ((*pi != ".")&&(*pi != "..")) {
  1597. if (!OSUtils::mkdir(ptmp))
  1598. throw std::runtime_error("home path does not exist, and could not create. Please verify local system permissions.");
  1599. }
  1600. }
  1601. }
  1602. // This can be removed once the new controller code has been around for many versions
  1603. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1604. 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());
  1605. return 1;
  1606. }
  1607. #ifdef __UNIX_LIKE__
  1608. #ifndef ZT_ONE_NO_ROOT_CHECK
  1609. if ((!skipRootCheck)&&(getuid() != 0)) {
  1610. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1611. return 1;
  1612. }
  1613. #endif // !ZT_ONE_NO_ROOT_CHECK
  1614. if (runAsDaemon) {
  1615. long p = (long)fork();
  1616. if (p < 0) {
  1617. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1618. return 1;
  1619. } else if (p > 0)
  1620. return 0; // forked
  1621. // else p == 0, so we are daemonized
  1622. }
  1623. #endif // __UNIX_LIKE__
  1624. #ifdef __WINDOWS__
  1625. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1626. // when tap instances are created.
  1627. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1628. if (winRunFromCommandLine) {
  1629. // Running in "interactive" mode (mostly for debugging)
  1630. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1631. if (!skipRootCheck) {
  1632. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1633. return 1;
  1634. }
  1635. } else {
  1636. _winPokeAHole();
  1637. }
  1638. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1639. // continues on to ordinary command line execution code below...
  1640. } else {
  1641. // Running from service manager
  1642. _winPokeAHole();
  1643. ZeroTierOneService zt1WindowsService;
  1644. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1645. return 0;
  1646. } else {
  1647. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1648. return 1;
  1649. }
  1650. }
  1651. #endif // __WINDOWS__
  1652. #ifdef __UNIX_LIKE__
  1653. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1654. if (!skipRootCheck)
  1655. dropPrivileges(argv[0],homeDir);
  1656. #endif
  1657. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1658. {
  1659. // Write .pid file to home folder
  1660. FILE *pf = fopen(pidPath.c_str(),"w");
  1661. if (pf) {
  1662. fprintf(pf,"%ld",(long)getpid());
  1663. fclose(pf);
  1664. }
  1665. }
  1666. #endif // __UNIX_LIKE__
  1667. _OneServiceRunner thr(argv[0],homeDir,port);
  1668. thr.threadMain();
  1669. //Thread::join(Thread::start(&thr));
  1670. #ifdef __UNIX_LIKE__
  1671. OSUtils::rm(pidPath.c_str());
  1672. #endif
  1673. return thr.returnValue;
  1674. }