one.cpp 75 KB

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