one.cpp 49 KB

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