1
0

one.cpp 67 KB

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