one.cpp 75 KB

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