2
0

one.cpp 75 KB

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