one.cpp 74 KB

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