one.cpp 63 KB

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