one.cpp 67 KB

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