one.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051
  1. /*
  2. * Copyright (c)2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdint.h>
  17. #include <time.h>
  18. #include <errno.h>
  19. #include "node/Constants.hpp"
  20. #ifdef __WINDOWS__
  21. #include <WinSock2.h>
  22. #include <Windows.h>
  23. #include <tchar.h>
  24. #include <wchar.h>
  25. #include <lmcons.h>
  26. #include <newdev.h>
  27. #include <atlbase.h>
  28. #include <iphlpapi.h>
  29. #include <iomanip>
  30. #include "osdep/WindowsEthernetTap.hpp"
  31. #include "windows/ZeroTierOne/ServiceInstaller.h"
  32. #include "windows/ZeroTierOne/ServiceBase.h"
  33. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  34. #else
  35. #include <unistd.h>
  36. #include <pwd.h>
  37. #include <fcntl.h>
  38. #include <sys/types.h>
  39. #include <sys/stat.h>
  40. #include <sys/uio.h>
  41. #include <dirent.h>
  42. #include <signal.h>
  43. #ifdef __LINUX__
  44. #include <sys/prctl.h>
  45. #include <sys/syscall.h>
  46. #include <sys/wait.h>
  47. #include <net/if.h>
  48. #include <sys/types.h>
  49. #include <sys/socket.h>
  50. #include <ifaddrs.h>
  51. #include <sys/ioctl.h>
  52. #ifndef ZT_NO_CAPABILITIES
  53. #include <linux/capability.h>
  54. #include <linux/securebits.h>
  55. #endif
  56. #endif
  57. #endif
  58. #include <string>
  59. #include <stdexcept>
  60. #include <iostream>
  61. #include <sstream>
  62. #include <algorithm>
  63. #include "version.h"
  64. #include "include/ZeroTierOne.h"
  65. #include "node/Identity.hpp"
  66. #include "node/CertificateOfMembership.hpp"
  67. #include "node/Utils.hpp"
  68. #include "node/NetworkController.hpp"
  69. #include "node/Buffer.hpp"
  70. #include "node/World.hpp"
  71. #include "osdep/OSUtils.hpp"
  72. #include "osdep/Http.hpp"
  73. #include "osdep/Thread.hpp"
  74. #include "node/BondController.hpp"
  75. #include "service/OneService.hpp"
  76. #include "ext/json/json.hpp"
  77. #ifdef __APPLE__
  78. #include <SystemConfiguration/SystemConfiguration.h>
  79. #include <sys/types.h>
  80. #include <sys/socket.h>
  81. #include <ifaddrs.h>
  82. #endif
  83. #define ZT_PID_PATH "zerotier-one.pid"
  84. using namespace ZeroTier;
  85. static OneService *volatile zt1Service = (OneService *)0;
  86. #define PROGRAM_NAME "ZeroTier One"
  87. #define COPYRIGHT_NOTICE "Copyright (c) 2020 ZeroTier, Inc."
  88. #define LICENSE_GRANT "Licensed under the ZeroTier BSL 1.1 (see LICENSE.txt)"
  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," peers - List all peers (prettier)" ZT_EOL_S);
  115. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  116. fprintf(out," join <network ID> - Join a network" ZT_EOL_S);
  117. fprintf(out," leave <network ID> - Leave a network" ZT_EOL_S);
  118. fprintf(out," set <network ID> <setting> - Set a network setting" ZT_EOL_S);
  119. fprintf(out," get <network ID> <setting> - Get a network setting" ZT_EOL_S);
  120. fprintf(out," listmoons - List moons (federated root sets)" ZT_EOL_S);
  121. fprintf(out," orbit <world ID> <seed> - Join a moon via any member root" ZT_EOL_S);
  122. fprintf(out," deorbit <world ID> - Leave a moon" ZT_EOL_S);
  123. fprintf(out,ZT_EOL_S"Available settings:" ZT_EOL_S);
  124. fprintf(out," Settings to use with [get/set] may include property names from " ZT_EOL_S);
  125. fprintf(out," the JSON output of \"zerotier-cli -j listnetworks\". Additionally, " ZT_EOL_S);
  126. fprintf(out," (ip, ip4, ip6, ip6plane, and ip6prefix can be used). For instance:" ZT_EOL_S);
  127. fprintf(out," zerotier-cli get <network ID> ip6plane will return the 6PLANE address" ZT_EOL_S);
  128. fprintf(out," assigned to this node." ZT_EOL_S);
  129. }
  130. static std::string cliFixJsonCRs(const std::string &s)
  131. {
  132. std::string r;
  133. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  134. if (*c == '\n')
  135. r.append(ZT_EOL_S);
  136. else r.push_back(*c);
  137. }
  138. return r;
  139. }
  140. #ifdef __WINDOWS__
  141. static int cli(int argc, _TCHAR* argv[])
  142. #else
  143. static int cli(int argc,char **argv)
  144. #endif
  145. {
  146. unsigned int port = 0;
  147. std::string homeDir,command,arg1,arg2,authToken;
  148. std::string ip("127.0.0.1");
  149. bool json = false;
  150. for(int i=1;i<argc;++i) {
  151. if (argv[i][0] == '-') {
  152. switch(argv[i][1]) {
  153. case 'q': // ignore -q used to invoke this personality
  154. if (argv[i][2]) {
  155. cliPrintHelp(argv[0],stdout);
  156. return 1;
  157. }
  158. break;
  159. case 'j':
  160. if (argv[i][2]) {
  161. cliPrintHelp(argv[0],stdout);
  162. return 1;
  163. }
  164. json = true;
  165. break;
  166. case 'p':
  167. port = Utils::strToUInt(argv[i] + 2);
  168. if ((port > 0xffff)||(port == 0)) {
  169. cliPrintHelp(argv[0],stdout);
  170. return 1;
  171. }
  172. break;
  173. case 'D':
  174. if (argv[i][2]) {
  175. homeDir = argv[i] + 2;
  176. } else {
  177. cliPrintHelp(argv[0],stdout);
  178. return 1;
  179. }
  180. break;
  181. case 'H':
  182. if (argv[i][2]) {
  183. ip = argv[i] + 2;
  184. } else {
  185. cliPrintHelp(argv[0],stdout);
  186. return 1;
  187. }
  188. break;
  189. case 'T':
  190. if (argv[i][2]) {
  191. authToken = argv[i] + 2;
  192. } else {
  193. cliPrintHelp(argv[0],stdout);
  194. return 1;
  195. }
  196. break;
  197. case 'v':
  198. if (argv[i][2]) {
  199. cliPrintHelp(argv[0],stdout);
  200. return 1;
  201. }
  202. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  203. return 0;
  204. case 'h':
  205. case '?':
  206. default:
  207. cliPrintHelp(argv[0],stdout);
  208. return 0;
  209. }
  210. } else {
  211. if (arg1.length())
  212. arg2 = argv[i];
  213. else if (command.length())
  214. arg1 = argv[i];
  215. else command = argv[i];
  216. }
  217. }
  218. if (!homeDir.length())
  219. homeDir = OneService::platformDefaultHomePath();
  220. // TODO: cleanup this logic
  221. // A lot of generic CLI errors land here; missing admin rights cause a bit of this.
  222. if ((!port)||(!authToken.length())) {
  223. if (!homeDir.length()) {
  224. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  225. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  226. return 2;
  227. }
  228. if (!port) {
  229. std::string portStr;
  230. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  231. port = Utils::strToUInt(portStr.c_str());
  232. if ((port == 0)||(port > 0xffff)) {
  233. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  234. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  235. return 2;
  236. }
  237. }
  238. if (!authToken.length()) {
  239. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  240. #ifdef __UNIX_LIKE__
  241. if (!authToken.length()) {
  242. const char *hd = getenv("HOME");
  243. if (hd) {
  244. char p[4096];
  245. #ifdef __APPLE__
  246. OSUtils::ztsnprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  247. #else
  248. OSUtils::ztsnprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  249. #endif
  250. OSUtils::readFile(p,authToken);
  251. }
  252. }
  253. #endif
  254. if (!authToken.length()) {
  255. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  256. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  257. return 2;
  258. }
  259. }
  260. }
  261. InetAddress addr;
  262. {
  263. char addrtmp[256];
  264. OSUtils::ztsnprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  265. addr = InetAddress(addrtmp);
  266. }
  267. std::map<std::string,std::string> requestHeaders;
  268. std::map<std::string,std::string> responseHeaders;
  269. std::string responseBody;
  270. requestHeaders["X-ZT1-Auth"] = authToken;
  271. if ((command.length() > 0)&&(command[0] == '/')) {
  272. unsigned int scode = Http::GET(
  273. 1024 * 1024 * 16,
  274. 60000,
  275. (const struct sockaddr *)&addr,
  276. command.c_str(),
  277. requestHeaders,
  278. responseHeaders,
  279. responseBody);
  280. if (scode == 200) {
  281. printf("%s", cliFixJsonCRs(responseBody).c_str());
  282. return 0;
  283. } else {
  284. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  285. return 1;
  286. }
  287. } else if ((command == "info")||(command == "status")) {
  288. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  289. if (scode == 0) {
  290. 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());
  291. return 1;
  292. }
  293. nlohmann::json j;
  294. try {
  295. j = OSUtils::jsonParse(responseBody);
  296. } catch (std::exception &exc) {
  297. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  298. return 1;
  299. } catch ( ... ) {
  300. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  301. return 1;
  302. }
  303. if (scode == 200) {
  304. if (json) {
  305. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  306. } else {
  307. if (j.is_object()) {
  308. printf("200 info %s %s %s" ZT_EOL_S,
  309. OSUtils::jsonString(j["address"],"-").c_str(),
  310. OSUtils::jsonString(j["version"],"-").c_str(),
  311. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  312. }
  313. }
  314. return 0;
  315. } else {
  316. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  317. return 1;
  318. }
  319. } else if (command == "listpeers") {
  320. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  321. if (scode == 0) {
  322. 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());
  323. return 1;
  324. }
  325. nlohmann::json j;
  326. try {
  327. j = OSUtils::jsonParse(responseBody);
  328. } catch (std::exception &exc) {
  329. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  330. return 1;
  331. } catch ( ... ) {
  332. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  333. return 1;
  334. }
  335. if (scode == 200) {
  336. if (json) {
  337. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  338. } else {
  339. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  340. if (j.is_array()) {
  341. for(unsigned long k=0;k<j.size();++k) {
  342. nlohmann::json &p = j[k];
  343. std::string bestPath;
  344. nlohmann::json &paths = p["paths"];
  345. if (paths.is_array()) {
  346. for(unsigned long i=0;i<paths.size();++i) {
  347. nlohmann::json &path = paths[i];
  348. if (path["preferred"]) {
  349. char tmp[256];
  350. std::string addr = path["address"];
  351. const int64_t now = OSUtils::now();
  352. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s;%lld;%lld",addr.c_str(),now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"]);
  353. bestPath = tmp;
  354. break;
  355. }
  356. }
  357. }
  358. if (bestPath.length() == 0) bestPath = "-";
  359. char ver[128];
  360. int64_t vmaj = p["versionMajor"];
  361. int64_t vmin = p["versionMinor"];
  362. int64_t vrev = p["versionRev"];
  363. if (vmaj >= 0) {
  364. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  365. } else {
  366. ver[0] = '-';
  367. ver[1] = (char)0;
  368. }
  369. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  370. OSUtils::jsonString(p["address"],"-").c_str(),
  371. bestPath.c_str(),
  372. (int)OSUtils::jsonInt(p["latency"],0),
  373. ver,
  374. OSUtils::jsonString(p["role"],"-").c_str());
  375. }
  376. }
  377. }
  378. return 0;
  379. } else {
  380. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  381. return 1;
  382. }
  383. } else if (command == "peers") {
  384. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  385. if (scode == 0) {
  386. 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());
  387. return 1;
  388. }
  389. nlohmann::json j;
  390. try {
  391. j = OSUtils::jsonParse(responseBody);
  392. } catch (std::exception &exc) {
  393. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  394. return 1;
  395. } catch ( ... ) {
  396. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  397. return 1;
  398. }
  399. if (scode == 200) {
  400. if (json) {
  401. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  402. } else {
  403. printf("200 peers\n<ztaddr> <ver> <role> <lat> <link> <lastTX> <lastRX> <path>" ZT_EOL_S);
  404. if (j.is_array()) {
  405. for(unsigned long k=0;k<j.size();++k) {
  406. nlohmann::json &p = j[k];
  407. std::string bestPath;
  408. nlohmann::json &paths = p["paths"];
  409. if (paths.is_array()) {
  410. for(unsigned long i=0;i<paths.size();++i) {
  411. nlohmann::json &path = paths[i];
  412. if (path["preferred"]) {
  413. char tmp[256];
  414. std::string addr = path["address"];
  415. const int64_t now = OSUtils::now();
  416. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%-8lld %-8lld %s",now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"],addr.c_str());
  417. bestPath = std::string("DIRECT ") + tmp;
  418. break;
  419. }
  420. }
  421. }
  422. if (bestPath.length() == 0) bestPath = "RELAY";
  423. char ver[128];
  424. int64_t vmaj = p["versionMajor"];
  425. int64_t vmin = p["versionMinor"];
  426. int64_t vrev = p["versionRev"];
  427. if (vmaj >= 0) {
  428. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  429. } else {
  430. ver[0] = '-';
  431. ver[1] = (char)0;
  432. }
  433. printf("%s %-6s %-6s %5d %s" ZT_EOL_S,
  434. OSUtils::jsonString(p["address"],"-").c_str(),
  435. ver,
  436. OSUtils::jsonString(p["role"],"-").c_str(),
  437. (int)OSUtils::jsonInt(p["latency"],0),
  438. bestPath.c_str());
  439. }
  440. }
  441. }
  442. return 0;
  443. } else {
  444. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  445. return 1;
  446. }
  447. } else if (command == "listbonds") {
  448. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  449. if (scode == 0) {
  450. 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());
  451. return 1;
  452. }
  453. nlohmann::json j;
  454. try {
  455. j = OSUtils::jsonParse(responseBody);
  456. } catch (std::exception &exc) {
  457. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  458. return 1;
  459. } catch ( ... ) {
  460. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  461. return 1;
  462. }
  463. if (scode == 200) {
  464. if (json) {
  465. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  466. } else {
  467. bool bFoundBond = false;
  468. printf(" <peer> <bondtype> <status> <links>" ZT_EOL_S);
  469. if (j.is_array()) {
  470. for(unsigned long k=0;k<j.size();++k) {
  471. nlohmann::json &p = j[k];
  472. bool isBonded = p["isBonded"];
  473. int8_t bondingPolicy = p["bondingPolicy"];
  474. bool isHealthy = p["isHealthy"];
  475. int8_t numAliveLinks = p["numAliveLinks"];
  476. int8_t numTotalLinks = p["numTotalLinks"];
  477. if (isBonded) {
  478. bFoundBond = true;
  479. std::string healthStr;
  480. if (isHealthy) {
  481. healthStr = "HEALTHY";
  482. } else {
  483. healthStr = "DEGRADED";
  484. }
  485. std::string policyStr = "none";
  486. if (bondingPolicy >= ZT_BONDING_POLICY_NONE && bondingPolicy <= ZT_BONDING_POLICY_BALANCE_AWARE) {
  487. policyStr = BondController::getPolicyStrByCode(bondingPolicy);
  488. }
  489. printf("%10s %32s %8s %d/%d" ZT_EOL_S,
  490. OSUtils::jsonString(p ["address"],"-").c_str(),
  491. policyStr.c_str(),
  492. healthStr.c_str(),
  493. numAliveLinks,
  494. numTotalLinks);
  495. }
  496. }
  497. }
  498. if (!bFoundBond) {
  499. printf(" NONE\t\t\t\tNONE\t NONE NONE" ZT_EOL_S);
  500. }
  501. }
  502. return 0;
  503. } else {
  504. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  505. return 1;
  506. }
  507. } else if (command == "listnetworks") {
  508. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  509. if (scode == 0) {
  510. 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());
  511. return 1;
  512. }
  513. nlohmann::json j;
  514. try {
  515. j = OSUtils::jsonParse(responseBody);
  516. } catch (std::exception &exc) {
  517. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  518. return 1;
  519. } catch ( ... ) {
  520. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  521. return 1;
  522. }
  523. if (scode == 200) {
  524. if (json) {
  525. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  526. } else {
  527. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  528. if (j.is_array()) {
  529. for(unsigned long i=0;i<j.size();++i) {
  530. nlohmann::json &n = j[i];
  531. if (n.is_object()) {
  532. std::string aa;
  533. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  534. if (assignedAddresses.is_array()) {
  535. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  536. nlohmann::json &addr = assignedAddresses[j];
  537. if (addr.is_string()) {
  538. if (aa.length() > 0) aa.push_back(',');
  539. aa.append(addr.get<std::string>());
  540. }
  541. }
  542. }
  543. if (aa.length() == 0) aa = "-";
  544. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  545. OSUtils::jsonString(n["nwid"],"-").c_str(),
  546. OSUtils::jsonString(n["name"],"-").c_str(),
  547. OSUtils::jsonString(n["mac"],"-").c_str(),
  548. OSUtils::jsonString(n["status"],"-").c_str(),
  549. OSUtils::jsonString(n["type"],"-").c_str(),
  550. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  551. aa.c_str());
  552. }
  553. }
  554. }
  555. }
  556. return 0;
  557. } else {
  558. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  559. return 1;
  560. }
  561. } else if (command == "join") {
  562. if (arg1.length() != 16) {
  563. printf("invalid network id" ZT_EOL_S);
  564. return 2;
  565. }
  566. requestHeaders["Content-Type"] = "application/json";
  567. requestHeaders["Content-Length"] = "2";
  568. unsigned int scode = Http::POST(
  569. 1024 * 1024 * 16,
  570. 60000,
  571. (const struct sockaddr *)&addr,
  572. (std::string("/network/") + arg1).c_str(),
  573. requestHeaders,
  574. "{}",
  575. 2,
  576. responseHeaders,
  577. responseBody);
  578. if (scode == 200) {
  579. if (json) {
  580. printf("%s",cliFixJsonCRs(responseBody).c_str());
  581. } else {
  582. printf("200 join OK" ZT_EOL_S);
  583. }
  584. return 0;
  585. } else {
  586. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  587. return 1;
  588. }
  589. } else if (command == "leave") {
  590. if (arg1.length() != 16) {
  591. printf("invalid network id" ZT_EOL_S);
  592. return 2;
  593. }
  594. unsigned int scode = Http::DEL(
  595. 1024 * 1024 * 16,
  596. 60000,
  597. (const struct sockaddr *)&addr,
  598. (std::string("/network/") + arg1).c_str(),
  599. requestHeaders,
  600. responseHeaders,
  601. responseBody);
  602. if (scode == 200) {
  603. if (json) {
  604. printf("%s",cliFixJsonCRs(responseBody).c_str());
  605. } else {
  606. printf("200 leave OK" ZT_EOL_S);
  607. }
  608. return 0;
  609. } else {
  610. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  611. return 1;
  612. }
  613. } else if (command == "listmoons") {
  614. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/moon",requestHeaders,responseHeaders,responseBody);
  615. if (scode == 0) {
  616. 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());
  617. return 1;
  618. }
  619. nlohmann::json j;
  620. try {
  621. j = OSUtils::jsonParse(responseBody);
  622. } catch (std::exception &exc) {
  623. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  624. return 1;
  625. } catch ( ... ) {
  626. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  627. return 1;
  628. }
  629. if (scode == 200) {
  630. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  631. return 0;
  632. } else {
  633. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  634. return 1;
  635. }
  636. } else if (command == "orbit") {
  637. const uint64_t worldId = Utils::hexStrToU64(arg1.c_str());
  638. const uint64_t seed = Utils::hexStrToU64(arg2.c_str());
  639. if ((worldId)&&(seed)) {
  640. char jsons[1024];
  641. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"seed\":\"%s\"}",arg2.c_str());
  642. char cl[128];
  643. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  644. requestHeaders["Content-Type"] = "application/json";
  645. requestHeaders["Content-Length"] = cl;
  646. unsigned int scode = Http::POST(
  647. 1024 * 1024 * 16,
  648. 60000,
  649. (const struct sockaddr *)&addr,
  650. (std::string("/moon/") + arg1).c_str(),
  651. requestHeaders,
  652. jsons,
  653. (unsigned long)strlen(jsons),
  654. responseHeaders,
  655. responseBody);
  656. if (scode == 200) {
  657. printf("200 orbit OK" ZT_EOL_S);
  658. return 0;
  659. } else {
  660. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  661. return 1;
  662. }
  663. }
  664. } else if (command == "deorbit") {
  665. unsigned int scode = Http::DEL(
  666. 1024 * 1024 * 16,
  667. 60000,
  668. (const struct sockaddr *)&addr,
  669. (std::string("/moon/") + arg1).c_str(),
  670. requestHeaders,
  671. responseHeaders,
  672. responseBody);
  673. if (scode == 200) {
  674. if (json) {
  675. printf("%s",cliFixJsonCRs(responseBody).c_str());
  676. } else {
  677. printf("200 deorbit OK" ZT_EOL_S);
  678. }
  679. return 0;
  680. } else {
  681. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  682. return 1;
  683. }
  684. } else if (command == "set") {
  685. if (arg1.length() != 16) {
  686. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  687. return 2;
  688. }
  689. if (!arg2.length()) {
  690. fprintf(stderr,"invalid format: include a property name to set\n");
  691. return 2;
  692. }
  693. std::size_t eqidx = arg2.find('=');
  694. if (eqidx != std::string::npos) {
  695. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")||(arg2.substr(0,eqidx) == "allowDNS")) {
  696. char jsons[1024];
  697. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  698. arg2.substr(0,eqidx).c_str(),
  699. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  700. char cl[128];
  701. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  702. requestHeaders["Content-Type"] = "application/json";
  703. requestHeaders["Content-Length"] = cl;
  704. unsigned int scode = Http::POST(
  705. 1024 * 1024 * 16,
  706. 60000,
  707. (const struct sockaddr *)&addr,
  708. (std::string("/network/") + arg1).c_str(),
  709. requestHeaders,
  710. jsons,
  711. (unsigned long)strlen(jsons),
  712. responseHeaders,
  713. responseBody);
  714. if (scode == 200) {
  715. printf("%s",cliFixJsonCRs(responseBody).c_str());
  716. return 0;
  717. } else {
  718. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  719. return 1;
  720. }
  721. }
  722. } else {
  723. cliPrintHelp(argv[0],stderr);
  724. return 2;
  725. }
  726. } else if (command == "get") {
  727. if (arg1.length() != 16) {
  728. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  729. return 2;
  730. }
  731. if (!arg2.length()) {
  732. fprintf(stderr,"invalid format: include a property name to get\n");
  733. return 2;
  734. }
  735. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  736. if (scode == 0) {
  737. 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());
  738. return 1;
  739. }
  740. nlohmann::json j;
  741. try {
  742. j = OSUtils::jsonParse(responseBody);
  743. } catch (std::exception &exc) {
  744. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  745. return 1;
  746. } catch ( ... ) {
  747. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  748. return 1;
  749. }
  750. bool bNetworkFound = false;
  751. if (j.is_array()) {
  752. for(unsigned long i=0;i<j.size();++i) {
  753. nlohmann::json &n = j[i];
  754. if (n.is_object()) {
  755. if (n["id"] == arg1) {
  756. bNetworkFound = true;
  757. std::string aa;
  758. if (arg2 != "ip" && arg2 != "ip4" && arg2 != "ip6" && arg2 != "ip6plane" && arg2 != "ip6prefix") {
  759. aa.append(OSUtils::jsonString(n[arg2],"-")); // Standard network property field
  760. if (aa == "-") {
  761. printf("error, unknown property name\n");
  762. break;
  763. }
  764. printf("%s\n",aa.c_str());
  765. break;
  766. }
  767. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  768. if (assignedAddresses.is_array()) {
  769. int matchingIdxs[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
  770. int addressCountOfType = 0;
  771. for (int k = 0; k<std::min(ZT_MAX_ZT_ASSIGNED_ADDRESSES, (int)assignedAddresses.size());++k) {
  772. nlohmann::json &addr = assignedAddresses[k];
  773. if ((arg2 == "ip4" && addr.get<std::string>().find(".") != std::string::npos)
  774. || ((arg2.find("ip6") == 0) && addr.get<std::string>().find(":") != std::string::npos)
  775. || (arg2 == "ip")
  776. ) {
  777. matchingIdxs[addressCountOfType++] = k;
  778. }
  779. }
  780. for (int k=0; k<addressCountOfType; k++) {
  781. nlohmann::json &addr = assignedAddresses[matchingIdxs[k]];
  782. if (!addr.is_string()) {
  783. continue;
  784. }
  785. if (arg2.find("ip6p") == 0) {
  786. if (arg2 == "ip6plane") {
  787. if (addr.get<std::string>().find("fc") == 0) {
  788. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  789. if (k < addressCountOfType-1) aa.append("\n");
  790. }
  791. }
  792. if (arg2 == "ip6prefix") {
  793. if (addr.get<std::string>().find("fc") == 0) {
  794. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")).substr(0,24));
  795. if (k < addressCountOfType-1) aa.append("\n");
  796. }
  797. }
  798. }
  799. else {
  800. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  801. if (k < addressCountOfType-1) aa.append("\n");
  802. }
  803. }
  804. }
  805. printf("%s\n",aa.c_str());
  806. }
  807. }
  808. }
  809. }
  810. if (!bNetworkFound) {
  811. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  812. }
  813. if (scode == 200) {
  814. return 0;
  815. } else {
  816. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  817. return 1;
  818. }
  819. } else if (command == "dump") {
  820. std::stringstream dump;
  821. dump << "platform: ";
  822. #ifdef __APPLE__
  823. dump << "macOS" << ZT_EOL_S;
  824. #elif defined(_WIN32)
  825. dump << "Windows" << ZT_EOL_S;
  826. #else
  827. dump << "other unix based OS" << ZT_EOL_S;
  828. #endif
  829. dump << "zerotier version: " << ZEROTIER_ONE_VERSION_MAJOR << "."
  830. << ZEROTIER_ONE_VERSION_MINOR << "." << ZEROTIER_ONE_VERSION_REVISION << ZT_EOL_S << ZT_EOL_S;
  831. // grab status
  832. dump << "status" << ZT_EOL_S << "------" << ZT_EOL_S;
  833. unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  834. if (scode != 200) {
  835. 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());
  836. return 1;
  837. }
  838. dump << responseBody << ZT_EOL_S;
  839. responseHeaders.clear();
  840. responseBody = "";
  841. // grab network list
  842. dump << ZT_EOL_S << "networks" << ZT_EOL_S << "--------" << ZT_EOL_S;
  843. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  844. if (scode != 200) {
  845. 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());
  846. return 1;
  847. }
  848. dump << responseBody << ZT_EOL_S;
  849. responseHeaders.clear();
  850. responseBody = "";
  851. // list peers
  852. dump << ZT_EOL_S << "peers" << ZT_EOL_S << "-----" << ZT_EOL_S;
  853. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  854. if (scode != 200) {
  855. 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());
  856. return 1;
  857. }
  858. dump << responseBody << ZT_EOL_S;
  859. // get bonds
  860. dump << ZT_EOL_S << "bonds" << ZT_EOL_S << "-----" << ZT_EOL_S;
  861. scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  862. if (scode != 200) {
  863. 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());
  864. return 1;
  865. }
  866. dump << responseBody << ZT_EOL_S;
  867. responseHeaders.clear();
  868. responseBody = "";
  869. dump << ZT_EOL_S << "local.conf" << ZT_EOL_S << "----------" << ZT_EOL_S;
  870. std::string localConf;
  871. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "local.conf").c_str(), localConf);
  872. if (localConf.empty()) {
  873. dump << "None Present" << ZT_EOL_S;
  874. }
  875. else {
  876. dump << localConf << ZT_EOL_S;
  877. }
  878. dump << ZT_EOL_S << "Network Interfaces" << ZT_EOL_S << "------------------" << ZT_EOL_S << ZT_EOL_S;
  879. #ifdef __APPLE__
  880. CFArrayRef interfaces = SCNetworkInterfaceCopyAll();
  881. CFIndex size = CFArrayGetCount(interfaces);
  882. for(CFIndex i = 0; i < size; ++i) {
  883. SCNetworkInterfaceRef iface = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(interfaces, i);
  884. dump << "Interface " << i << ZT_EOL_S << "-----------" << ZT_EOL_S;
  885. CFStringRef tmp = SCNetworkInterfaceGetBSDName(iface);
  886. char stringBuffer[512] = {};
  887. CFStringGetCString(tmp,stringBuffer, sizeof(stringBuffer), kCFStringEncodingUTF8);
  888. dump << "Name: " << stringBuffer << ZT_EOL_S;
  889. std::string ifName(stringBuffer);
  890. int mtuCur, mtuMin, mtuMax;
  891. SCNetworkInterfaceCopyMTU(iface, &mtuCur, &mtuMin, &mtuMax);
  892. dump << "MTU: " << mtuCur << ZT_EOL_S;
  893. tmp = SCNetworkInterfaceGetHardwareAddressString(iface);
  894. CFStringGetCString(tmp, stringBuffer, sizeof(stringBuffer), kCFStringEncodingUTF8);
  895. dump << "MAC: " << stringBuffer << ZT_EOL_S;
  896. tmp = SCNetworkInterfaceGetInterfaceType(iface);
  897. CFStringGetCString(tmp, stringBuffer, sizeof(stringBuffer), kCFStringEncodingUTF8);
  898. dump << "Type: " << stringBuffer << ZT_EOL_S;
  899. dump << "Addresses:" << ZT_EOL_S;
  900. struct ifaddrs *ifap, *ifa;
  901. void *addr;
  902. getifaddrs(&ifap);
  903. for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
  904. if (strcmp(ifName.c_str(), ifa->ifa_name) == 0) {
  905. if (ifa->ifa_addr->sa_family == AF_INET) {
  906. struct sockaddr_in *ipv4 = (struct sockaddr_in*)ifa->ifa_addr;
  907. addr = &ipv4->sin_addr;
  908. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  909. struct sockaddr_in6 *ipv6 = (struct sockaddr_in6*)ifa->ifa_addr;
  910. addr = &ipv6->sin6_addr;
  911. } else {
  912. continue;
  913. }
  914. inet_ntop(ifa->ifa_addr->sa_family, addr, stringBuffer, sizeof(stringBuffer));
  915. dump << stringBuffer << ZT_EOL_S;
  916. }
  917. }
  918. dump << ZT_EOL_S;
  919. }
  920. #elif defined(_WIN32)
  921. ULONG buffLen = 16384;
  922. PIP_ADAPTER_ADDRESSES addresses;
  923. ULONG ret = 0;
  924. do {
  925. addresses = (PIP_ADAPTER_ADDRESSES)malloc(buffLen);
  926. ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, addresses, &buffLen);
  927. if (ret == ERROR_BUFFER_OVERFLOW) {
  928. free(addresses);
  929. addresses = NULL;
  930. }
  931. else {
  932. break;
  933. }
  934. } while (ret == ERROR_BUFFER_OVERFLOW);
  935. int i = 0;
  936. if (ret == NO_ERROR) {
  937. PIP_ADAPTER_ADDRESSES curAddr = addresses;
  938. while (curAddr) {
  939. dump << "Interface " << i << ZT_EOL_S << "-----------" << ZT_EOL_S;
  940. dump << "Name: " << curAddr->AdapterName << ZT_EOL_S;
  941. dump << "MTU: " << curAddr->Mtu << ZT_EOL_S;
  942. dump << "MAC: ";
  943. char macBuffer[64] = {};
  944. sprintf(macBuffer, "%02x:%02x:%02x:%02x:%02x:%02x",
  945. curAddr->PhysicalAddress[0],
  946. curAddr->PhysicalAddress[1],
  947. curAddr->PhysicalAddress[2],
  948. curAddr->PhysicalAddress[3],
  949. curAddr->PhysicalAddress[4],
  950. curAddr->PhysicalAddress[5]);
  951. dump << macBuffer << ZT_EOL_S;
  952. dump << "Type: " << curAddr->IfType << ZT_EOL_S;
  953. dump << "Addresses:" << ZT_EOL_S;
  954. PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
  955. pUnicast = curAddr->FirstUnicastAddress;
  956. if (pUnicast) {
  957. for (int j = 0; pUnicast != NULL; ++j) {
  958. char buf[128] = {};
  959. DWORD bufLen = 128;
  960. LPSOCKADDR a = pUnicast->Address.lpSockaddr;
  961. WSAAddressToStringA(
  962. pUnicast->Address.lpSockaddr,
  963. pUnicast->Address.iSockaddrLength,
  964. NULL,
  965. buf,
  966. &bufLen
  967. );
  968. dump << buf << ZT_EOL_S;
  969. pUnicast = pUnicast->Next;
  970. }
  971. }
  972. curAddr = curAddr->Next;
  973. ++i;
  974. }
  975. }
  976. if (addresses) {
  977. free(addresses);
  978. addresses = NULL;
  979. }
  980. #elif defined(__LINUX__)
  981. struct ifreq ifr;
  982. struct ifconf ifc;
  983. char buf[1024];
  984. char stringBuffer[128];
  985. int success = 0;
  986. int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
  987. ifc.ifc_len = sizeof(buf);
  988. ifc.ifc_buf = buf;
  989. ioctl(sock, SIOCGIFCONF, &ifc);
  990. struct ifreq *it = ifc.ifc_req;
  991. const struct ifreq * const end = it + (ifc.ifc_len / sizeof(struct ifreq));
  992. int count = 0;
  993. for(; it != end; ++it) {
  994. strcpy(ifr.ifr_name, it->ifr_name);
  995. if(ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
  996. if (!(ifr.ifr_flags & IFF_LOOPBACK)) { // skip loopback
  997. dump << "Interface " << count++ << ZT_EOL_S << "-----------" << ZT_EOL_S;
  998. dump << "Name: " << ifr.ifr_name << ZT_EOL_S;
  999. if (ioctl(sock, SIOCGIFMTU, &ifr) == 0) {
  1000. dump << "MTU: " << ifr.ifr_mtu << ZT_EOL_S;
  1001. }
  1002. if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
  1003. unsigned char mac_addr[6];
  1004. memcpy(mac_addr, ifr.ifr_hwaddr.sa_data, 6);
  1005. char macStr[16];
  1006. sprintf(macStr, "%02x:%02x:%02x:%02x:%02x:%02x",
  1007. mac_addr[0],
  1008. mac_addr[1],
  1009. mac_addr[2],
  1010. mac_addr[3],
  1011. mac_addr[4],
  1012. mac_addr[5]);
  1013. dump << "MAC: " << macStr << ZT_EOL_S;
  1014. }
  1015. dump << "Addresses: " << ZT_EOL_S;
  1016. struct ifaddrs *ifap, *ifa;
  1017. void *addr;
  1018. getifaddrs(&ifap);
  1019. for(ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1020. if(strcmp(ifr.ifr_name, ifa->ifa_name) == 0) {
  1021. if(ifa->ifa_addr->sa_family == AF_INET) {
  1022. struct sockaddr_in *ipv4 = (struct sockaddr_in*)ifa->ifa_addr;
  1023. addr = &ipv4->sin_addr;
  1024. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  1025. struct sockaddr_in6 *ipv6 = (struct sockaddr_in6*)ifa->ifa_addr;
  1026. addr = &ipv6->sin6_addr;
  1027. } else {
  1028. continue;
  1029. }
  1030. inet_ntop(ifa->ifa_addr->sa_family, addr, stringBuffer, sizeof(stringBuffer));
  1031. dump << stringBuffer << ZT_EOL_S;
  1032. }
  1033. }
  1034. }
  1035. }
  1036. }
  1037. close(sock);
  1038. char cwd[PATH_MAX];
  1039. getcwd(cwd, sizeof(cwd));
  1040. sprintf(cwd, "%s%szerotier_dump.txt", cwd, ZT_PATH_SEPARATOR_S);
  1041. fprintf(stdout, "Writing dump to: %s\n", cwd);
  1042. int fd = open(cwd, O_CREAT|O_RDWR,0664);
  1043. if (fd == -1) {
  1044. fprintf(stderr, "Error creating file.\n");
  1045. }
  1046. write(fd, dump.str().c_str(), dump.str().size());
  1047. close(fd);
  1048. #endif
  1049. // fprintf(stderr, "%s\n", dump.str().c_str());
  1050. } else {
  1051. cliPrintHelp(argv[0],stderr);
  1052. return 0;
  1053. }
  1054. return 0;
  1055. }
  1056. /****************************************************************************/
  1057. /* zerotier-idtool personality */
  1058. /****************************************************************************/
  1059. static void idtoolPrintHelp(FILE *out,const char *pn)
  1060. {
  1061. fprintf(out,
  1062. "%s version %d.%d.%d" ZT_EOL_S,
  1063. PROGRAM_NAME,
  1064. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1065. fprintf(out,
  1066. COPYRIGHT_NOTICE ZT_EOL_S
  1067. LICENSE_GRANT ZT_EOL_S);
  1068. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  1069. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  1070. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  1071. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  1072. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  1073. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  1074. fprintf(out," initmoon <identity.public of first seed>" ZT_EOL_S);
  1075. fprintf(out," genmoon <moon json>" ZT_EOL_S);
  1076. }
  1077. static Identity getIdFromArg(char *arg)
  1078. {
  1079. Identity id;
  1080. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  1081. if (id.fromString(arg))
  1082. return id;
  1083. } else { // identity is to be read from a file
  1084. std::string idser;
  1085. if (OSUtils::readFile(arg,idser)) {
  1086. if (id.fromString(idser.c_str()))
  1087. return id;
  1088. }
  1089. }
  1090. return Identity();
  1091. }
  1092. #ifdef __WINDOWS__
  1093. static int idtool(int argc, _TCHAR* argv[])
  1094. #else
  1095. static int idtool(int argc,char **argv)
  1096. #endif
  1097. {
  1098. if (argc < 2) {
  1099. idtoolPrintHelp(stdout,argv[0]);
  1100. return 1;
  1101. }
  1102. if (!strcmp(argv[1],"generate")) {
  1103. uint64_t vanity = 0;
  1104. int vanityBits = 0;
  1105. if (argc >= 5) {
  1106. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  1107. vanityBits = 4 * (int)strlen(argv[4]);
  1108. if (vanityBits > 40)
  1109. vanityBits = 40;
  1110. }
  1111. Identity id;
  1112. for(;;) {
  1113. id.generate();
  1114. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  1115. if (vanityBits > 0) {
  1116. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  1117. }
  1118. break;
  1119. } else {
  1120. 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)));
  1121. }
  1122. }
  1123. char idtmp[1024];
  1124. std::string idser = id.toString(true,idtmp);
  1125. if (argc >= 3) {
  1126. if (!OSUtils::writeFile(argv[2],idser)) {
  1127. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  1128. return 1;
  1129. } else printf("%s written" ZT_EOL_S,argv[2]);
  1130. if (argc >= 4) {
  1131. idser = id.toString(false,idtmp);
  1132. if (!OSUtils::writeFile(argv[3],idser)) {
  1133. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  1134. return 1;
  1135. } else printf("%s written" ZT_EOL_S,argv[3]);
  1136. }
  1137. } else printf("%s",idser.c_str());
  1138. } else if (!strcmp(argv[1],"validate")) {
  1139. if (argc < 3) {
  1140. idtoolPrintHelp(stdout,argv[0]);
  1141. return 1;
  1142. }
  1143. Identity id = getIdFromArg(argv[2]);
  1144. if (!id) {
  1145. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1146. return 1;
  1147. }
  1148. if (!id.locallyValidate()) {
  1149. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  1150. return 1;
  1151. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  1152. } else if (!strcmp(argv[1],"getpublic")) {
  1153. if (argc < 3) {
  1154. idtoolPrintHelp(stdout,argv[0]);
  1155. return 1;
  1156. }
  1157. Identity id = getIdFromArg(argv[2]);
  1158. if (!id) {
  1159. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1160. return 1;
  1161. }
  1162. char idtmp[1024];
  1163. printf("%s",id.toString(false,idtmp));
  1164. } else if (!strcmp(argv[1],"sign")) {
  1165. if (argc < 4) {
  1166. idtoolPrintHelp(stdout,argv[0]);
  1167. return 1;
  1168. }
  1169. Identity id = getIdFromArg(argv[2]);
  1170. if (!id) {
  1171. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1172. return 1;
  1173. }
  1174. if (!id.hasPrivate()) {
  1175. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  1176. return 1;
  1177. }
  1178. std::string inf;
  1179. if (!OSUtils::readFile(argv[3],inf)) {
  1180. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  1181. return 1;
  1182. }
  1183. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  1184. char hexbuf[1024];
  1185. printf("%s",Utils::hex(signature.data,ZT_C25519_SIGNATURE_LEN,hexbuf));
  1186. } else if (!strcmp(argv[1],"verify")) {
  1187. if (argc < 5) {
  1188. idtoolPrintHelp(stdout,argv[0]);
  1189. return 1;
  1190. }
  1191. Identity id = getIdFromArg(argv[2]);
  1192. if (!id) {
  1193. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  1194. return 1;
  1195. }
  1196. std::string inf;
  1197. if (!OSUtils::readFile(argv[3],inf)) {
  1198. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  1199. return 1;
  1200. }
  1201. char buf[4096];
  1202. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  1203. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  1204. printf("%s signature valid" ZT_EOL_S,argv[3]);
  1205. } else {
  1206. signature.clear();
  1207. if (OSUtils::readFile(argv[4],signature)) {
  1208. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  1209. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  1210. printf("%s signature valid" ZT_EOL_S,argv[3]);
  1211. } else {
  1212. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  1213. return 1;
  1214. }
  1215. } else {
  1216. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  1217. return 1;
  1218. }
  1219. }
  1220. } else if (!strcmp(argv[1],"initmoon")) {
  1221. if (argc < 3) {
  1222. idtoolPrintHelp(stdout,argv[0]);
  1223. } else {
  1224. const Identity id = getIdFromArg(argv[2]);
  1225. if (!id) {
  1226. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  1227. return 1;
  1228. }
  1229. C25519::Pair kp(C25519::generate());
  1230. char idtmp[4096];
  1231. nlohmann::json mj;
  1232. mj["objtype"] = "world";
  1233. mj["worldType"] = "moon";
  1234. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,ZT_C25519_PUBLIC_KEY_LEN,idtmp);
  1235. mj["signingKey_SECRET"] = Utils::hex(kp.priv.data,ZT_C25519_PRIVATE_KEY_LEN,idtmp);
  1236. mj["id"] = id.address().toString(idtmp);
  1237. nlohmann::json seedj;
  1238. seedj["identity"] = id.toString(false,idtmp);
  1239. seedj["stableEndpoints"] = nlohmann::json::array();
  1240. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  1241. std::string mjd(OSUtils::jsonDump(mj));
  1242. printf("%s" ZT_EOL_S,mjd.c_str());
  1243. }
  1244. } else if (!strcmp(argv[1],"genmoon")) {
  1245. if (argc < 3) {
  1246. idtoolPrintHelp(stdout,argv[0]);
  1247. } else {
  1248. std::string buf;
  1249. if (!OSUtils::readFile(argv[2],buf)) {
  1250. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  1251. return 1;
  1252. }
  1253. nlohmann::json mj(OSUtils::jsonParse(buf));
  1254. const uint64_t id = Utils::hexStrToU64(OSUtils::jsonString(mj["id"],"0").c_str());
  1255. if (!id) {
  1256. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  1257. return 1;
  1258. }
  1259. World::Type t;
  1260. if (mj["worldType"] == "moon") {
  1261. t = World::TYPE_MOON;
  1262. } else if (mj["worldType"] == "planet") {
  1263. t = World::TYPE_PLANET;
  1264. } else {
  1265. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  1266. return 1;
  1267. }
  1268. C25519::Pair signingKey;
  1269. C25519::Public updatesMustBeSignedBy;
  1270. Utils::unhex(OSUtils::jsonString(mj["signingKey"],"").c_str(),signingKey.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  1271. Utils::unhex(OSUtils::jsonString(mj["signingKey_SECRET"],"").c_str(),signingKey.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  1272. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],"").c_str(),updatesMustBeSignedBy.data,ZT_C25519_PUBLIC_KEY_LEN);
  1273. std::vector<World::Root> roots;
  1274. nlohmann::json &rootsj = mj["roots"];
  1275. if (rootsj.is_array()) {
  1276. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  1277. nlohmann::json &r = rootsj[i];
  1278. if (r.is_object()) {
  1279. roots.push_back(World::Root());
  1280. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],"").c_str());
  1281. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  1282. if (stableEndpointsj.is_array()) {
  1283. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  1284. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"").c_str()));
  1285. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  1286. }
  1287. }
  1288. }
  1289. }
  1290. std::sort(roots.begin(),roots.end());
  1291. const int64_t now = OSUtils::now();
  1292. World w(World::make(t,id,now,updatesMustBeSignedBy,roots,signingKey));
  1293. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  1294. w.serialize(wbuf);
  1295. char fn[128];
  1296. OSUtils::ztsnprintf(fn,sizeof(fn),"%.16llx.moon",w.id());
  1297. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  1298. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  1299. }
  1300. } else {
  1301. idtoolPrintHelp(stdout,argv[0]);
  1302. return 1;
  1303. }
  1304. return 0;
  1305. }
  1306. /****************************************************************************/
  1307. /* Unix helper functions and signal handlers */
  1308. /****************************************************************************/
  1309. #ifdef __UNIX_LIKE__
  1310. static void _sighandlerHup(int sig)
  1311. {
  1312. }
  1313. static void _sighandlerQuit(int sig)
  1314. {
  1315. OneService *s = zt1Service;
  1316. if (s)
  1317. s->terminate();
  1318. else exit(0);
  1319. }
  1320. #endif
  1321. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  1322. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  1323. #ifndef PR_CAP_AMBIENT
  1324. #define PR_CAP_AMBIENT 47
  1325. #define PR_CAP_AMBIENT_IS_SET 1
  1326. #define PR_CAP_AMBIENT_RAISE 2
  1327. #define PR_CAP_AMBIENT_LOWER 3
  1328. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  1329. #endif
  1330. #define ZT_LINUX_USER "zerotier-one"
  1331. #define ZT_HAVE_DROP_PRIVILEGES 1
  1332. namespace {
  1333. // libc doesn't export capset, it is instead located in libcap
  1334. // We ignore libcap and call it manually.
  1335. struct cap_header_struct {
  1336. __u32 version;
  1337. int pid;
  1338. };
  1339. struct cap_data_struct {
  1340. __u32 effective;
  1341. __u32 permitted;
  1342. __u32 inheritable;
  1343. };
  1344. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  1345. static void _notDropping(const char *procName,const std::string &homeDir)
  1346. {
  1347. struct stat buf;
  1348. if (lstat(homeDir.c_str(),&buf) < 0) {
  1349. if (buf.st_uid != 0 || buf.st_gid != 0) {
  1350. 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);
  1351. exit(1);
  1352. }
  1353. }
  1354. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  1355. }
  1356. static int _setCapabilities(int flags)
  1357. {
  1358. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  1359. cap_data_struct capdata;
  1360. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  1361. return _zt_capset(&capheader, &capdata);
  1362. }
  1363. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  1364. {
  1365. struct dirent de;
  1366. struct dirent *dptr;
  1367. lchown(path,uid,gid);
  1368. DIR *d = opendir(path);
  1369. if (!d)
  1370. return;
  1371. dptr = (struct dirent *)0;
  1372. for(;;) {
  1373. if (readdir_r(d,&de,&dptr) != 0)
  1374. break;
  1375. if (!dptr)
  1376. break;
  1377. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  1378. std::string p(path);
  1379. p.push_back(ZT_PATH_SEPARATOR);
  1380. p.append(dptr->d_name);
  1381. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  1382. }
  1383. }
  1384. closedir(d);
  1385. }
  1386. static void dropPrivileges(const char *procName,const std::string &homeDir)
  1387. {
  1388. if (getuid() != 0)
  1389. return;
  1390. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  1391. // and CAP_NET_RAW capabilities.
  1392. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  1393. if (!targetUser)
  1394. return;
  1395. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  1396. // Kernel has no support for ambient capabilities.
  1397. _notDropping(procName,homeDir);
  1398. return;
  1399. }
  1400. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  1401. _notDropping(procName,homeDir);
  1402. return;
  1403. }
  1404. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  1405. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  1406. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1407. _notDropping(procName,homeDir);
  1408. return;
  1409. }
  1410. int oldDumpable = prctl(PR_GET_DUMPABLE);
  1411. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  1412. // Disable ptracing. Otherwise there is a small window when previous
  1413. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  1414. // (this is mitigated anyway on most distros by ptrace_scope=1)
  1415. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1416. exit(1);
  1417. }
  1418. // Relinquish root
  1419. if (setgid(targetUser->pw_gid) < 0) {
  1420. perror("setgid");
  1421. exit(1);
  1422. }
  1423. if (setuid(targetUser->pw_uid) < 0) {
  1424. perror("setuid");
  1425. exit(1);
  1426. }
  1427. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1428. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  1429. exit(1);
  1430. }
  1431. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  1432. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1433. exit(1);
  1434. }
  1435. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  1436. 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);
  1437. exit(1);
  1438. }
  1439. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  1440. 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);
  1441. exit(1);
  1442. }
  1443. }
  1444. } // anonymous namespace
  1445. #endif // __LINUX__
  1446. /****************************************************************************/
  1447. /* Windows helper functions and signal handlers */
  1448. /****************************************************************************/
  1449. #ifdef __WINDOWS__
  1450. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  1451. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  1452. {
  1453. switch(dwCtrlType) {
  1454. case CTRL_C_EVENT:
  1455. case CTRL_BREAK_EVENT:
  1456. case CTRL_CLOSE_EVENT:
  1457. case CTRL_SHUTDOWN_EVENT:
  1458. OneService *s = zt1Service;
  1459. if (s)
  1460. s->terminate();
  1461. return TRUE;
  1462. }
  1463. return FALSE;
  1464. }
  1465. // TODO: revisit this with https://support.microsoft.com/en-us/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh
  1466. static void _winPokeAHole()
  1467. {
  1468. char myPath[MAX_PATH];
  1469. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1470. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1471. STARTUPINFOA startupInfo;
  1472. PROCESS_INFORMATION processInfo;
  1473. startupInfo.cb = sizeof(startupInfo);
  1474. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1475. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1476. 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)) {
  1477. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1478. CloseHandle(processInfo.hProcess);
  1479. CloseHandle(processInfo.hThread);
  1480. }
  1481. startupInfo.cb = sizeof(startupInfo);
  1482. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1483. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1484. 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)) {
  1485. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1486. CloseHandle(processInfo.hProcess);
  1487. CloseHandle(processInfo.hThread);
  1488. }
  1489. startupInfo.cb = sizeof(startupInfo);
  1490. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1491. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1492. 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)) {
  1493. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1494. CloseHandle(processInfo.hProcess);
  1495. CloseHandle(processInfo.hThread);
  1496. }
  1497. }
  1498. }
  1499. // Returns true if this is running as the local administrator
  1500. static BOOL IsCurrentUserLocalAdministrator(void)
  1501. {
  1502. BOOL fReturn = FALSE;
  1503. DWORD dwStatus;
  1504. DWORD dwAccessMask;
  1505. DWORD dwAccessDesired;
  1506. DWORD dwACLSize;
  1507. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1508. PACL pACL = NULL;
  1509. PSID psidAdmin = NULL;
  1510. HANDLE hToken = NULL;
  1511. HANDLE hImpersonationToken = NULL;
  1512. PRIVILEGE_SET ps;
  1513. GENERIC_MAPPING GenericMapping;
  1514. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1515. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1516. const DWORD ACCESS_READ = 1;
  1517. const DWORD ACCESS_WRITE = 2;
  1518. __try
  1519. {
  1520. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1521. {
  1522. if (GetLastError() != ERROR_NO_TOKEN)
  1523. __leave;
  1524. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1525. __leave;
  1526. }
  1527. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1528. __leave;
  1529. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1530. SECURITY_BUILTIN_DOMAIN_RID,
  1531. DOMAIN_ALIAS_RID_ADMINS,
  1532. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1533. __leave;
  1534. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1535. if (psdAdmin == NULL)
  1536. __leave;
  1537. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1538. __leave;
  1539. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1540. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1541. if (pACL == NULL)
  1542. __leave;
  1543. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1544. __leave;
  1545. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1546. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1547. __leave;
  1548. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1549. __leave;
  1550. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1551. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1552. if (!IsValidSecurityDescriptor(psdAdmin))
  1553. __leave;
  1554. dwAccessDesired = ACCESS_READ;
  1555. GenericMapping.GenericRead = ACCESS_READ;
  1556. GenericMapping.GenericWrite = ACCESS_WRITE;
  1557. GenericMapping.GenericExecute = 0;
  1558. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1559. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1560. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1561. &fReturn))
  1562. {
  1563. fReturn = FALSE;
  1564. __leave;
  1565. }
  1566. }
  1567. __finally
  1568. {
  1569. // Clean up.
  1570. if (pACL) LocalFree(pACL);
  1571. if (psdAdmin) LocalFree(psdAdmin);
  1572. if (psidAdmin) FreeSid(psidAdmin);
  1573. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1574. if (hToken) CloseHandle (hToken);
  1575. }
  1576. return fReturn;
  1577. }
  1578. #endif // __WINDOWS__
  1579. /****************************************************************************/
  1580. /* main() and friends */
  1581. /****************************************************************************/
  1582. static void printHelp(const char *cn,FILE *out)
  1583. {
  1584. fprintf(out,
  1585. "%s version %d.%d.%d" ZT_EOL_S,
  1586. PROGRAM_NAME,
  1587. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1588. fprintf(out,
  1589. COPYRIGHT_NOTICE ZT_EOL_S
  1590. LICENSE_GRANT ZT_EOL_S);
  1591. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1592. fprintf(out,"Available switches:" ZT_EOL_S);
  1593. fprintf(out," -h - Display this help" ZT_EOL_S);
  1594. fprintf(out," -v - Show version" ZT_EOL_S);
  1595. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1596. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1597. #ifdef __UNIX_LIKE__
  1598. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1599. #endif // __UNIX_LIKE__
  1600. #ifdef __WINDOWS__
  1601. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1602. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1603. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1604. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1605. #endif // __WINDOWS__
  1606. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1607. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1608. }
  1609. class _OneServiceRunner
  1610. {
  1611. public:
  1612. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1613. void threadMain()
  1614. throw()
  1615. {
  1616. try {
  1617. for(;;) {
  1618. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1619. switch(zt1Service->run()) {
  1620. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1621. case OneService::ONE_NORMAL_TERMINATION:
  1622. break;
  1623. case OneService::ONE_UNRECOVERABLE_ERROR:
  1624. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1625. returnValue = 1;
  1626. break;
  1627. case OneService::ONE_IDENTITY_COLLISION: {
  1628. delete zt1Service;
  1629. zt1Service = (OneService *)0;
  1630. std::string oldid;
  1631. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1632. if (oldid.length()) {
  1633. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1634. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1635. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1636. }
  1637. } continue; // restart!
  1638. }
  1639. break; // terminate loop -- normally we don't keep restarting
  1640. }
  1641. delete zt1Service;
  1642. zt1Service = (OneService *)0;
  1643. } catch ( ... ) {
  1644. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1645. returnValue = 1;
  1646. }
  1647. }
  1648. const char *progname;
  1649. unsigned int returnValue;
  1650. unsigned int port;
  1651. const std::string &homeDir;
  1652. };
  1653. #ifdef __WINDOWS__
  1654. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1655. #else
  1656. int main(int argc,char **argv)
  1657. #endif
  1658. {
  1659. #ifdef __UNIX_LIKE__
  1660. signal(SIGHUP,&_sighandlerHup);
  1661. signal(SIGPIPE,SIG_IGN);
  1662. signal(SIGIO,SIG_IGN);
  1663. signal(SIGUSR1,SIG_IGN);
  1664. signal(SIGUSR2,SIG_IGN);
  1665. signal(SIGALRM,SIG_IGN);
  1666. signal(SIGINT,&_sighandlerQuit);
  1667. signal(SIGTERM,&_sighandlerQuit);
  1668. signal(SIGQUIT,&_sighandlerQuit);
  1669. signal(SIGINT,&_sighandlerQuit);
  1670. /* Ensure that there are no inherited file descriptors open from a previous
  1671. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1672. * of it do not return, and should not do anything otherwise bad. */
  1673. {
  1674. int mfd = STDIN_FILENO;
  1675. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1676. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1677. for(int f=mfd+1;f<1024;++f)
  1678. ::close(f);
  1679. }
  1680. bool runAsDaemon = false;
  1681. #endif // __UNIX_LIKE__
  1682. #ifdef __WINDOWS__
  1683. {
  1684. WSADATA wsaData;
  1685. WSAStartup(MAKEWORD(2,2),&wsaData);
  1686. }
  1687. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1688. bool winRunFromCommandLine = true;
  1689. #else
  1690. bool winRunFromCommandLine = false;
  1691. #endif
  1692. #endif // __WINDOWS__
  1693. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1694. return idtool(argc,argv);
  1695. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1696. return cli(argc,argv);
  1697. std::string homeDir;
  1698. unsigned int port = ZT_DEFAULT_PORT;
  1699. bool skipRootCheck = false;
  1700. for(int i=1;i<argc;++i) {
  1701. if (argv[i][0] == '-') {
  1702. switch(argv[i][1]) {
  1703. case 'p': // port -- for both UDP and TCP, packets and control plane
  1704. port = Utils::strToUInt(argv[i] + 2);
  1705. if (port > 0xffff) {
  1706. printHelp(argv[0],stdout);
  1707. return 1;
  1708. }
  1709. break;
  1710. #ifdef __UNIX_LIKE__
  1711. case 'd': // Run in background as daemon
  1712. runAsDaemon = true;
  1713. break;
  1714. #endif // __UNIX_LIKE__
  1715. case 'U':
  1716. skipRootCheck = true;
  1717. break;
  1718. case 'v': // Display version
  1719. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1720. return 0;
  1721. case 'i': // Invoke idtool personality
  1722. if (argv[i][2]) {
  1723. printHelp(argv[0],stdout);
  1724. return 0;
  1725. } else return idtool(argc-1,argv+1);
  1726. case 'q': // Invoke cli personality
  1727. if (argv[i][2]) {
  1728. printHelp(argv[0],stdout);
  1729. return 0;
  1730. } else return cli(argc,argv);
  1731. #ifdef __WINDOWS__
  1732. case 'C': // Run from command line instead of as Windows service
  1733. winRunFromCommandLine = true;
  1734. break;
  1735. case 'I': { // Install this binary as a Windows service
  1736. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1737. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1738. return 1;
  1739. }
  1740. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1741. if (ret.length()) {
  1742. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1743. return 3;
  1744. }
  1745. return 0;
  1746. } break;
  1747. case 'R': { // Uninstall this binary as Windows service
  1748. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1749. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1750. return 1;
  1751. }
  1752. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1753. if (ret.length()) {
  1754. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1755. return 3;
  1756. }
  1757. return 0;
  1758. } break;
  1759. case 'D': {
  1760. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1761. if (err.length() > 0) {
  1762. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1763. return 3;
  1764. }
  1765. return 0;
  1766. } break;
  1767. #endif // __WINDOWS__
  1768. case 'h':
  1769. case '?':
  1770. default:
  1771. printHelp(argv[0],stdout);
  1772. return 0;
  1773. }
  1774. } else {
  1775. if (homeDir.length()) {
  1776. printHelp(argv[0],stdout);
  1777. return 0;
  1778. } else {
  1779. homeDir = argv[i];
  1780. }
  1781. }
  1782. }
  1783. if (!homeDir.length())
  1784. homeDir = OneService::platformDefaultHomePath();
  1785. if (!homeDir.length()) {
  1786. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1787. return 1;
  1788. } else {
  1789. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1790. std::string ptmp;
  1791. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1792. ptmp.push_back(ZT_PATH_SEPARATOR);
  1793. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1794. if (ptmp.length() > 0)
  1795. ptmp.push_back(ZT_PATH_SEPARATOR);
  1796. ptmp.append(*pi);
  1797. if ((*pi != ".")&&(*pi != "..")) {
  1798. if (!OSUtils::mkdir(ptmp))
  1799. throw std::runtime_error("home path does not exist, and could not create. Please verify local system permissions.");
  1800. }
  1801. }
  1802. }
  1803. // This can be removed once the new controller code has been around for many versions
  1804. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1805. 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());
  1806. return 1;
  1807. }
  1808. #ifdef __UNIX_LIKE__
  1809. #ifndef ZT_ONE_NO_ROOT_CHECK
  1810. if ((!skipRootCheck)&&(getuid() != 0)) {
  1811. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1812. return 1;
  1813. }
  1814. #endif // !ZT_ONE_NO_ROOT_CHECK
  1815. if (runAsDaemon) {
  1816. long p = (long)fork();
  1817. if (p < 0) {
  1818. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1819. return 1;
  1820. } else if (p > 0)
  1821. return 0; // forked
  1822. // else p == 0, so we are daemonized
  1823. }
  1824. #endif // __UNIX_LIKE__
  1825. #ifdef __WINDOWS__
  1826. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1827. // when tap instances are created.
  1828. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1829. if (winRunFromCommandLine) {
  1830. // Running in "interactive" mode (mostly for debugging)
  1831. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1832. if (!skipRootCheck) {
  1833. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1834. return 1;
  1835. }
  1836. } else {
  1837. _winPokeAHole();
  1838. }
  1839. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1840. // continues on to ordinary command line execution code below...
  1841. } else {
  1842. // Running from service manager
  1843. _winPokeAHole();
  1844. ZeroTierOneService zt1WindowsService;
  1845. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1846. return 0;
  1847. } else {
  1848. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1849. return 1;
  1850. }
  1851. }
  1852. #endif // __WINDOWS__
  1853. #ifdef __UNIX_LIKE__
  1854. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1855. if (!skipRootCheck)
  1856. dropPrivileges(argv[0],homeDir);
  1857. #endif
  1858. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1859. {
  1860. // Write .pid file to home folder
  1861. FILE *pf = fopen(pidPath.c_str(),"w");
  1862. if (pf) {
  1863. fprintf(pf,"%ld",(long)getpid());
  1864. fclose(pf);
  1865. }
  1866. }
  1867. #endif // __UNIX_LIKE__
  1868. _OneServiceRunner thr(argv[0],homeDir,port);
  1869. thr.threadMain();
  1870. //Thread::join(Thread::start(&thr));
  1871. #ifdef __UNIX_LIKE__
  1872. OSUtils::rm(pidPath.c_str());
  1873. #endif
  1874. return thr.returnValue;
  1875. }