one.cpp 74 KB

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