one.cpp 74 KB

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