one.cpp 67 KB

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