one.cpp 75 KB

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