one.cpp 77 KB

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