one.cpp 67 KB

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