2
0

one.cpp 77 KB

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