one.cpp 75 KB

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