one.cpp 49 KB

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