one.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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. fprintf(stderr,"invalid network ID format, must be a 16-digit hexidecimal number\n");
  589. return 2;
  590. }
  591. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  592. if (scode == 0) {
  593. printf("Error connecting to the ZeroTier service: %s\n\nPlease check that the service is running and that TCP port 9993 can be contacted via 127.0.0.1." ZT_EOL_S, responseBody.c_str());
  594. return 1;
  595. }
  596. nlohmann::json j;
  597. try {
  598. j = OSUtils::jsonParse(responseBody);
  599. } catch (std::exception &exc) {
  600. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  601. return 1;
  602. } catch ( ... ) {
  603. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  604. return 1;
  605. }
  606. bool bNetworkFound = false;
  607. if (j.is_array()) {
  608. for(unsigned long i=0;i<j.size();++i) {
  609. nlohmann::json &n = j[i];
  610. if (n.is_object()) {
  611. if (n["id"] == arg1) {
  612. printf("%s\n", OSUtils::jsonString(n[arg2],"-").c_str());
  613. bNetworkFound = true;
  614. }
  615. }
  616. }
  617. }
  618. if (!bNetworkFound) {
  619. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  620. }
  621. if (scode == 200) {
  622. return 0;
  623. } else {
  624. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  625. return 1;
  626. }
  627. } else {
  628. cliPrintHelp(argv[0],stderr);
  629. return 0;
  630. }
  631. return 0;
  632. }
  633. /****************************************************************************/
  634. /* zerotier-idtool personality */
  635. /****************************************************************************/
  636. static void idtoolPrintHelp(FILE *out,const char *pn)
  637. {
  638. fprintf(out,
  639. "%s version %d.%d.%d" ZT_EOL_S,
  640. PROGRAM_NAME,
  641. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  642. fprintf(out,
  643. COPYRIGHT_NOTICE ZT_EOL_S
  644. LICENSE_GRANT ZT_EOL_S);
  645. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  646. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  647. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  648. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  649. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  650. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  651. fprintf(out," initmoon <identity.public of first seed>" ZT_EOL_S);
  652. fprintf(out," genmoon <moon json>" ZT_EOL_S);
  653. }
  654. static Identity getIdFromArg(char *arg)
  655. {
  656. Identity id;
  657. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  658. if (id.fromString(arg))
  659. return id;
  660. } else { // identity is to be read from a file
  661. std::string idser;
  662. if (OSUtils::readFile(arg,idser)) {
  663. if (id.fromString(idser.c_str()))
  664. return id;
  665. }
  666. }
  667. return Identity();
  668. }
  669. #ifdef __WINDOWS__
  670. static int idtool(int argc, _TCHAR* argv[])
  671. #else
  672. static int idtool(int argc,char **argv)
  673. #endif
  674. {
  675. if (argc < 2) {
  676. idtoolPrintHelp(stdout,argv[0]);
  677. return 1;
  678. }
  679. if (!strcmp(argv[1],"generate")) {
  680. uint64_t vanity = 0;
  681. int vanityBits = 0;
  682. if (argc >= 5) {
  683. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  684. vanityBits = 4 * (int)strlen(argv[4]);
  685. if (vanityBits > 40)
  686. vanityBits = 40;
  687. }
  688. Identity id;
  689. for(;;) {
  690. id.generate();
  691. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  692. if (vanityBits > 0) {
  693. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  694. }
  695. break;
  696. } else {
  697. 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)));
  698. }
  699. }
  700. char idtmp[1024];
  701. std::string idser = id.toString(true,idtmp);
  702. if (argc >= 3) {
  703. if (!OSUtils::writeFile(argv[2],idser)) {
  704. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  705. return 1;
  706. } else printf("%s written" ZT_EOL_S,argv[2]);
  707. if (argc >= 4) {
  708. idser = id.toString(false,idtmp);
  709. if (!OSUtils::writeFile(argv[3],idser)) {
  710. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  711. return 1;
  712. } else printf("%s written" ZT_EOL_S,argv[3]);
  713. }
  714. } else printf("%s",idser.c_str());
  715. } else if (!strcmp(argv[1],"validate")) {
  716. if (argc < 3) {
  717. idtoolPrintHelp(stdout,argv[0]);
  718. return 1;
  719. }
  720. Identity id = getIdFromArg(argv[2]);
  721. if (!id) {
  722. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  723. return 1;
  724. }
  725. if (!id.locallyValidate()) {
  726. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  727. return 1;
  728. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  729. } else if (!strcmp(argv[1],"getpublic")) {
  730. if (argc < 3) {
  731. idtoolPrintHelp(stdout,argv[0]);
  732. return 1;
  733. }
  734. Identity id = getIdFromArg(argv[2]);
  735. if (!id) {
  736. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  737. return 1;
  738. }
  739. char idtmp[1024];
  740. printf("%s",id.toString(false,idtmp));
  741. } else if (!strcmp(argv[1],"sign")) {
  742. if (argc < 4) {
  743. idtoolPrintHelp(stdout,argv[0]);
  744. return 1;
  745. }
  746. Identity id = getIdFromArg(argv[2]);
  747. if (!id) {
  748. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  749. return 1;
  750. }
  751. if (!id.hasPrivate()) {
  752. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  753. return 1;
  754. }
  755. std::string inf;
  756. if (!OSUtils::readFile(argv[3],inf)) {
  757. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  758. return 1;
  759. }
  760. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  761. char hexbuf[1024];
  762. printf("%s",Utils::hex(signature.data,ZT_C25519_SIGNATURE_LEN,hexbuf));
  763. } else if (!strcmp(argv[1],"verify")) {
  764. if (argc < 5) {
  765. idtoolPrintHelp(stdout,argv[0]);
  766. return 1;
  767. }
  768. Identity id = getIdFromArg(argv[2]);
  769. if (!id) {
  770. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  771. return 1;
  772. }
  773. std::string inf;
  774. if (!OSUtils::readFile(argv[3],inf)) {
  775. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  776. return 1;
  777. }
  778. char buf[4096];
  779. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  780. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  781. printf("%s signature valid" ZT_EOL_S,argv[3]);
  782. } else {
  783. signature.clear();
  784. if (OSUtils::readFile(argv[4],signature)) {
  785. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  786. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  787. printf("%s signature valid" ZT_EOL_S,argv[3]);
  788. } else {
  789. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  790. return 1;
  791. }
  792. } else {
  793. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  794. return 1;
  795. }
  796. }
  797. } else if (!strcmp(argv[1],"initmoon")) {
  798. if (argc < 3) {
  799. idtoolPrintHelp(stdout,argv[0]);
  800. } else {
  801. const Identity id = getIdFromArg(argv[2]);
  802. if (!id) {
  803. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  804. return 1;
  805. }
  806. C25519::Pair kp(C25519::generate());
  807. char idtmp[4096];
  808. nlohmann::json mj;
  809. mj["objtype"] = "world";
  810. mj["worldType"] = "moon";
  811. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,ZT_C25519_PUBLIC_KEY_LEN,idtmp);
  812. mj["signingKey_SECRET"] = Utils::hex(kp.priv.data,ZT_C25519_PRIVATE_KEY_LEN,idtmp);
  813. mj["id"] = id.address().toString(idtmp);
  814. nlohmann::json seedj;
  815. seedj["identity"] = id.toString(false,idtmp);
  816. seedj["stableEndpoints"] = nlohmann::json::array();
  817. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  818. std::string mjd(OSUtils::jsonDump(mj));
  819. printf("%s" ZT_EOL_S,mjd.c_str());
  820. }
  821. } else if (!strcmp(argv[1],"genmoon")) {
  822. if (argc < 3) {
  823. idtoolPrintHelp(stdout,argv[0]);
  824. } else {
  825. std::string buf;
  826. if (!OSUtils::readFile(argv[2],buf)) {
  827. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  828. return 1;
  829. }
  830. nlohmann::json mj(OSUtils::jsonParse(buf));
  831. const uint64_t id = Utils::hexStrToU64(OSUtils::jsonString(mj["id"],"0").c_str());
  832. if (!id) {
  833. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  834. return 1;
  835. }
  836. World::Type t;
  837. if (mj["worldType"] == "moon") {
  838. t = World::TYPE_MOON;
  839. } else if (mj["worldType"] == "planet") {
  840. t = World::TYPE_PLANET;
  841. } else {
  842. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  843. return 1;
  844. }
  845. C25519::Pair signingKey;
  846. C25519::Public updatesMustBeSignedBy;
  847. Utils::unhex(OSUtils::jsonString(mj["signingKey"],"").c_str(),signingKey.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  848. Utils::unhex(OSUtils::jsonString(mj["signingKey_SECRET"],"").c_str(),signingKey.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  849. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],"").c_str(),updatesMustBeSignedBy.data,ZT_C25519_PUBLIC_KEY_LEN);
  850. std::vector<World::Root> roots;
  851. nlohmann::json &rootsj = mj["roots"];
  852. if (rootsj.is_array()) {
  853. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  854. nlohmann::json &r = rootsj[i];
  855. if (r.is_object()) {
  856. roots.push_back(World::Root());
  857. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],"").c_str());
  858. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  859. if (stableEndpointsj.is_array()) {
  860. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  861. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"").c_str()));
  862. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  863. }
  864. }
  865. }
  866. }
  867. std::sort(roots.begin(),roots.end());
  868. const int64_t now = OSUtils::now();
  869. World w(World::make(t,id,now,updatesMustBeSignedBy,roots,signingKey));
  870. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  871. w.serialize(wbuf);
  872. char fn[128];
  873. OSUtils::ztsnprintf(fn,sizeof(fn),"%.16llx.moon",w.id());
  874. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  875. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  876. }
  877. } else {
  878. idtoolPrintHelp(stdout,argv[0]);
  879. return 1;
  880. }
  881. return 0;
  882. }
  883. /****************************************************************************/
  884. /* Unix helper functions and signal handlers */
  885. /****************************************************************************/
  886. #ifdef __UNIX_LIKE__
  887. static void _sighandlerHup(int sig)
  888. {
  889. }
  890. static void _sighandlerQuit(int sig)
  891. {
  892. OneService *s = zt1Service;
  893. if (s)
  894. s->terminate();
  895. else exit(0);
  896. }
  897. #endif
  898. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  899. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  900. #ifndef PR_CAP_AMBIENT
  901. #define PR_CAP_AMBIENT 47
  902. #define PR_CAP_AMBIENT_IS_SET 1
  903. #define PR_CAP_AMBIENT_RAISE 2
  904. #define PR_CAP_AMBIENT_LOWER 3
  905. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  906. #endif
  907. #define ZT_LINUX_USER "zerotier-one"
  908. #define ZT_HAVE_DROP_PRIVILEGES 1
  909. namespace {
  910. // libc doesn't export capset, it is instead located in libcap
  911. // We ignore libcap and call it manually.
  912. struct cap_header_struct {
  913. __u32 version;
  914. int pid;
  915. };
  916. struct cap_data_struct {
  917. __u32 effective;
  918. __u32 permitted;
  919. __u32 inheritable;
  920. };
  921. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  922. static void _notDropping(const char *procName,const std::string &homeDir)
  923. {
  924. struct stat buf;
  925. if (lstat(homeDir.c_str(),&buf) < 0) {
  926. if (buf.st_uid != 0 || buf.st_gid != 0) {
  927. 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);
  928. exit(1);
  929. }
  930. }
  931. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  932. }
  933. static int _setCapabilities(int flags)
  934. {
  935. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  936. cap_data_struct capdata;
  937. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  938. return _zt_capset(&capheader, &capdata);
  939. }
  940. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  941. {
  942. struct dirent de;
  943. struct dirent *dptr;
  944. lchown(path,uid,gid);
  945. DIR *d = opendir(path);
  946. if (!d)
  947. return;
  948. dptr = (struct dirent *)0;
  949. for(;;) {
  950. if (readdir_r(d,&de,&dptr) != 0)
  951. break;
  952. if (!dptr)
  953. break;
  954. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  955. std::string p(path);
  956. p.push_back(ZT_PATH_SEPARATOR);
  957. p.append(dptr->d_name);
  958. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  959. }
  960. }
  961. closedir(d);
  962. }
  963. static void dropPrivileges(const char *procName,const std::string &homeDir)
  964. {
  965. if (getuid() != 0)
  966. return;
  967. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  968. // and CAP_NET_RAW capabilities.
  969. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  970. if (!targetUser)
  971. return;
  972. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  973. // Kernel has no support for ambient capabilities.
  974. _notDropping(procName,homeDir);
  975. return;
  976. }
  977. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  978. _notDropping(procName,homeDir);
  979. return;
  980. }
  981. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  982. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  983. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  984. _notDropping(procName,homeDir);
  985. return;
  986. }
  987. int oldDumpable = prctl(PR_GET_DUMPABLE);
  988. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  989. // Disable ptracing. Otherwise there is a small window when previous
  990. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  991. // (this is mitigated anyway on most distros by ptrace_scope=1)
  992. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  993. exit(1);
  994. }
  995. // Relinquish root
  996. if (setgid(targetUser->pw_gid) < 0) {
  997. perror("setgid");
  998. exit(1);
  999. }
  1000. if (setuid(targetUser->pw_uid) < 0) {
  1001. perror("setuid");
  1002. exit(1);
  1003. }
  1004. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1005. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  1006. exit(1);
  1007. }
  1008. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  1009. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1010. exit(1);
  1011. }
  1012. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  1013. 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);
  1014. exit(1);
  1015. }
  1016. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  1017. 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);
  1018. exit(1);
  1019. }
  1020. }
  1021. } // anonymous namespace
  1022. #endif // __LINUX__
  1023. /****************************************************************************/
  1024. /* Windows helper functions and signal handlers */
  1025. /****************************************************************************/
  1026. #ifdef __WINDOWS__
  1027. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  1028. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  1029. {
  1030. switch(dwCtrlType) {
  1031. case CTRL_C_EVENT:
  1032. case CTRL_BREAK_EVENT:
  1033. case CTRL_CLOSE_EVENT:
  1034. case CTRL_SHUTDOWN_EVENT:
  1035. OneService *s = zt1Service;
  1036. if (s)
  1037. s->terminate();
  1038. return TRUE;
  1039. }
  1040. return FALSE;
  1041. }
  1042. static void _winPokeAHole()
  1043. {
  1044. char myPath[MAX_PATH];
  1045. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1046. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1047. STARTUPINFOA startupInfo;
  1048. PROCESS_INFORMATION processInfo;
  1049. startupInfo.cb = sizeof(startupInfo);
  1050. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1051. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1052. 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)) {
  1053. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1054. CloseHandle(processInfo.hProcess);
  1055. CloseHandle(processInfo.hThread);
  1056. }
  1057. startupInfo.cb = sizeof(startupInfo);
  1058. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1059. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1060. 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)) {
  1061. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1062. CloseHandle(processInfo.hProcess);
  1063. CloseHandle(processInfo.hThread);
  1064. }
  1065. startupInfo.cb = sizeof(startupInfo);
  1066. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1067. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1068. 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)) {
  1069. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1070. CloseHandle(processInfo.hProcess);
  1071. CloseHandle(processInfo.hThread);
  1072. }
  1073. }
  1074. }
  1075. // Returns true if this is running as the local administrator
  1076. static BOOL IsCurrentUserLocalAdministrator(void)
  1077. {
  1078. BOOL fReturn = FALSE;
  1079. DWORD dwStatus;
  1080. DWORD dwAccessMask;
  1081. DWORD dwAccessDesired;
  1082. DWORD dwACLSize;
  1083. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1084. PACL pACL = NULL;
  1085. PSID psidAdmin = NULL;
  1086. HANDLE hToken = NULL;
  1087. HANDLE hImpersonationToken = NULL;
  1088. PRIVILEGE_SET ps;
  1089. GENERIC_MAPPING GenericMapping;
  1090. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1091. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1092. const DWORD ACCESS_READ = 1;
  1093. const DWORD ACCESS_WRITE = 2;
  1094. __try
  1095. {
  1096. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1097. {
  1098. if (GetLastError() != ERROR_NO_TOKEN)
  1099. __leave;
  1100. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1101. __leave;
  1102. }
  1103. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1104. __leave;
  1105. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1106. SECURITY_BUILTIN_DOMAIN_RID,
  1107. DOMAIN_ALIAS_RID_ADMINS,
  1108. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1109. __leave;
  1110. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1111. if (psdAdmin == NULL)
  1112. __leave;
  1113. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1114. __leave;
  1115. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1116. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1117. if (pACL == NULL)
  1118. __leave;
  1119. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1120. __leave;
  1121. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1122. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1123. __leave;
  1124. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1125. __leave;
  1126. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1127. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1128. if (!IsValidSecurityDescriptor(psdAdmin))
  1129. __leave;
  1130. dwAccessDesired = ACCESS_READ;
  1131. GenericMapping.GenericRead = ACCESS_READ;
  1132. GenericMapping.GenericWrite = ACCESS_WRITE;
  1133. GenericMapping.GenericExecute = 0;
  1134. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1135. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1136. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1137. &fReturn))
  1138. {
  1139. fReturn = FALSE;
  1140. __leave;
  1141. }
  1142. }
  1143. __finally
  1144. {
  1145. // Clean up.
  1146. if (pACL) LocalFree(pACL);
  1147. if (psdAdmin) LocalFree(psdAdmin);
  1148. if (psidAdmin) FreeSid(psidAdmin);
  1149. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1150. if (hToken) CloseHandle (hToken);
  1151. }
  1152. return fReturn;
  1153. }
  1154. #endif // __WINDOWS__
  1155. /****************************************************************************/
  1156. /* main() and friends */
  1157. /****************************************************************************/
  1158. static void printHelp(const char *cn,FILE *out)
  1159. {
  1160. fprintf(out,
  1161. "%s version %d.%d.%d" ZT_EOL_S,
  1162. PROGRAM_NAME,
  1163. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1164. fprintf(out,
  1165. COPYRIGHT_NOTICE ZT_EOL_S
  1166. LICENSE_GRANT ZT_EOL_S);
  1167. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1168. fprintf(out,"Available switches:" ZT_EOL_S);
  1169. fprintf(out," -h - Display this help" ZT_EOL_S);
  1170. fprintf(out," -v - Show version" ZT_EOL_S);
  1171. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1172. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1173. #ifdef __UNIX_LIKE__
  1174. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1175. #endif // __UNIX_LIKE__
  1176. #ifdef __WINDOWS__
  1177. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1178. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1179. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1180. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1181. #endif // __WINDOWS__
  1182. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1183. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1184. }
  1185. class _OneServiceRunner
  1186. {
  1187. public:
  1188. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1189. void threadMain()
  1190. throw()
  1191. {
  1192. try {
  1193. for(;;) {
  1194. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1195. switch(zt1Service->run()) {
  1196. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1197. case OneService::ONE_NORMAL_TERMINATION:
  1198. break;
  1199. case OneService::ONE_UNRECOVERABLE_ERROR:
  1200. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1201. returnValue = 1;
  1202. break;
  1203. case OneService::ONE_IDENTITY_COLLISION: {
  1204. delete zt1Service;
  1205. zt1Service = (OneService *)0;
  1206. std::string oldid;
  1207. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1208. if (oldid.length()) {
  1209. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1210. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1211. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1212. }
  1213. } continue; // restart!
  1214. }
  1215. break; // terminate loop -- normally we don't keep restarting
  1216. }
  1217. delete zt1Service;
  1218. zt1Service = (OneService *)0;
  1219. } catch ( ... ) {
  1220. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1221. returnValue = 1;
  1222. }
  1223. }
  1224. const char *progname;
  1225. unsigned int returnValue;
  1226. unsigned int port;
  1227. const std::string &homeDir;
  1228. };
  1229. #ifdef __WINDOWS__
  1230. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1231. #else
  1232. int main(int argc,char **argv)
  1233. #endif
  1234. {
  1235. #ifdef __UNIX_LIKE__
  1236. signal(SIGHUP,&_sighandlerHup);
  1237. signal(SIGPIPE,SIG_IGN);
  1238. signal(SIGUSR1,SIG_IGN);
  1239. signal(SIGUSR2,SIG_IGN);
  1240. signal(SIGALRM,SIG_IGN);
  1241. signal(SIGINT,&_sighandlerQuit);
  1242. signal(SIGTERM,&_sighandlerQuit);
  1243. signal(SIGQUIT,&_sighandlerQuit);
  1244. /* Ensure that there are no inherited file descriptors open from a previous
  1245. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1246. * of it do not return, and should not do anything otherwise bad. */
  1247. {
  1248. int mfd = STDIN_FILENO;
  1249. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1250. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1251. for(int f=mfd+1;f<1024;++f)
  1252. ::close(f);
  1253. }
  1254. bool runAsDaemon = false;
  1255. #endif // __UNIX_LIKE__
  1256. #ifdef __WINDOWS__
  1257. {
  1258. WSADATA wsaData;
  1259. WSAStartup(MAKEWORD(2,2),&wsaData);
  1260. }
  1261. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1262. bool winRunFromCommandLine = true;
  1263. #else
  1264. bool winRunFromCommandLine = false;
  1265. #endif
  1266. #endif // __WINDOWS__
  1267. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1268. return idtool(argc,argv);
  1269. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1270. return cli(argc,argv);
  1271. std::string homeDir;
  1272. unsigned int port = ZT_DEFAULT_PORT;
  1273. bool skipRootCheck = false;
  1274. for(int i=1;i<argc;++i) {
  1275. if (argv[i][0] == '-') {
  1276. switch(argv[i][1]) {
  1277. case 'p': // port -- for both UDP and TCP, packets and control plane
  1278. port = Utils::strToUInt(argv[i] + 2);
  1279. if (port > 0xffff) {
  1280. printHelp(argv[0],stdout);
  1281. return 1;
  1282. }
  1283. break;
  1284. #ifdef __UNIX_LIKE__
  1285. case 'd': // Run in background as daemon
  1286. runAsDaemon = true;
  1287. break;
  1288. #endif // __UNIX_LIKE__
  1289. case 'U':
  1290. skipRootCheck = true;
  1291. break;
  1292. case 'v': // Display version
  1293. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1294. return 0;
  1295. case 'i': // Invoke idtool personality
  1296. if (argv[i][2]) {
  1297. printHelp(argv[0],stdout);
  1298. return 0;
  1299. } else return idtool(argc-1,argv+1);
  1300. case 'q': // Invoke cli personality
  1301. if (argv[i][2]) {
  1302. printHelp(argv[0],stdout);
  1303. return 0;
  1304. } else return cli(argc,argv);
  1305. #ifdef __WINDOWS__
  1306. case 'C': // Run from command line instead of as Windows service
  1307. winRunFromCommandLine = true;
  1308. break;
  1309. case 'I': { // Install this binary as a Windows service
  1310. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1311. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1312. return 1;
  1313. }
  1314. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1315. if (ret.length()) {
  1316. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1317. return 3;
  1318. }
  1319. return 0;
  1320. } break;
  1321. case 'R': { // Uninstall this binary as Windows service
  1322. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1323. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1324. return 1;
  1325. }
  1326. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1327. if (ret.length()) {
  1328. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1329. return 3;
  1330. }
  1331. return 0;
  1332. } break;
  1333. case 'D': {
  1334. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1335. if (err.length() > 0) {
  1336. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1337. return 3;
  1338. }
  1339. return 0;
  1340. } break;
  1341. #endif // __WINDOWS__
  1342. case 'h':
  1343. case '?':
  1344. default:
  1345. printHelp(argv[0],stdout);
  1346. return 0;
  1347. }
  1348. } else {
  1349. if (homeDir.length()) {
  1350. printHelp(argv[0],stdout);
  1351. return 0;
  1352. } else {
  1353. homeDir = argv[i];
  1354. }
  1355. }
  1356. }
  1357. if (!homeDir.length())
  1358. homeDir = OneService::platformDefaultHomePath();
  1359. if (!homeDir.length()) {
  1360. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1361. return 1;
  1362. } else {
  1363. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1364. std::string ptmp;
  1365. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1366. ptmp.push_back(ZT_PATH_SEPARATOR);
  1367. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1368. if (ptmp.length() > 0)
  1369. ptmp.push_back(ZT_PATH_SEPARATOR);
  1370. ptmp.append(*pi);
  1371. if ((*pi != ".")&&(*pi != "..")) {
  1372. if (!OSUtils::mkdir(ptmp))
  1373. throw std::runtime_error("home path does not exist, and could not create");
  1374. }
  1375. }
  1376. }
  1377. // This can be removed once the new controller code has been around for many versions
  1378. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1379. 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());
  1380. return 1;
  1381. }
  1382. #ifdef __UNIX_LIKE__
  1383. #ifndef ZT_ONE_NO_ROOT_CHECK
  1384. if ((!skipRootCheck)&&(getuid() != 0)) {
  1385. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1386. return 1;
  1387. }
  1388. #endif // !ZT_ONE_NO_ROOT_CHECK
  1389. if (runAsDaemon) {
  1390. long p = (long)fork();
  1391. if (p < 0) {
  1392. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1393. return 1;
  1394. } else if (p > 0)
  1395. return 0; // forked
  1396. // else p == 0, so we are daemonized
  1397. }
  1398. #endif // __UNIX_LIKE__
  1399. #ifdef __WINDOWS__
  1400. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1401. // when tap instances are created.
  1402. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1403. if (winRunFromCommandLine) {
  1404. // Running in "interactive" mode (mostly for debugging)
  1405. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1406. if (!skipRootCheck) {
  1407. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1408. return 1;
  1409. }
  1410. } else {
  1411. _winPokeAHole();
  1412. }
  1413. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1414. // continues on to ordinary command line execution code below...
  1415. } else {
  1416. // Running from service manager
  1417. _winPokeAHole();
  1418. ZeroTierOneService zt1WindowsService;
  1419. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1420. return 0;
  1421. } else {
  1422. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1423. return 1;
  1424. }
  1425. }
  1426. #endif // __WINDOWS__
  1427. #ifdef __UNIX_LIKE__
  1428. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1429. if (!skipRootCheck)
  1430. dropPrivileges(argv[0],homeDir);
  1431. #endif
  1432. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1433. {
  1434. // Write .pid file to home folder
  1435. FILE *pf = fopen(pidPath.c_str(),"w");
  1436. if (pf) {
  1437. fprintf(pf,"%ld",(long)getpid());
  1438. fclose(pf);
  1439. }
  1440. }
  1441. #endif // __UNIX_LIKE__
  1442. _OneServiceRunner thr(argv[0],homeDir,port);
  1443. thr.threadMain();
  1444. //Thread::join(Thread::start(&thr));
  1445. #ifdef __UNIX_LIKE__
  1446. OSUtils::rm(pidPath.c_str());
  1447. #endif
  1448. return thr.returnValue;
  1449. }