one.cpp 54 KB

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