one.cpp 68 KB

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