one.cpp 56 KB

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