one.cpp 75 KB

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