one.cpp 74 KB

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