one.cpp 66 KB

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