1
0

one.cpp 77 KB

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