one.cpp 76 KB

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