one.cpp 74 KB

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