one.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334
  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. #ifndef _GNU_SOURCE
  14. #define _GNU_SOURCE
  15. #endif
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include <stdint.h>
  20. #include <time.h>
  21. #include <errno.h>
  22. #include "node/Constants.hpp"
  23. #ifdef __WINDOWS__
  24. #include <WinSock2.h>
  25. #include <Windows.h>
  26. #include <tchar.h>
  27. #include <wchar.h>
  28. #include <lmcons.h>
  29. #include <newdev.h>
  30. #include <atlbase.h>
  31. #include <iphlpapi.h>
  32. #include <iomanip>
  33. #include <shlobj.h>
  34. #include "osdep/WindowsEthernetTap.hpp"
  35. #include "windows/ZeroTierOne/ServiceInstaller.h"
  36. #include "windows/ZeroTierOne/ServiceBase.h"
  37. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  38. #else
  39. #include <unistd.h>
  40. #include <pwd.h>
  41. #include <fcntl.h>
  42. #include <sys/types.h>
  43. #include <sys/stat.h>
  44. #include <sys/uio.h>
  45. #include <dirent.h>
  46. #include <signal.h>
  47. #ifdef __LINUX__
  48. #include <sys/prctl.h>
  49. #include <sys/syscall.h>
  50. #include <sys/wait.h>
  51. #include <net/if.h>
  52. #include <sys/types.h>
  53. #include <sys/socket.h>
  54. #include <ifaddrs.h>
  55. #include <sys/ioctl.h>
  56. #ifndef ZT_NO_CAPABILITIES
  57. #include <linux/capability.h>
  58. #include <linux/securebits.h>
  59. #endif
  60. #endif
  61. #endif
  62. #include <string>
  63. #include <stdexcept>
  64. #include <iostream>
  65. #include <sstream>
  66. #include <algorithm>
  67. #include "version.h"
  68. #include "include/ZeroTierOne.h"
  69. #include "node/Identity.hpp"
  70. #include "node/CertificateOfMembership.hpp"
  71. #include "node/Utils.hpp"
  72. #include "node/NetworkController.hpp"
  73. #include "node/Buffer.hpp"
  74. #include "node/World.hpp"
  75. #include "osdep/OSUtils.hpp"
  76. #include "osdep/Http.hpp"
  77. #include "osdep/Thread.hpp"
  78. #include "node/BondController.hpp"
  79. #include "service/OneService.hpp"
  80. #include "ext/json/json.hpp"
  81. #ifdef __APPLE__
  82. #include <SystemConfiguration/SystemConfiguration.h>
  83. #include <CoreServices/CoreServices.h>
  84. #include <sys/types.h>
  85. #include <sys/socket.h>
  86. #include <ifaddrs.h>
  87. #endif
  88. #define ZT_PID_PATH "zerotier-one.pid"
  89. using namespace ZeroTier;
  90. static OneService *volatile zt1Service = (OneService *)0;
  91. #define PROGRAM_NAME "ZeroTier One"
  92. #define COPYRIGHT_NOTICE "Copyright (c) 2020 ZeroTier, Inc."
  93. #define LICENSE_GRANT "Licensed under the ZeroTier BSL 1.1 (see LICENSE.txt)"
  94. /****************************************************************************/
  95. /* zerotier-cli personality */
  96. /****************************************************************************/
  97. // This is getting deprecated soon in favor of the stuff in cli/
  98. static void cliPrintHelp(const char *pn,FILE *out)
  99. {
  100. fprintf(out,
  101. "%s version %d.%d.%d build %d (platform %d arch %d)" ZT_EOL_S,
  102. PROGRAM_NAME,
  103. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION, ZEROTIER_ONE_VERSION_BUILD,
  104. ZT_BUILD_PLATFORM, ZT_BUILD_ARCHITECTURE);
  105. fprintf(out,
  106. COPYRIGHT_NOTICE ZT_EOL_S
  107. LICENSE_GRANT ZT_EOL_S);
  108. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  109. fprintf(out,"Available switches:" ZT_EOL_S);
  110. fprintf(out," -h - Display this help" ZT_EOL_S);
  111. fprintf(out," -v - Show version" ZT_EOL_S);
  112. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  113. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  114. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  115. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  116. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  117. fprintf(out," info - Display status info" ZT_EOL_S);
  118. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  119. fprintf(out," peers - List all peers (prettier)" ZT_EOL_S);
  120. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  121. fprintf(out," join <network ID> - Join a network" ZT_EOL_S);
  122. fprintf(out," leave <network ID> - Leave a network" ZT_EOL_S);
  123. fprintf(out," set <network ID> <setting> - Set a network setting" ZT_EOL_S);
  124. fprintf(out," get <network ID> <setting> - Get a network setting" ZT_EOL_S);
  125. fprintf(out," listmoons - List moons (federated root sets)" ZT_EOL_S);
  126. fprintf(out," orbit <world ID> <seed> - Join a moon via any member root" ZT_EOL_S);
  127. fprintf(out," deorbit <world ID> - Leave a moon" ZT_EOL_S);
  128. fprintf(out," dump - Debug settings dump for support" ZT_EOL_S);
  129. fprintf(out,ZT_EOL_S"Available settings:" ZT_EOL_S);
  130. fprintf(out," Settings to use with [get/set] may include property names from " ZT_EOL_S);
  131. fprintf(out," the JSON output of \"zerotier-cli -j listnetworks\". Additionally, " ZT_EOL_S);
  132. fprintf(out," (ip, ip4, ip6, ip6plane, and ip6prefix can be used). For instance:" ZT_EOL_S);
  133. fprintf(out," zerotier-cli get <network ID> ip6plane will return the 6PLANE address" ZT_EOL_S);
  134. fprintf(out," assigned to this node." ZT_EOL_S);
  135. }
  136. static std::string cliFixJsonCRs(const std::string &s)
  137. {
  138. std::string r;
  139. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  140. if (*c == '\n')
  141. r.append(ZT_EOL_S);
  142. else r.push_back(*c);
  143. }
  144. return r;
  145. }
  146. #ifdef __WINDOWS__
  147. static int cli(int argc, _TCHAR* argv[])
  148. #else
  149. static int cli(int argc,char **argv)
  150. #endif
  151. {
  152. unsigned int port = 0;
  153. std::string homeDir,command,arg1,arg2,authToken;
  154. std::string ip("127.0.0.1");
  155. bool json = false;
  156. for(int i=1;i<argc;++i) {
  157. if (argv[i][0] == '-') {
  158. switch(argv[i][1]) {
  159. case 'q': // ignore -q used to invoke this personality
  160. if (argv[i][2]) {
  161. cliPrintHelp(argv[0],stdout);
  162. return 1;
  163. }
  164. break;
  165. case 'j':
  166. if (argv[i][2]) {
  167. cliPrintHelp(argv[0],stdout);
  168. return 1;
  169. }
  170. json = true;
  171. break;
  172. case 'p':
  173. port = Utils::strToUInt(argv[i] + 2);
  174. if ((port > 0xffff)||(port == 0)) {
  175. cliPrintHelp(argv[0],stdout);
  176. return 1;
  177. }
  178. break;
  179. case 'D':
  180. if (argv[i][2]) {
  181. homeDir = argv[i] + 2;
  182. } else {
  183. cliPrintHelp(argv[0],stdout);
  184. return 1;
  185. }
  186. break;
  187. case 'H':
  188. if (argv[i][2]) {
  189. ip = argv[i] + 2;
  190. } else {
  191. cliPrintHelp(argv[0],stdout);
  192. return 1;
  193. }
  194. break;
  195. case 'T':
  196. if (argv[i][2]) {
  197. authToken = argv[i] + 2;
  198. } else {
  199. cliPrintHelp(argv[0],stdout);
  200. return 1;
  201. }
  202. break;
  203. case 'v':
  204. if (argv[i][2]) {
  205. cliPrintHelp(argv[0],stdout);
  206. return 1;
  207. }
  208. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  209. return 0;
  210. case 'h':
  211. case '?':
  212. default:
  213. cliPrintHelp(argv[0],stdout);
  214. return 0;
  215. }
  216. } else {
  217. if (arg1.length())
  218. arg2 = argv[i];
  219. else if (command.length())
  220. arg1 = argv[i];
  221. else command = argv[i];
  222. }
  223. }
  224. if (!homeDir.length())
  225. homeDir = OneService::platformDefaultHomePath();
  226. // TODO: cleanup this logic
  227. if ((!port)||(!authToken.length())) {
  228. if (!homeDir.length()) {
  229. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  230. return 2;
  231. }
  232. if (!port) {
  233. std::string portStr;
  234. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  235. port = Utils::strToUInt(portStr.c_str());
  236. if ((port == 0)||(port > 0xffff)) {
  237. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  238. return 2;
  239. }
  240. }
  241. if (!authToken.length()) {
  242. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  243. #ifdef __UNIX_LIKE__
  244. if (!authToken.length()) {
  245. const char *hd = getenv("HOME");
  246. if (hd) {
  247. char p[4096];
  248. #ifdef __APPLE__
  249. OSUtils::ztsnprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  250. #else
  251. OSUtils::ztsnprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  252. #endif
  253. OSUtils::readFile(p,authToken);
  254. }
  255. }
  256. #endif
  257. if (!authToken.length()) {
  258. fprintf(stderr,"%s: authtoken.secret not found or readable in %s (try again as root)" ZT_EOL_S,argv[0],homeDir.c_str());
  259. return 2;
  260. }
  261. }
  262. }
  263. InetAddress addr;
  264. {
  265. char addrtmp[256];
  266. OSUtils::ztsnprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  267. addr = InetAddress(addrtmp);
  268. }
  269. std::map<std::string,std::string> requestHeaders;
  270. std::map<std::string,std::string> responseHeaders;
  271. std::string responseBody;
  272. requestHeaders["X-ZT1-Auth"] = authToken;
  273. if ((command.length() > 0)&&(command[0] == '/')) {
  274. unsigned int scode = Http::GET(
  275. 1024 * 1024 * 16,
  276. 60000,
  277. (const struct sockaddr *)&addr,
  278. command.c_str(),
  279. requestHeaders,
  280. responseHeaders,
  281. responseBody);
  282. if (scode == 200) {
  283. printf("%s", cliFixJsonCRs(responseBody).c_str());
  284. return 0;
  285. } else {
  286. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  287. return 1;
  288. }
  289. } else if ((command == "info")||(command == "status")) {
  290. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  291. if (scode == 0) {
  292. 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());
  293. return 1;
  294. }
  295. nlohmann::json j;
  296. try {
  297. j = OSUtils::jsonParse(responseBody);
  298. } catch (std::exception &exc) {
  299. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  300. return 1;
  301. } catch ( ... ) {
  302. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  303. return 1;
  304. }
  305. if (scode == 200) {
  306. if (json) {
  307. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  308. } else {
  309. if (j.is_object()) {
  310. printf("200 info %s %s %s" ZT_EOL_S,
  311. OSUtils::jsonString(j["address"],"-").c_str(),
  312. OSUtils::jsonString(j["version"],"-").c_str(),
  313. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  314. }
  315. }
  316. return 0;
  317. } else {
  318. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  319. return 1;
  320. }
  321. } else if (command == "listpeers") {
  322. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  323. if (scode == 0) {
  324. 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());
  325. return 1;
  326. }
  327. nlohmann::json j;
  328. try {
  329. j = OSUtils::jsonParse(responseBody);
  330. } catch (std::exception &exc) {
  331. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  332. return 1;
  333. } catch ( ... ) {
  334. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  335. return 1;
  336. }
  337. if (scode == 200) {
  338. if (json) {
  339. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  340. } else {
  341. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  342. if (j.is_array()) {
  343. for(unsigned long k=0;k<j.size();++k) {
  344. nlohmann::json &p = j[k];
  345. std::string bestPath;
  346. nlohmann::json &paths = p["paths"];
  347. if (paths.is_array()) {
  348. for(unsigned long i=0;i<paths.size();++i) {
  349. nlohmann::json &path = paths[i];
  350. if (path["preferred"]) {
  351. char tmp[256];
  352. std::string addr = path["address"];
  353. const int64_t now = OSUtils::now();
  354. int64_t lastSendDiff = (uint64_t)path["lastSend"] ? now - (uint64_t)path["lastSend"] : -1;
  355. int64_t lastReceiveDiff = (uint64_t)path["lastReceive"] ? now - (uint64_t)path["lastReceive"] : -1;
  356. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s;%lld;%lld",addr.c_str(),lastSendDiff,lastReceiveDiff);
  357. bestPath = tmp;
  358. break;
  359. }
  360. }
  361. }
  362. if (bestPath.length() == 0) bestPath = "-";
  363. char ver[128];
  364. int64_t vmaj = p["versionMajor"];
  365. int64_t vmin = p["versionMinor"];
  366. int64_t vrev = p["versionRev"];
  367. if (vmaj >= 0) {
  368. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  369. } else {
  370. ver[0] = '-';
  371. ver[1] = (char)0;
  372. }
  373. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  374. OSUtils::jsonString(p["address"],"-").c_str(),
  375. bestPath.c_str(),
  376. (int)OSUtils::jsonInt(p["latency"],0),
  377. ver,
  378. OSUtils::jsonString(p["role"],"-").c_str());
  379. }
  380. }
  381. }
  382. return 0;
  383. } else {
  384. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  385. return 1;
  386. }
  387. } else if (command == "peers") {
  388. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  389. if (scode == 0) {
  390. 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());
  391. return 1;
  392. }
  393. nlohmann::json j;
  394. try {
  395. j = OSUtils::jsonParse(responseBody);
  396. } catch (std::exception &exc) {
  397. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  398. return 1;
  399. } catch ( ... ) {
  400. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  401. return 1;
  402. }
  403. if (scode == 200) {
  404. if (json) {
  405. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  406. } else {
  407. printf("200 peers\n<ztaddr> <ver> <role> <lat> <link> <lastTX> <lastRX> <path>" ZT_EOL_S);
  408. if (j.is_array()) {
  409. for(unsigned long k=0;k<j.size();++k) {
  410. nlohmann::json &p = j[k];
  411. std::string bestPath;
  412. nlohmann::json &paths = p["paths"];
  413. if (paths.is_array()) {
  414. for(unsigned long i=0;i<paths.size();++i) {
  415. nlohmann::json &path = paths[i];
  416. if (path["preferred"]) {
  417. char tmp[256];
  418. std::string addr = path["address"];
  419. const int64_t now = OSUtils::now();
  420. int64_t lastSendDiff = (uint64_t)path["lastSend"] ? now - (uint64_t)path["lastSend"] : -1;
  421. int64_t lastReceiveDiff = (uint64_t)path["lastReceive"] ? now - (uint64_t)path["lastReceive"] : -1;
  422. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%-8lld %-8lld %s",lastSendDiff,lastReceiveDiff,addr.c_str());
  423. bestPath = std::string("DIRECT ") + tmp;
  424. break;
  425. }
  426. }
  427. }
  428. if (bestPath.length() == 0) bestPath = "RELAY";
  429. char ver[128];
  430. int64_t vmaj = p["versionMajor"];
  431. int64_t vmin = p["versionMinor"];
  432. int64_t vrev = p["versionRev"];
  433. if (vmaj >= 0) {
  434. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  435. } else {
  436. ver[0] = '-';
  437. ver[1] = (char)0;
  438. }
  439. printf("%s %-6s %-6s %5d %s" ZT_EOL_S,
  440. OSUtils::jsonString(p["address"],"-").c_str(),
  441. ver,
  442. OSUtils::jsonString(p["role"],"-").c_str(),
  443. (int)OSUtils::jsonInt(p["latency"],0),
  444. bestPath.c_str());
  445. }
  446. }
  447. }
  448. return 0;
  449. } else {
  450. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  451. return 1;
  452. }
  453. } else if (command == "bond") {
  454. /* zerotier-cli bond */
  455. if (arg1.empty()) {
  456. printf("(bond) command is missing required arguments" ZT_EOL_S);
  457. return 2;
  458. }
  459. /* zerotier-cli bond list */
  460. if (arg1 == "list") {
  461. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  462. if (scode == 0) {
  463. 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());
  464. return 1;
  465. }
  466. nlohmann::json j;
  467. try {
  468. j = OSUtils::jsonParse(responseBody);
  469. } catch (std::exception &exc) {
  470. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  471. return 1;
  472. } catch ( ... ) {
  473. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  474. return 1;
  475. }
  476. if (scode == 200) {
  477. if (json) {
  478. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  479. } else {
  480. bool bFoundBond = false;
  481. printf(" <peer> <bondtype> <status> <links>" ZT_EOL_S);
  482. if (j.is_array()) {
  483. for(unsigned long k=0;k<j.size();++k) {
  484. nlohmann::json &p = j[k];
  485. bool isBonded = p["isBonded"];
  486. if (isBonded) {
  487. int8_t bondingPolicy = p["bondingPolicy"];
  488. bool isHealthy = p["isHealthy"];
  489. int8_t numAliveLinks = p["numAliveLinks"];
  490. int8_t numTotalLinks = p["numTotalLinks"];
  491. bFoundBond = true;
  492. std::string healthStr;
  493. if (isHealthy) {
  494. healthStr = "HEALTHY";
  495. } else {
  496. healthStr = "DEGRADED";
  497. }
  498. std::string policyStr = "none";
  499. if (bondingPolicy >= ZT_BONDING_POLICY_NONE && bondingPolicy <= ZT_BONDING_POLICY_BALANCE_AWARE) {
  500. policyStr = BondController::getPolicyStrByCode(bondingPolicy);
  501. }
  502. printf("%10s %32s %8s %d/%d" ZT_EOL_S,
  503. OSUtils::jsonString(p ["address"],"-").c_str(),
  504. policyStr.c_str(),
  505. healthStr.c_str(),
  506. numAliveLinks,
  507. numTotalLinks);
  508. }
  509. }
  510. }
  511. if (!bFoundBond) {
  512. printf(" NONE\t\t\t\tNONE\t NONE NONE" ZT_EOL_S);
  513. }
  514. }
  515. return 0;
  516. } else {
  517. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  518. return 1;
  519. }
  520. }
  521. else if (arg1.length() == 10) { /* zerotier-cli bond <peerId> enable */
  522. if (arg2 == "enable") {
  523. fprintf(stderr, "zerotier-cli bond <peerId> enable\n");
  524. return 0;
  525. }
  526. if (arg2 == "rotate") { /* zerotier-cli bond <peerId> rotate */
  527. fprintf(stderr, "zerotier-cli bond <peerId> rotate\n");
  528. requestHeaders["Content-Type"] = "application/json";
  529. requestHeaders["Content-Length"] = "2";
  530. unsigned int scode = Http::POST(
  531. 1024 * 1024 * 16,
  532. 60000,
  533. (const struct sockaddr *)&addr,
  534. (std::string("/bond/") + arg2 + "/" + arg1).c_str(),
  535. requestHeaders,
  536. "{}",
  537. 2,
  538. responseHeaders,
  539. responseBody);
  540. if (scode == 200) {
  541. if (json) {
  542. printf("%s",cliFixJsonCRs(responseBody).c_str());
  543. } else {
  544. printf("200 bond OK" ZT_EOL_S);
  545. }
  546. return 0;
  547. } else {
  548. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  549. return 1;
  550. }
  551. return 0;
  552. }
  553. if (arg2 == "show") {
  554. //fprintf(stderr, "zerotier-cli bond <peerId> show\n");
  555. const unsigned int scode = Http::GET(
  556. 1024 * 1024 * 16,60000,
  557. (const struct sockaddr *)&addr,(std::string("/bond/") + arg2 + "/" + arg1).c_str(),
  558. requestHeaders,
  559. responseHeaders,
  560. responseBody);
  561. if (scode == 0) {
  562. 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());
  563. return 1;
  564. }
  565. nlohmann::json j;
  566. try {
  567. j = OSUtils::jsonParse(responseBody);
  568. } catch (std::exception &exc) {
  569. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  570. return 1;
  571. } catch ( ... ) {
  572. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  573. return 1;
  574. }
  575. if (scode == 200) {
  576. if (json) {
  577. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  578. } else {
  579. std::string healthStr;
  580. if (OSUtils::jsonInt(j["isHealthy"],0)) {
  581. healthStr = "Healthy";
  582. } else {
  583. healthStr = "Degraded";
  584. }
  585. int numAliveLinks = OSUtils::jsonInt(j["numAliveLinks"],0);
  586. int numTotalLinks = OSUtils::jsonInt(j["numTotalLinks"],0);
  587. printf("Peer : %s\n", arg1.c_str());
  588. printf("Bond : %s\n", OSUtils::jsonString(j["bondingPolicy"],"-").c_str());
  589. //if (bondingPolicy == ZT_BONDING_POLICY_ACTIVE_BACKUP) {
  590. printf("Link Select Method : %d\n", (int)OSUtils::jsonInt(j["linkSelectMethod"],0));
  591. //}
  592. printf("Status : %s\n", healthStr.c_str());
  593. printf("Links : %d/%d\n", numAliveLinks, numTotalLinks);
  594. printf("Failover Interval : %d (ms)\n", (int)OSUtils::jsonInt(j["failoverInterval"],0));
  595. printf("Up Delay : %d (ms)\n", (int)OSUtils::jsonInt(j["upDelay"],0));
  596. printf("Down Delay : %d (ms)\n", (int)OSUtils::jsonInt(j["downDelay"],0));
  597. printf("Packets Per Link : %d (ms)\n", (int)OSUtils::jsonInt(j["packetsPerLink"],0));
  598. nlohmann::json &p = j["links"];
  599. if (p.is_array()) {
  600. printf("\n Interface Name\t\t\t\t\t Path\t Alive\n");
  601. for(int i=0; i<80; i++) { printf("-"); }
  602. printf("\n");
  603. for (int i=0; i<p.size(); i++)
  604. {
  605. printf("[%d] %15s %45s %12d\n",
  606. i,
  607. OSUtils::jsonString(p[i]["ifname"],"-").c_str(),
  608. OSUtils::jsonString(p[i]["path"],"-").c_str(),
  609. (int)OSUtils::jsonInt(p[i]["alive"],0));
  610. }
  611. printf("\n Latency Jitter Loss Error Speed Alloc\n");
  612. for(int i=0; i<80; i++) { printf("-"); }
  613. printf("\n");
  614. for (int i=0; i<p.size(); i++)
  615. {
  616. printf("[%d] %5.3f %5.3f %5.3f %5.3f %8d %5d\n",
  617. i,
  618. OSUtils::jsonDouble(p[i]["latencyMean"], 0),
  619. OSUtils::jsonDouble(p[i]["latencyVariance"], 0),
  620. OSUtils::jsonDouble(p[i]["packetLossRatio"], 0),
  621. OSUtils::jsonDouble(p[i]["packetErrorRatio"], 0),
  622. (int)OSUtils::jsonInt(p[i]["givenLinkSpeed"], 0),
  623. (int)OSUtils::jsonInt(p[i]["allocation"], 0));
  624. }
  625. }
  626. }
  627. return 0;
  628. } else {
  629. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  630. return 1;
  631. }
  632. return 2;
  633. }
  634. }
  635. /* zerotier-cli bond command was malformed in some way */
  636. printf("(bond) command is missing required arguments" ZT_EOL_S);
  637. return 2;
  638. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  639. if (scode == 0) {
  640. 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());
  641. return 1;
  642. }
  643. } else if (command == "listbonds") {
  644. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  645. if (scode == 0) {
  646. 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());
  647. return 1;
  648. }
  649. nlohmann::json j;
  650. try {
  651. j = OSUtils::jsonParse(responseBody);
  652. } catch (std::exception &exc) {
  653. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  654. return 1;
  655. } catch ( ... ) {
  656. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  657. return 1;
  658. }
  659. if (scode == 200) {
  660. if (json) {
  661. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  662. } else {
  663. bool bFoundBond = false;
  664. printf(" <peer> <bondtype> <status> <links>" ZT_EOL_S);
  665. if (j.is_array()) {
  666. for(unsigned long k=0;k<j.size();++k) {
  667. nlohmann::json &p = j[k];
  668. bool isBonded = p["isBonded"];
  669. if (isBonded) {
  670. int8_t bondingPolicy = p["bondingPolicy"];
  671. bool isHealthy = p["isHealthy"];
  672. int8_t numAliveLinks = p["numAliveLinks"];
  673. int8_t numTotalLinks = p["numTotalLinks"];
  674. bFoundBond = true;
  675. std::string healthStr;
  676. if (isHealthy) {
  677. healthStr = "Healthy";
  678. } else {
  679. healthStr = "Degraded";
  680. }
  681. std::string policyStr = "none";
  682. if (bondingPolicy >= ZT_BONDING_POLICY_NONE && bondingPolicy <= ZT_BONDING_POLICY_BALANCE_AWARE) {
  683. policyStr = BondController::getPolicyStrByCode(bondingPolicy);
  684. }
  685. printf("%10s %32s %8s %d/%d" ZT_EOL_S,
  686. OSUtils::jsonString(p["address"],"-").c_str(),
  687. policyStr.c_str(),
  688. healthStr.c_str(),
  689. numAliveLinks,
  690. numTotalLinks);
  691. }
  692. }
  693. }
  694. if (!bFoundBond) {
  695. printf(" NONE\t\t\t\tNONE\t NONE NONE" ZT_EOL_S);
  696. }
  697. }
  698. return 0;
  699. } else {
  700. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  701. return 1;
  702. }
  703. } else if (command == "listnetworks") {
  704. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  705. if (scode == 0) {
  706. 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());
  707. return 1;
  708. }
  709. nlohmann::json j;
  710. try {
  711. j = OSUtils::jsonParse(responseBody);
  712. } catch (std::exception &exc) {
  713. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  714. return 1;
  715. } catch ( ... ) {
  716. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  717. return 1;
  718. }
  719. if (scode == 200) {
  720. if (json) {
  721. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  722. } else {
  723. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  724. if (j.is_array()) {
  725. for(unsigned long i=0;i<j.size();++i) {
  726. nlohmann::json &n = j[i];
  727. if (n.is_object()) {
  728. std::string aa;
  729. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  730. if (assignedAddresses.is_array()) {
  731. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  732. nlohmann::json &addr = assignedAddresses[j];
  733. if (addr.is_string()) {
  734. if (aa.length() > 0) aa.push_back(',');
  735. aa.append(addr.get<std::string>());
  736. }
  737. }
  738. }
  739. if (aa.length() == 0) aa = "-";
  740. const std::string status = OSUtils::jsonString(n["status"],"-");
  741. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  742. OSUtils::jsonString(n["nwid"],"-").c_str(),
  743. OSUtils::jsonString(n["name"],"-").c_str(),
  744. OSUtils::jsonString(n["mac"],"-").c_str(),
  745. status.c_str(),
  746. OSUtils::jsonString(n["type"],"-").c_str(),
  747. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  748. aa.c_str());
  749. if (OSUtils::jsonBool(n["ssoEnabled"], false)) {
  750. uint64_t authenticationExpiryTime = n["authenticationExpiryTime"];
  751. if (status == "AUTHENTICATION_REQUIRED") {
  752. printf(" AUTH EXPIRED, URL: %s" ZT_EOL_S, OSUtils::jsonString(n["authenticationURL"], "(null)").c_str());
  753. } else if (status == "OK") {
  754. printf(" AUTH OK, expires in: %lld seconds" ZT_EOL_S, ((int64_t)authenticationExpiryTime - OSUtils::now()) / 1000LL);
  755. }
  756. }
  757. }
  758. }
  759. }
  760. }
  761. return 0;
  762. } else {
  763. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  764. return 1;
  765. }
  766. } else if (command == "join") {
  767. if (arg1.length() != 16) {
  768. printf("invalid network id" ZT_EOL_S);
  769. return 2;
  770. }
  771. requestHeaders["Content-Type"] = "application/json";
  772. requestHeaders["Content-Length"] = "2";
  773. unsigned int scode = Http::POST(
  774. 1024 * 1024 * 16,
  775. 60000,
  776. (const struct sockaddr *)&addr,
  777. (std::string("/network/") + arg1).c_str(),
  778. requestHeaders,
  779. "{}",
  780. 2,
  781. responseHeaders,
  782. responseBody);
  783. if (scode == 200) {
  784. if (json) {
  785. printf("%s",cliFixJsonCRs(responseBody).c_str());
  786. } else {
  787. printf("200 join OK" ZT_EOL_S);
  788. }
  789. return 0;
  790. } else {
  791. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  792. return 1;
  793. }
  794. } else if (command == "leave") {
  795. if (arg1.length() != 16) {
  796. printf("invalid network id" ZT_EOL_S);
  797. return 2;
  798. }
  799. unsigned int scode = Http::DEL(
  800. 1024 * 1024 * 16,
  801. 60000,
  802. (const struct sockaddr *)&addr,
  803. (std::string("/network/") + arg1).c_str(),
  804. requestHeaders,
  805. responseHeaders,
  806. responseBody);
  807. if (scode == 200) {
  808. if (json) {
  809. printf("%s",cliFixJsonCRs(responseBody).c_str());
  810. } else {
  811. printf("200 leave OK" ZT_EOL_S);
  812. }
  813. return 0;
  814. } else {
  815. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  816. return 1;
  817. }
  818. } else if (command == "listmoons") {
  819. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/moon",requestHeaders,responseHeaders,responseBody);
  820. if (scode == 0) {
  821. 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());
  822. return 1;
  823. }
  824. nlohmann::json j;
  825. try {
  826. j = OSUtils::jsonParse(responseBody);
  827. } catch (std::exception &exc) {
  828. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  829. return 1;
  830. } catch ( ... ) {
  831. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  832. return 1;
  833. }
  834. if (scode == 200) {
  835. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  836. return 0;
  837. } else {
  838. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  839. return 1;
  840. }
  841. } else if (command == "orbit") {
  842. const uint64_t worldId = Utils::hexStrToU64(arg1.c_str());
  843. const uint64_t seed = Utils::hexStrToU64(arg2.c_str());
  844. if ((worldId)&&(seed)) {
  845. char jsons[1024];
  846. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"seed\":\"%s\"}",arg2.c_str());
  847. char cl[128];
  848. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  849. requestHeaders["Content-Type"] = "application/json";
  850. requestHeaders["Content-Length"] = cl;
  851. unsigned int scode = Http::POST(
  852. 1024 * 1024 * 16,
  853. 60000,
  854. (const struct sockaddr *)&addr,
  855. (std::string("/moon/") + arg1).c_str(),
  856. requestHeaders,
  857. jsons,
  858. (unsigned long)strlen(jsons),
  859. responseHeaders,
  860. responseBody);
  861. if (scode == 200) {
  862. printf("200 orbit OK" ZT_EOL_S);
  863. return 0;
  864. } else {
  865. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  866. return 1;
  867. }
  868. }
  869. } else if (command == "deorbit") {
  870. unsigned int scode = Http::DEL(
  871. 1024 * 1024 * 16,
  872. 60000,
  873. (const struct sockaddr *)&addr,
  874. (std::string("/moon/") + arg1).c_str(),
  875. requestHeaders,
  876. responseHeaders,
  877. responseBody);
  878. if (scode == 200) {
  879. if (json) {
  880. printf("%s",cliFixJsonCRs(responseBody).c_str());
  881. } else {
  882. printf("200 deorbit OK" ZT_EOL_S);
  883. }
  884. return 0;
  885. } else {
  886. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  887. return 1;
  888. }
  889. } else if (command == "set") {
  890. if (arg1.length() != 16) {
  891. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  892. return 2;
  893. }
  894. if (!arg2.length()) {
  895. fprintf(stderr,"invalid format: include a property name to set\n");
  896. return 2;
  897. }
  898. std::size_t eqidx = arg2.find('=');
  899. if (eqidx != std::string::npos) {
  900. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")||(arg2.substr(0,eqidx) == "allowDNS")) {
  901. char jsons[1024];
  902. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  903. arg2.substr(0,eqidx).c_str(),
  904. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  905. char cl[128];
  906. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  907. requestHeaders["Content-Type"] = "application/json";
  908. requestHeaders["Content-Length"] = cl;
  909. unsigned int scode = Http::POST(
  910. 1024 * 1024 * 16,
  911. 60000,
  912. (const struct sockaddr *)&addr,
  913. (std::string("/network/") + arg1).c_str(),
  914. requestHeaders,
  915. jsons,
  916. (unsigned long)strlen(jsons),
  917. responseHeaders,
  918. responseBody);
  919. if (scode == 200) {
  920. printf("%s",cliFixJsonCRs(responseBody).c_str());
  921. return 0;
  922. } else {
  923. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  924. return 1;
  925. }
  926. }
  927. } else {
  928. cliPrintHelp(argv[0],stderr);
  929. return 2;
  930. }
  931. } else if (command == "get") {
  932. if (arg1.length() != 16) {
  933. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  934. return 2;
  935. }
  936. if (!arg2.length()) {
  937. fprintf(stderr,"invalid format: include a property name to get\n");
  938. return 2;
  939. }
  940. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  941. if (scode == 0) {
  942. 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());
  943. return 1;
  944. }
  945. nlohmann::json j;
  946. try {
  947. j = OSUtils::jsonParse(responseBody);
  948. } catch (std::exception &exc) {
  949. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  950. return 1;
  951. } catch ( ... ) {
  952. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  953. return 1;
  954. }
  955. bool bNetworkFound = false;
  956. if (j.is_array()) {
  957. for(unsigned long i=0;i<j.size();++i) {
  958. nlohmann::json &n = j[i];
  959. if (n.is_object()) {
  960. if (n["id"] == arg1) {
  961. bNetworkFound = true;
  962. std::string aa;
  963. if (arg2 != "ip" && arg2 != "ip4" && arg2 != "ip6" && arg2 != "ip6plane" && arg2 != "ip6prefix") {
  964. aa.append(OSUtils::jsonString(n[arg2],"-")); // Standard network property field
  965. if (aa == "-") {
  966. printf("error, unknown property name\n");
  967. break;
  968. }
  969. printf("%s\n",aa.c_str());
  970. break;
  971. }
  972. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  973. if (assignedAddresses.is_array()) {
  974. int matchingIdxs[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
  975. int addressCountOfType = 0;
  976. for (int k = 0; k<std::min(ZT_MAX_ZT_ASSIGNED_ADDRESSES, (int)assignedAddresses.size());++k) {
  977. nlohmann::json &addr = assignedAddresses[k];
  978. if ((arg2 == "ip4" && addr.get<std::string>().find('.') != std::string::npos)
  979. || ((arg2.find("ip6") == 0) && addr.get<std::string>().find(":") != std::string::npos)
  980. || (arg2 == "ip")
  981. ) {
  982. matchingIdxs[addressCountOfType++] = k;
  983. }
  984. }
  985. for (int k=0; k<addressCountOfType; k++) {
  986. nlohmann::json &addr = assignedAddresses[matchingIdxs[k]];
  987. if (!addr.is_string()) {
  988. continue;
  989. }
  990. if (arg2.find("ip6p") == 0) {
  991. if (arg2 == "ip6plane") {
  992. if (addr.get<std::string>().find("fc") == 0) {
  993. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find('/')));
  994. if (k < addressCountOfType-1) aa.append("\n");
  995. }
  996. }
  997. if (arg2 == "ip6prefix") {
  998. if (addr.get<std::string>().find("fc") == 0) {
  999. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find('/')).substr(0,24));
  1000. if (k < addressCountOfType-1) aa.append("\n");
  1001. }
  1002. }
  1003. }
  1004. else {
  1005. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find('/')));
  1006. if (k < addressCountOfType-1) aa.append("\n");
  1007. }
  1008. }
  1009. }
  1010. printf("%s\n",aa.c_str());
  1011. }
  1012. }
  1013. }
  1014. }
  1015. if (!bNetworkFound) {
  1016. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  1017. }
  1018. if (scode == 200) {
  1019. return 0;
  1020. } else {
  1021. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  1022. return 1;
  1023. }
  1024. } else if (command == "dump") {
  1025. std::stringstream dump;
  1026. dump << "platform: ";
  1027. #ifdef __APPLE__
  1028. dump << "macOS" << ZT_EOL_S;
  1029. #elif defined(_WIN32)
  1030. dump << "Windows" << ZT_EOL_S;
  1031. #elif defined(__LINUX__)
  1032. dump << "Linux" << ZT_EOL_S;
  1033. #else
  1034. dump << "other unix based OS" << ZT_EOL_S;
  1035. #endif
  1036. dump << "zerotier version: " << ZEROTIER_ONE_VERSION_MAJOR << "."
  1037. << ZEROTIER_ONE_VERSION_MINOR << "." << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S << ZT_EOL_S;
  1038. // grab status
  1039. dump << "status" << ZT_EOL_S << "------" << ZT_EOL_S;
  1040. unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  1041. if (scode != 200) {
  1042. 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());
  1043. return 1;
  1044. }
  1045. dump << responseBody << ZT_EOL_S;
  1046. responseHeaders.clear();
  1047. responseBody = "";
  1048. // grab network list
  1049. dump << ZT_EOL_S << "networks" << ZT_EOL_S << "--------" << ZT_EOL_S;
  1050. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  1051. if (scode != 200) {
  1052. 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());
  1053. return 1;
  1054. }
  1055. dump << responseBody << ZT_EOL_S;
  1056. responseHeaders.clear();
  1057. responseBody = "";
  1058. // list peers
  1059. dump << ZT_EOL_S << "peers" << ZT_EOL_S << "-----" << ZT_EOL_S;
  1060. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  1061. if (scode != 200) {
  1062. 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());
  1063. return 1;
  1064. }
  1065. dump << responseBody << ZT_EOL_S;
  1066. // get bonds
  1067. dump << ZT_EOL_S << "bonds" << ZT_EOL_S << "-----" << ZT_EOL_S;
  1068. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  1069. if (scode != 200) {
  1070. 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());
  1071. return 1;
  1072. }
  1073. dump << responseBody << ZT_EOL_S;
  1074. responseHeaders.clear();
  1075. responseBody = "";
  1076. dump << ZT_EOL_S << "local.conf" << ZT_EOL_S << "----------" << ZT_EOL_S;
  1077. std::string localConf;
  1078. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "local.conf").c_str(), localConf);
  1079. if (localConf.empty()) {
  1080. dump << "None Present" << ZT_EOL_S;
  1081. }
  1082. else {
  1083. dump << localConf << ZT_EOL_S;
  1084. }
  1085. dump << ZT_EOL_S << "Network Interfaces" << ZT_EOL_S << "------------------" << ZT_EOL_S << ZT_EOL_S;
  1086. #ifdef __APPLE__
  1087. CFArrayRef interfaces = SCNetworkInterfaceCopyAll();
  1088. CFIndex size = CFArrayGetCount(interfaces);
  1089. for(CFIndex i = 0; i < size; ++i) {
  1090. SCNetworkInterfaceRef iface = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(interfaces, i);
  1091. dump << "Interface " << i << ZT_EOL_S << "-----------" << ZT_EOL_S;
  1092. CFStringRef tmp = SCNetworkInterfaceGetBSDName(iface);
  1093. char stringBuffer[512] = {};
  1094. CFStringGetCString(tmp,stringBuffer, sizeof(stringBuffer), kCFStringEncodingUTF8);
  1095. dump << "Name: " << stringBuffer << ZT_EOL_S;
  1096. std::string ifName(stringBuffer);
  1097. int mtuCur, mtuMin, mtuMax;
  1098. SCNetworkInterfaceCopyMTU(iface, &mtuCur, &mtuMin, &mtuMax);
  1099. dump << "MTU: " << mtuCur << ZT_EOL_S;
  1100. tmp = SCNetworkInterfaceGetHardwareAddressString(iface);
  1101. CFStringGetCString(tmp, stringBuffer, sizeof(stringBuffer), kCFStringEncodingUTF8);
  1102. dump << "MAC: " << stringBuffer << ZT_EOL_S;
  1103. tmp = SCNetworkInterfaceGetInterfaceType(iface);
  1104. CFStringGetCString(tmp, stringBuffer, sizeof(stringBuffer), kCFStringEncodingUTF8);
  1105. dump << "Type: " << stringBuffer << ZT_EOL_S;
  1106. dump << "Addresses:" << ZT_EOL_S;
  1107. struct ifaddrs *ifap, *ifa;
  1108. void *addr;
  1109. getifaddrs(&ifap);
  1110. for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1111. if (strcmp(ifName.c_str(), ifa->ifa_name) == 0) {
  1112. if (ifa->ifa_addr->sa_family == AF_INET) {
  1113. struct sockaddr_in *ipv4 = (struct sockaddr_in*)ifa->ifa_addr;
  1114. addr = &ipv4->sin_addr;
  1115. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  1116. struct sockaddr_in6 *ipv6 = (struct sockaddr_in6*)ifa->ifa_addr;
  1117. addr = &ipv6->sin6_addr;
  1118. } else {
  1119. continue;
  1120. }
  1121. inet_ntop(ifa->ifa_addr->sa_family, addr, stringBuffer, sizeof(stringBuffer));
  1122. dump << stringBuffer << ZT_EOL_S;
  1123. }
  1124. }
  1125. dump << ZT_EOL_S;
  1126. }
  1127. FSRef fsref;
  1128. UInt8 path[PATH_MAX];
  1129. if (FSFindFolder(kUserDomain, kDesktopFolderType, kDontCreateFolder, &fsref) == noErr &&
  1130. FSRefMakePath(&fsref, path, sizeof(path)) == noErr) {
  1131. } else if (getenv("SUDO_USER")) {
  1132. sprintf((char*)path, "/Users/%s/Desktop/", getenv("SUDO_USER"));
  1133. } else {
  1134. fprintf(stdout, "%s", dump.str().c_str());
  1135. return 0;
  1136. }
  1137. sprintf((char*)path, "%s%szerotier_dump.txt", (char*)path, ZT_PATH_SEPARATOR_S);
  1138. fprintf(stdout, "Writing dump to: %s\n", path);
  1139. int fd = open((char*)path, O_CREAT|O_RDWR,0664);
  1140. if (fd == -1) {
  1141. fprintf(stderr, "Error creating file.\n");
  1142. return 1;
  1143. }
  1144. write(fd, dump.str().c_str(), dump.str().size());
  1145. close(fd);
  1146. #elif defined(_WIN32)
  1147. ULONG buffLen = 16384;
  1148. PIP_ADAPTER_ADDRESSES addresses;
  1149. ULONG ret = 0;
  1150. do {
  1151. addresses = (PIP_ADAPTER_ADDRESSES)malloc(buffLen);
  1152. ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, addresses, &buffLen);
  1153. if (ret == ERROR_BUFFER_OVERFLOW) {
  1154. free(addresses);
  1155. addresses = NULL;
  1156. }
  1157. else {
  1158. break;
  1159. }
  1160. } while (ret == ERROR_BUFFER_OVERFLOW);
  1161. int i = 0;
  1162. if (ret == NO_ERROR) {
  1163. PIP_ADAPTER_ADDRESSES curAddr = addresses;
  1164. while (curAddr) {
  1165. dump << "Interface " << i << ZT_EOL_S << "-----------" << ZT_EOL_S;
  1166. dump << "Name: " << curAddr->AdapterName << ZT_EOL_S;
  1167. dump << "MTU: " << curAddr->Mtu << ZT_EOL_S;
  1168. dump << "MAC: ";
  1169. char macBuffer[64] = {};
  1170. sprintf(macBuffer, "%02x:%02x:%02x:%02x:%02x:%02x",
  1171. curAddr->PhysicalAddress[0],
  1172. curAddr->PhysicalAddress[1],
  1173. curAddr->PhysicalAddress[2],
  1174. curAddr->PhysicalAddress[3],
  1175. curAddr->PhysicalAddress[4],
  1176. curAddr->PhysicalAddress[5]);
  1177. dump << macBuffer << ZT_EOL_S;
  1178. dump << "Type: " << curAddr->IfType << ZT_EOL_S;
  1179. dump << "Addresses:" << ZT_EOL_S;
  1180. PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
  1181. pUnicast = curAddr->FirstUnicastAddress;
  1182. if (pUnicast) {
  1183. for (int j = 0; pUnicast != NULL; ++j) {
  1184. char buf[128] = {};
  1185. DWORD bufLen = 128;
  1186. LPSOCKADDR a = pUnicast->Address.lpSockaddr;
  1187. WSAAddressToStringA(
  1188. pUnicast->Address.lpSockaddr,
  1189. pUnicast->Address.iSockaddrLength,
  1190. NULL,
  1191. buf,
  1192. &bufLen
  1193. );
  1194. dump << buf << ZT_EOL_S;
  1195. pUnicast = pUnicast->Next;
  1196. }
  1197. }
  1198. curAddr = curAddr->Next;
  1199. ++i;
  1200. }
  1201. }
  1202. if (addresses) {
  1203. free(addresses);
  1204. addresses = NULL;
  1205. }
  1206. char path[MAX_PATH + 1] = {};
  1207. if (SHGetFolderPathA(NULL, CSIDL_DESKTOP, NULL, 0, path) == S_OK) {
  1208. sprintf(path, "%s%szerotier_dump.txt", path, ZT_PATH_SEPARATOR_S);
  1209. fprintf(stdout, "Writing dump to: %s\n", path);
  1210. HANDLE file = CreateFileA(
  1211. path,
  1212. GENERIC_WRITE,
  1213. 0,
  1214. NULL,
  1215. CREATE_ALWAYS,
  1216. FILE_ATTRIBUTE_NORMAL,
  1217. NULL
  1218. );
  1219. if (file == INVALID_HANDLE_VALUE) {
  1220. fprintf(stdout, "%s", dump.str().c_str());
  1221. return 0;
  1222. }
  1223. BOOL err = WriteFile(
  1224. file,
  1225. dump.str().c_str(),
  1226. dump.str().size(),
  1227. NULL,
  1228. NULL
  1229. );
  1230. if (err = FALSE) {
  1231. fprintf(stderr, "Error writing file");
  1232. return 1;
  1233. }
  1234. CloseHandle(file);
  1235. }
  1236. else {
  1237. fprintf(stdout, "%s", dump.str().c_str());
  1238. }
  1239. #elif defined(__LINUX__)
  1240. struct ifreq ifr;
  1241. struct ifconf ifc;
  1242. char buf[1024];
  1243. char stringBuffer[128];
  1244. int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
  1245. ifc.ifc_len = sizeof(buf);
  1246. ifc.ifc_buf = buf;
  1247. ioctl(sock, SIOCGIFCONF, &ifc);
  1248. struct ifreq *it = ifc.ifc_req;
  1249. const struct ifreq * const end = it + (ifc.ifc_len / sizeof(struct ifreq));
  1250. int count = 0;
  1251. for(; it != end; ++it) {
  1252. strcpy(ifr.ifr_name, it->ifr_name);
  1253. if(ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
  1254. if (!(ifr.ifr_flags & IFF_LOOPBACK)) { // skip loopback
  1255. dump << "Interface " << count++ << ZT_EOL_S << "-----------" << ZT_EOL_S;
  1256. dump << "Name: " << ifr.ifr_name << ZT_EOL_S;
  1257. if (ioctl(sock, SIOCGIFMTU, &ifr) == 0) {
  1258. dump << "MTU: " << ifr.ifr_mtu << ZT_EOL_S;
  1259. }
  1260. if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
  1261. unsigned char mac_addr[6];
  1262. memcpy(mac_addr, ifr.ifr_hwaddr.sa_data, 6);
  1263. char macStr[18];
  1264. sprintf(macStr, "%02x:%02x:%02x:%02x:%02x:%02x",
  1265. mac_addr[0],
  1266. mac_addr[1],
  1267. mac_addr[2],
  1268. mac_addr[3],
  1269. mac_addr[4],
  1270. mac_addr[5]);
  1271. dump << "MAC: " << macStr << ZT_EOL_S;
  1272. }
  1273. dump << "Addresses: " << ZT_EOL_S;
  1274. struct ifaddrs *ifap, *ifa;
  1275. void *addr;
  1276. getifaddrs(&ifap);
  1277. for(ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1278. if(strcmp(ifr.ifr_name, ifa->ifa_name) == 0 && ifa->ifa_addr != NULL) {
  1279. if(ifa->ifa_addr->sa_family == AF_INET) {
  1280. struct sockaddr_in *ipv4 = (struct sockaddr_in*)ifa->ifa_addr;
  1281. addr = &ipv4->sin_addr;
  1282. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  1283. struct sockaddr_in6 *ipv6 = (struct sockaddr_in6*)ifa->ifa_addr;
  1284. addr = &ipv6->sin6_addr;
  1285. } else {
  1286. continue;
  1287. }
  1288. inet_ntop(ifa->ifa_addr->sa_family, addr, stringBuffer, sizeof(stringBuffer));
  1289. dump << stringBuffer << ZT_EOL_S;
  1290. }
  1291. }
  1292. }
  1293. }
  1294. }
  1295. close(sock);
  1296. char cwd[16384];
  1297. getcwd(cwd, sizeof(cwd));
  1298. sprintf(cwd, "%s%szerotier_dump.txt", cwd, ZT_PATH_SEPARATOR_S);
  1299. fprintf(stdout, "Writing dump to: %s\n", cwd);
  1300. int fd = open(cwd, O_CREAT|O_RDWR,0664);
  1301. if (fd == -1) {
  1302. fprintf(stderr, "Error creating file.\n");
  1303. return 1;
  1304. }
  1305. write(fd, dump.str().c_str(), dump.str().size());
  1306. close(fd);
  1307. #else
  1308. fprintf(stderr, "%s", dump.str().c_str());
  1309. #endif
  1310. // fprintf(stderr, "%s\n", dump.str().c_str());
  1311. } else {
  1312. cliPrintHelp(argv[0],stderr);
  1313. return 0;
  1314. }
  1315. return 0;
  1316. }
  1317. /****************************************************************************/
  1318. /* zerotier-idtool personality */
  1319. /****************************************************************************/
  1320. static void idtoolPrintHelp(FILE *out,const char *pn)
  1321. {
  1322. fprintf(out,
  1323. "%s version %d.%d.%d" ZT_EOL_S,
  1324. PROGRAM_NAME,
  1325. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1326. fprintf(out,
  1327. COPYRIGHT_NOTICE ZT_EOL_S
  1328. LICENSE_GRANT ZT_EOL_S);
  1329. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  1330. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  1331. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  1332. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  1333. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  1334. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  1335. fprintf(out," initmoon <identity.public of first seed>" ZT_EOL_S);
  1336. fprintf(out," genmoon <moon json>" ZT_EOL_S);
  1337. }
  1338. static Identity getIdFromArg(char *arg)
  1339. {
  1340. Identity id;
  1341. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  1342. if (id.fromString(arg))
  1343. return id;
  1344. } else { // identity is to be read from a file
  1345. std::string idser;
  1346. if (OSUtils::readFile(arg,idser)) {
  1347. if (id.fromString(idser.c_str()))
  1348. return id;
  1349. }
  1350. }
  1351. return Identity();
  1352. }
  1353. #ifdef __WINDOWS__
  1354. static int idtool(int argc, _TCHAR* argv[])
  1355. #else
  1356. static int idtool(int argc,char **argv)
  1357. #endif
  1358. {
  1359. if (argc < 2) {
  1360. idtoolPrintHelp(stdout,argv[0]);
  1361. return 1;
  1362. }
  1363. if (!strcmp(argv[1],"generate")) {
  1364. uint64_t vanity = 0;
  1365. int vanityBits = 0;
  1366. if (argc >= 5) {
  1367. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  1368. vanityBits = 4 * (int)strlen(argv[4]);
  1369. if (vanityBits > 40)
  1370. vanityBits = 40;
  1371. }
  1372. Identity id;
  1373. for(;;) {
  1374. id.generate();
  1375. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  1376. if (vanityBits > 0) {
  1377. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  1378. }
  1379. break;
  1380. } else {
  1381. 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)));
  1382. }
  1383. }
  1384. char idtmp[1024];
  1385. std::string idser = id.toString(true,idtmp);
  1386. if (argc >= 3) {
  1387. if (!OSUtils::writeFile(argv[2],idser)) {
  1388. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  1389. return 1;
  1390. } else printf("%s written" ZT_EOL_S,argv[2]);
  1391. if (argc >= 4) {
  1392. idser = id.toString(false,idtmp);
  1393. if (!OSUtils::writeFile(argv[3],idser)) {
  1394. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  1395. return 1;
  1396. } else printf("%s written" ZT_EOL_S,argv[3]);
  1397. }
  1398. } else printf("%s",idser.c_str());
  1399. } else if (!strcmp(argv[1],"validate")) {
  1400. if (argc < 3) {
  1401. idtoolPrintHelp(stdout,argv[0]);
  1402. return 1;
  1403. }
  1404. Identity id = getIdFromArg(argv[2]);
  1405. if (!id) {
  1406. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1407. return 1;
  1408. }
  1409. if (!id.locallyValidate()) {
  1410. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  1411. return 1;
  1412. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  1413. } else if (!strcmp(argv[1],"getpublic")) {
  1414. if (argc < 3) {
  1415. idtoolPrintHelp(stdout,argv[0]);
  1416. return 1;
  1417. }
  1418. Identity id = getIdFromArg(argv[2]);
  1419. if (!id) {
  1420. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1421. return 1;
  1422. }
  1423. char idtmp[1024];
  1424. printf("%s",id.toString(false,idtmp));
  1425. } else if (!strcmp(argv[1],"sign")) {
  1426. if (argc < 4) {
  1427. idtoolPrintHelp(stdout,argv[0]);
  1428. return 1;
  1429. }
  1430. Identity id = getIdFromArg(argv[2]);
  1431. if (!id) {
  1432. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1433. return 1;
  1434. }
  1435. if (!id.hasPrivate()) {
  1436. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  1437. return 1;
  1438. }
  1439. std::string inf;
  1440. if (!OSUtils::readFile(argv[3],inf)) {
  1441. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  1442. return 1;
  1443. }
  1444. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  1445. char hexbuf[1024];
  1446. printf("%s",Utils::hex(signature.data,ZT_C25519_SIGNATURE_LEN,hexbuf));
  1447. } else if (!strcmp(argv[1],"verify")) {
  1448. if (argc < 5) {
  1449. idtoolPrintHelp(stdout,argv[0]);
  1450. return 1;
  1451. }
  1452. Identity id = getIdFromArg(argv[2]);
  1453. if (!id) {
  1454. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1455. return 1;
  1456. }
  1457. std::string inf;
  1458. if (!OSUtils::readFile(argv[3],inf)) {
  1459. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  1460. return 1;
  1461. }
  1462. char buf[4096];
  1463. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  1464. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  1465. printf("%s signature valid" ZT_EOL_S,argv[3]);
  1466. } else {
  1467. signature.clear();
  1468. if (OSUtils::readFile(argv[4],signature)) {
  1469. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  1470. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  1471. printf("%s signature valid" ZT_EOL_S,argv[3]);
  1472. } else {
  1473. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  1474. return 1;
  1475. }
  1476. } else {
  1477. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  1478. return 1;
  1479. }
  1480. }
  1481. } else if (!strcmp(argv[1],"initmoon")) {
  1482. if (argc < 3) {
  1483. idtoolPrintHelp(stdout,argv[0]);
  1484. } else {
  1485. const Identity id = getIdFromArg(argv[2]);
  1486. if (!id) {
  1487. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  1488. return 1;
  1489. }
  1490. C25519::Pair kp(C25519::generate());
  1491. char idtmp[4096];
  1492. nlohmann::json mj;
  1493. mj["objtype"] = "world";
  1494. mj["worldType"] = "moon";
  1495. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,ZT_C25519_PUBLIC_KEY_LEN,idtmp);
  1496. mj["signingKey_SECRET"] = Utils::hex(kp.priv.data,ZT_C25519_PRIVATE_KEY_LEN,idtmp);
  1497. mj["id"] = id.address().toString(idtmp);
  1498. nlohmann::json seedj;
  1499. seedj["identity"] = id.toString(false,idtmp);
  1500. seedj["stableEndpoints"] = nlohmann::json::array();
  1501. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  1502. std::string mjd(OSUtils::jsonDump(mj));
  1503. printf("%s" ZT_EOL_S,mjd.c_str());
  1504. }
  1505. } else if (!strcmp(argv[1],"genmoon")) {
  1506. if (argc < 3) {
  1507. idtoolPrintHelp(stdout,argv[0]);
  1508. } else {
  1509. std::string buf;
  1510. if (!OSUtils::readFile(argv[2],buf)) {
  1511. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  1512. return 1;
  1513. }
  1514. nlohmann::json mj(OSUtils::jsonParse(buf));
  1515. const uint64_t id = Utils::hexStrToU64(OSUtils::jsonString(mj["id"],"0").c_str());
  1516. if (!id) {
  1517. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  1518. return 1;
  1519. }
  1520. World::Type t;
  1521. if (mj["worldType"] == "moon") {
  1522. t = World::TYPE_MOON;
  1523. } else if (mj["worldType"] == "planet") {
  1524. t = World::TYPE_PLANET;
  1525. } else {
  1526. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  1527. return 1;
  1528. }
  1529. C25519::Pair signingKey;
  1530. C25519::Public updatesMustBeSignedBy;
  1531. Utils::unhex(OSUtils::jsonString(mj["signingKey"],"").c_str(),signingKey.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  1532. Utils::unhex(OSUtils::jsonString(mj["signingKey_SECRET"],"").c_str(),signingKey.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  1533. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],"").c_str(),updatesMustBeSignedBy.data,ZT_C25519_PUBLIC_KEY_LEN);
  1534. std::vector<World::Root> roots;
  1535. nlohmann::json &rootsj = mj["roots"];
  1536. if (rootsj.is_array()) {
  1537. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  1538. nlohmann::json &r = rootsj[i];
  1539. if (r.is_object()) {
  1540. roots.push_back(World::Root());
  1541. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],"").c_str());
  1542. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  1543. if (stableEndpointsj.is_array()) {
  1544. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  1545. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"").c_str()));
  1546. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  1547. }
  1548. }
  1549. }
  1550. }
  1551. std::sort(roots.begin(),roots.end());
  1552. const int64_t now = OSUtils::now();
  1553. World w(World::make(t,id,now,updatesMustBeSignedBy,roots,signingKey));
  1554. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  1555. w.serialize(wbuf);
  1556. char fn[128];
  1557. OSUtils::ztsnprintf(fn,sizeof(fn),"%.16llx.moon",w.id());
  1558. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  1559. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  1560. }
  1561. } else {
  1562. idtoolPrintHelp(stdout,argv[0]);
  1563. return 1;
  1564. }
  1565. return 0;
  1566. }
  1567. /****************************************************************************/
  1568. /* Unix helper functions and signal handlers */
  1569. /****************************************************************************/
  1570. #ifdef __UNIX_LIKE__
  1571. static void _sighandlerHup(int sig)
  1572. {
  1573. }
  1574. static void _sighandlerReallyQuit(int sig)
  1575. {
  1576. exit(0);
  1577. }
  1578. static void _sighandlerQuit(int sig)
  1579. {
  1580. alarm(5); // force exit after 5s
  1581. OneService *s = zt1Service;
  1582. if (s)
  1583. s->terminate();
  1584. else exit(0);
  1585. }
  1586. #endif
  1587. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  1588. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  1589. #ifndef PR_CAP_AMBIENT
  1590. #define PR_CAP_AMBIENT 47
  1591. #define PR_CAP_AMBIENT_IS_SET 1
  1592. #define PR_CAP_AMBIENT_RAISE 2
  1593. #define PR_CAP_AMBIENT_LOWER 3
  1594. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  1595. #endif
  1596. #define ZT_LINUX_USER "zerotier-one"
  1597. #define ZT_HAVE_DROP_PRIVILEGES 1
  1598. namespace {
  1599. // libc doesn't export capset, it is instead located in libcap
  1600. // We ignore libcap and call it manually.
  1601. struct cap_header_struct {
  1602. __u32 version;
  1603. int pid;
  1604. };
  1605. struct cap_data_struct {
  1606. __u32 effective;
  1607. __u32 permitted;
  1608. __u32 inheritable;
  1609. };
  1610. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  1611. static void _notDropping(const char *procName,const std::string &homeDir)
  1612. {
  1613. struct stat buf;
  1614. if (lstat(homeDir.c_str(),&buf) < 0) {
  1615. if (buf.st_uid != 0 || buf.st_gid != 0) {
  1616. 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);
  1617. exit(1);
  1618. }
  1619. }
  1620. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  1621. }
  1622. static int _setCapabilities(int flags)
  1623. {
  1624. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  1625. cap_data_struct capdata;
  1626. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  1627. return _zt_capset(&capheader, &capdata);
  1628. }
  1629. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  1630. {
  1631. struct dirent de;
  1632. struct dirent *dptr;
  1633. lchown(path,uid,gid);
  1634. DIR *d = opendir(path);
  1635. if (!d)
  1636. return;
  1637. dptr = (struct dirent *)0;
  1638. for(;;) {
  1639. if (readdir_r(d,&de,&dptr) != 0)
  1640. break;
  1641. if (!dptr)
  1642. break;
  1643. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  1644. std::string p(path);
  1645. p.push_back(ZT_PATH_SEPARATOR);
  1646. p.append(dptr->d_name);
  1647. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  1648. }
  1649. }
  1650. closedir(d);
  1651. }
  1652. static void dropPrivileges(const char *procName,const std::string &homeDir)
  1653. {
  1654. if (getuid() != 0)
  1655. return;
  1656. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  1657. // and CAP_NET_RAW capabilities.
  1658. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  1659. if (!targetUser)
  1660. return;
  1661. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  1662. // Kernel has no support for ambient capabilities.
  1663. _notDropping(procName,homeDir);
  1664. return;
  1665. }
  1666. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  1667. _notDropping(procName,homeDir);
  1668. return;
  1669. }
  1670. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  1671. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  1672. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1673. _notDropping(procName,homeDir);
  1674. return;
  1675. }
  1676. int oldDumpable = prctl(PR_GET_DUMPABLE);
  1677. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  1678. // Disable ptracing. Otherwise there is a small window when previous
  1679. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  1680. // (this is mitigated anyway on most distros by ptrace_scope=1)
  1681. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1682. exit(1);
  1683. }
  1684. // Relinquish root
  1685. if (setgid(targetUser->pw_gid) < 0) {
  1686. perror("setgid");
  1687. exit(1);
  1688. }
  1689. if (setuid(targetUser->pw_uid) < 0) {
  1690. perror("setuid");
  1691. exit(1);
  1692. }
  1693. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1694. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  1695. exit(1);
  1696. }
  1697. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  1698. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1699. exit(1);
  1700. }
  1701. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  1702. 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);
  1703. exit(1);
  1704. }
  1705. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  1706. 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);
  1707. exit(1);
  1708. }
  1709. }
  1710. } // anonymous namespace
  1711. #endif // __LINUX__
  1712. /****************************************************************************/
  1713. /* Windows helper functions and signal handlers */
  1714. /****************************************************************************/
  1715. #ifdef __WINDOWS__
  1716. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  1717. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  1718. {
  1719. switch(dwCtrlType) {
  1720. case CTRL_C_EVENT:
  1721. case CTRL_BREAK_EVENT:
  1722. case CTRL_CLOSE_EVENT:
  1723. case CTRL_SHUTDOWN_EVENT:
  1724. OneService *s = zt1Service;
  1725. if (s)
  1726. s->terminate();
  1727. return TRUE;
  1728. }
  1729. return FALSE;
  1730. }
  1731. // TODO: revisit this with https://support.microsoft.com/en-us/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh
  1732. static void _winPokeAHole()
  1733. {
  1734. char myPath[MAX_PATH];
  1735. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1736. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1737. STARTUPINFOA startupInfo;
  1738. PROCESS_INFORMATION processInfo;
  1739. startupInfo.cb = sizeof(startupInfo);
  1740. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1741. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1742. 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)) {
  1743. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1744. CloseHandle(processInfo.hProcess);
  1745. CloseHandle(processInfo.hThread);
  1746. }
  1747. startupInfo.cb = sizeof(startupInfo);
  1748. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1749. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1750. 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)) {
  1751. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1752. CloseHandle(processInfo.hProcess);
  1753. CloseHandle(processInfo.hThread);
  1754. }
  1755. startupInfo.cb = sizeof(startupInfo);
  1756. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1757. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1758. 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)) {
  1759. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1760. CloseHandle(processInfo.hProcess);
  1761. CloseHandle(processInfo.hThread);
  1762. }
  1763. }
  1764. }
  1765. // Returns true if this is running as the local administrator
  1766. static BOOL IsCurrentUserLocalAdministrator(void)
  1767. {
  1768. BOOL fReturn = FALSE;
  1769. DWORD dwStatus;
  1770. DWORD dwAccessMask;
  1771. DWORD dwAccessDesired;
  1772. DWORD dwACLSize;
  1773. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1774. PACL pACL = NULL;
  1775. PSID psidAdmin = NULL;
  1776. HANDLE hToken = NULL;
  1777. HANDLE hImpersonationToken = NULL;
  1778. PRIVILEGE_SET ps;
  1779. GENERIC_MAPPING GenericMapping;
  1780. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1781. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1782. const DWORD ACCESS_READ = 1;
  1783. const DWORD ACCESS_WRITE = 2;
  1784. __try
  1785. {
  1786. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1787. {
  1788. if (GetLastError() != ERROR_NO_TOKEN)
  1789. __leave;
  1790. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1791. __leave;
  1792. }
  1793. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1794. __leave;
  1795. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1796. SECURITY_BUILTIN_DOMAIN_RID,
  1797. DOMAIN_ALIAS_RID_ADMINS,
  1798. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1799. __leave;
  1800. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1801. if (psdAdmin == NULL)
  1802. __leave;
  1803. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1804. __leave;
  1805. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1806. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1807. if (pACL == NULL)
  1808. __leave;
  1809. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1810. __leave;
  1811. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1812. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1813. __leave;
  1814. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1815. __leave;
  1816. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1817. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1818. if (!IsValidSecurityDescriptor(psdAdmin))
  1819. __leave;
  1820. dwAccessDesired = ACCESS_READ;
  1821. GenericMapping.GenericRead = ACCESS_READ;
  1822. GenericMapping.GenericWrite = ACCESS_WRITE;
  1823. GenericMapping.GenericExecute = 0;
  1824. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1825. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1826. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1827. &fReturn))
  1828. {
  1829. fReturn = FALSE;
  1830. __leave;
  1831. }
  1832. }
  1833. __finally
  1834. {
  1835. // Clean up.
  1836. if (pACL) LocalFree(pACL);
  1837. if (psdAdmin) LocalFree(psdAdmin);
  1838. if (psidAdmin) FreeSid(psidAdmin);
  1839. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1840. if (hToken) CloseHandle (hToken);
  1841. }
  1842. return fReturn;
  1843. }
  1844. #endif // __WINDOWS__
  1845. /****************************************************************************/
  1846. /* main() and friends */
  1847. /****************************************************************************/
  1848. static void printHelp(const char *cn,FILE *out)
  1849. {
  1850. fprintf(out,
  1851. "%s version %d.%d.%d" ZT_EOL_S,
  1852. PROGRAM_NAME,
  1853. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1854. fprintf(out,
  1855. COPYRIGHT_NOTICE ZT_EOL_S
  1856. LICENSE_GRANT ZT_EOL_S);
  1857. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1858. fprintf(out,"Available switches:" ZT_EOL_S);
  1859. fprintf(out," -h - Display this help" ZT_EOL_S);
  1860. fprintf(out," -v - Show version" ZT_EOL_S);
  1861. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1862. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1863. #ifdef __UNIX_LIKE__
  1864. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1865. #endif // __UNIX_LIKE__
  1866. #ifdef __WINDOWS__
  1867. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1868. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1869. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1870. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1871. #endif // __WINDOWS__
  1872. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1873. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1874. }
  1875. class _OneServiceRunner
  1876. {
  1877. public:
  1878. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1879. void threadMain()
  1880. throw()
  1881. {
  1882. try {
  1883. for(;;) {
  1884. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1885. switch(zt1Service->run()) {
  1886. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1887. case OneService::ONE_NORMAL_TERMINATION:
  1888. break;
  1889. case OneService::ONE_UNRECOVERABLE_ERROR:
  1890. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1891. returnValue = 1;
  1892. break;
  1893. case OneService::ONE_IDENTITY_COLLISION: {
  1894. delete zt1Service;
  1895. zt1Service = (OneService *)0;
  1896. std::string oldid;
  1897. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1898. if (oldid.length()) {
  1899. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1900. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1901. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1902. }
  1903. } continue; // restart!
  1904. }
  1905. break; // terminate loop -- normally we don't keep restarting
  1906. }
  1907. delete zt1Service;
  1908. zt1Service = (OneService *)0;
  1909. } catch ( ... ) {
  1910. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1911. returnValue = 1;
  1912. }
  1913. }
  1914. const char *progname;
  1915. unsigned int returnValue;
  1916. unsigned int port;
  1917. const std::string &homeDir;
  1918. };
  1919. #ifdef __WINDOWS__
  1920. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1921. #else
  1922. int main(int argc,char **argv)
  1923. #endif
  1924. {
  1925. #if defined(__LINUX__) && ( (!defined(__GLIBC__)) || ((__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 18)) )
  1926. // This corrects for systems with abnormally small defaults (musl) and also
  1927. // shrinks the stack on systems with large defaults to save a bit of memory.
  1928. pthread_attr_t tattr;
  1929. pthread_attr_init(&tattr);
  1930. pthread_attr_setstacksize(&tattr,1048576);
  1931. pthread_setattr_default_np(&tattr);
  1932. pthread_attr_destroy(&tattr);
  1933. #endif
  1934. #ifdef __UNIX_LIKE__
  1935. signal(SIGHUP,&_sighandlerHup);
  1936. signal(SIGPIPE,SIG_IGN);
  1937. signal(SIGIO,SIG_IGN);
  1938. signal(SIGUSR1,SIG_IGN);
  1939. signal(SIGUSR2,SIG_IGN);
  1940. signal(SIGALRM,&_sighandlerReallyQuit);
  1941. signal(SIGINT,&_sighandlerQuit);
  1942. signal(SIGTERM,&_sighandlerQuit);
  1943. signal(SIGQUIT,&_sighandlerQuit);
  1944. signal(SIGINT,&_sighandlerQuit);
  1945. /* Ensure that there are no inherited file descriptors open from a previous
  1946. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1947. * of it do not return, and should not do anything otherwise bad. */
  1948. {
  1949. int mfd = STDIN_FILENO;
  1950. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1951. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1952. for(int f=mfd+1;f<1024;++f)
  1953. ::close(f);
  1954. }
  1955. bool runAsDaemon = false;
  1956. #endif // __UNIX_LIKE__
  1957. #ifdef __WINDOWS__
  1958. {
  1959. WSADATA wsaData;
  1960. WSAStartup(MAKEWORD(2,2),&wsaData);
  1961. }
  1962. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1963. bool winRunFromCommandLine = true;
  1964. #else
  1965. bool winRunFromCommandLine = false;
  1966. #endif
  1967. #endif // __WINDOWS__
  1968. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1969. return idtool(argc,argv);
  1970. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1971. return cli(argc,argv);
  1972. std::string homeDir;
  1973. unsigned int port = ZT_DEFAULT_PORT;
  1974. bool skipRootCheck = false;
  1975. for(int i=1;i<argc;++i) {
  1976. if (argv[i][0] == '-') {
  1977. switch(argv[i][1]) {
  1978. case 'p': // port -- for both UDP and TCP, packets and control plane
  1979. port = Utils::strToUInt(argv[i] + 2);
  1980. if (port > 0xffff) {
  1981. printHelp(argv[0],stdout);
  1982. return 1;
  1983. }
  1984. break;
  1985. #ifdef __UNIX_LIKE__
  1986. case 'd': // Run in background as daemon
  1987. runAsDaemon = true;
  1988. break;
  1989. #endif // __UNIX_LIKE__
  1990. case 'U':
  1991. skipRootCheck = true;
  1992. break;
  1993. case 'v': // Display version
  1994. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1995. return 0;
  1996. case 'i': // Invoke idtool personality
  1997. if (argv[i][2]) {
  1998. printHelp(argv[0],stdout);
  1999. return 0;
  2000. } else return idtool(argc-1,argv+1);
  2001. case 'q': // Invoke cli personality
  2002. if (argv[i][2]) {
  2003. printHelp(argv[0],stdout);
  2004. return 0;
  2005. } else return cli(argc,argv);
  2006. #ifdef __WINDOWS__
  2007. case 'C': // Run from command line instead of as Windows service
  2008. winRunFromCommandLine = true;
  2009. break;
  2010. case 'I': { // Install this binary as a Windows service
  2011. if (IsCurrentUserLocalAdministrator() != TRUE) {
  2012. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  2013. return 1;
  2014. }
  2015. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  2016. if (ret.length()) {
  2017. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  2018. return 3;
  2019. }
  2020. return 0;
  2021. } break;
  2022. case 'R': { // Uninstall this binary as Windows service
  2023. if (IsCurrentUserLocalAdministrator() != TRUE) {
  2024. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  2025. return 1;
  2026. }
  2027. std::string ret(UninstallService(ZT_SERVICE_NAME));
  2028. if (ret.length()) {
  2029. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  2030. return 3;
  2031. }
  2032. return 0;
  2033. } break;
  2034. case 'D': {
  2035. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  2036. if (err.length() > 0) {
  2037. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  2038. return 3;
  2039. }
  2040. return 0;
  2041. } break;
  2042. #endif // __WINDOWS__
  2043. case 'h':
  2044. case '?':
  2045. default:
  2046. printHelp(argv[0],stdout);
  2047. return 0;
  2048. }
  2049. } else {
  2050. if (homeDir.length()) {
  2051. printHelp(argv[0],stdout);
  2052. return 0;
  2053. } else {
  2054. homeDir = argv[i];
  2055. }
  2056. }
  2057. }
  2058. if (!homeDir.length())
  2059. homeDir = OneService::platformDefaultHomePath();
  2060. if (!homeDir.length()) {
  2061. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  2062. return 1;
  2063. } else {
  2064. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  2065. std::string ptmp;
  2066. if (homeDir[0] == ZT_PATH_SEPARATOR)
  2067. ptmp.push_back(ZT_PATH_SEPARATOR);
  2068. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  2069. if (ptmp.length() > 0)
  2070. ptmp.push_back(ZT_PATH_SEPARATOR);
  2071. ptmp.append(*pi);
  2072. if ((*pi != ".")&&(*pi != "..")) {
  2073. if (!OSUtils::mkdir(ptmp))
  2074. throw std::runtime_error("home path does not exist, and could not create. Please verify local system permissions.");
  2075. }
  2076. }
  2077. }
  2078. // This can be removed once the new controller code has been around for many versions
  2079. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  2080. 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());
  2081. return 1;
  2082. }
  2083. #ifdef __UNIX_LIKE__
  2084. #ifndef ZT_ONE_NO_ROOT_CHECK
  2085. if ((!skipRootCheck)&&(getuid() != 0)) {
  2086. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  2087. return 1;
  2088. }
  2089. #endif // !ZT_ONE_NO_ROOT_CHECK
  2090. if (runAsDaemon) {
  2091. long p = (long)fork();
  2092. if (p < 0) {
  2093. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  2094. return 1;
  2095. } else if (p > 0)
  2096. return 0; // forked
  2097. // else p == 0, so we are daemonized
  2098. }
  2099. #endif // __UNIX_LIKE__
  2100. #ifdef __WINDOWS__
  2101. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  2102. // when tap instances are created.
  2103. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  2104. if (winRunFromCommandLine) {
  2105. // Running in "interactive" mode (mostly for debugging)
  2106. if (IsCurrentUserLocalAdministrator() != TRUE) {
  2107. if (!skipRootCheck) {
  2108. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  2109. return 1;
  2110. }
  2111. } else {
  2112. _winPokeAHole();
  2113. }
  2114. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  2115. // continues on to ordinary command line execution code below...
  2116. } else {
  2117. // Running from service manager
  2118. _winPokeAHole();
  2119. ZeroTierOneService zt1WindowsService;
  2120. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  2121. return 0;
  2122. } else {
  2123. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  2124. return 1;
  2125. }
  2126. }
  2127. #endif // __WINDOWS__
  2128. #ifdef __UNIX_LIKE__
  2129. #ifdef ZT_HAVE_DROP_PRIVILEGES
  2130. if (!skipRootCheck)
  2131. dropPrivileges(argv[0],homeDir);
  2132. #endif
  2133. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  2134. {
  2135. // Write .pid file to home folder
  2136. FILE *pf = fopen(pidPath.c_str(),"w");
  2137. if (pf) {
  2138. fprintf(pf,"%ld",(long)getpid());
  2139. fclose(pf);
  2140. }
  2141. }
  2142. #endif // __UNIX_LIKE__
  2143. _OneServiceRunner thr(argv[0],homeDir,port);
  2144. thr.threadMain();
  2145. //Thread::join(Thread::start(&thr));
  2146. #ifdef __UNIX_LIKE__
  2147. OSUtils::rm(pidPath.c_str());
  2148. #endif
  2149. return thr.returnValue;
  2150. }