one.cpp 77 KB

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