one.cpp 50 KB

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