one.cpp 76 KB

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