2
0

one.cpp 69 KB

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