one.cpp 50 KB

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