2
0

one.cpp 67 KB

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