one.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  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. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <stdint.h>
  17. #include <time.h>
  18. #include <errno.h>
  19. #include "node/Constants.hpp"
  20. #ifdef __WINDOWS__
  21. #include <WinSock2.h>
  22. #include <Windows.h>
  23. #include <tchar.h>
  24. #include <wchar.h>
  25. #include <lmcons.h>
  26. #include <newdev.h>
  27. #include <atlbase.h>
  28. #include "osdep/WindowsEthernetTap.hpp"
  29. #include "windows/ZeroTierOne/ServiceInstaller.h"
  30. #include "windows/ZeroTierOne/ServiceBase.h"
  31. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  32. #else
  33. #include <unistd.h>
  34. #include <pwd.h>
  35. #include <fcntl.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. #include <sys/uio.h>
  39. #include <dirent.h>
  40. #include <signal.h>
  41. #ifdef __LINUX__
  42. #include <sys/prctl.h>
  43. #include <sys/syscall.h>
  44. #include <sys/wait.h>
  45. #ifndef ZT_NO_CAPABILITIES
  46. #include <linux/capability.h>
  47. #include <linux/securebits.h>
  48. #endif
  49. #endif
  50. #endif
  51. #include <string>
  52. #include <stdexcept>
  53. #include <iostream>
  54. #include <sstream>
  55. #include <algorithm>
  56. #include "version.h"
  57. #include "include/ZeroTierOne.h"
  58. #include "node/Identity.hpp"
  59. #include "node/CertificateOfMembership.hpp"
  60. #include "node/Utils.hpp"
  61. #include "node/NetworkController.hpp"
  62. #include "node/Buffer.hpp"
  63. #include "node/World.hpp"
  64. #include "osdep/OSUtils.hpp"
  65. #include "osdep/Http.hpp"
  66. #include "osdep/Thread.hpp"
  67. #include "node/BondController.hpp"
  68. #include "service/OneService.hpp"
  69. #include "ext/json/json.hpp"
  70. #define ZT_PID_PATH "zerotier-one.pid"
  71. using namespace ZeroTier;
  72. static OneService *volatile zt1Service = (OneService *)0;
  73. #define PROGRAM_NAME "ZeroTier One"
  74. #define COPYRIGHT_NOTICE "Copyright (c) 2020 ZeroTier, Inc."
  75. #define LICENSE_GRANT "Licensed under the ZeroTier BSL 1.1 (see LICENSE.txt)"
  76. /****************************************************************************/
  77. /* zerotier-cli personality */
  78. /****************************************************************************/
  79. // This is getting deprecated soon in favor of the stuff in cli/
  80. static void cliPrintHelp(const char *pn,FILE *out)
  81. {
  82. fprintf(out,
  83. "%s version %d.%d.%d build %d (platform %d arch %d)" ZT_EOL_S,
  84. PROGRAM_NAME,
  85. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION, ZEROTIER_ONE_VERSION_BUILD,
  86. ZT_BUILD_PLATFORM, ZT_BUILD_ARCHITECTURE);
  87. fprintf(out,
  88. COPYRIGHT_NOTICE ZT_EOL_S
  89. LICENSE_GRANT ZT_EOL_S);
  90. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  91. fprintf(out,"Available switches:" ZT_EOL_S);
  92. fprintf(out," -h - Display this help" ZT_EOL_S);
  93. fprintf(out," -v - Show version" ZT_EOL_S);
  94. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  95. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  96. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  97. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  98. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  99. fprintf(out," info - Display status info" ZT_EOL_S);
  100. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  101. fprintf(out," peers - List all peers (prettier)" ZT_EOL_S);
  102. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  103. fprintf(out," join <network ID> - Join a network" ZT_EOL_S);
  104. fprintf(out," leave <network ID> - Leave a network" ZT_EOL_S);
  105. fprintf(out," set <network ID> <setting> - Set a network setting" ZT_EOL_S);
  106. fprintf(out," get <network ID> <setting> - Get a network setting" ZT_EOL_S);
  107. fprintf(out," listmoons - List moons (federated root sets)" ZT_EOL_S);
  108. fprintf(out," orbit <world ID> <seed> - Join a moon via any member root" ZT_EOL_S);
  109. fprintf(out," deorbit <world ID> - Leave a moon" ZT_EOL_S);
  110. fprintf(out,ZT_EOL_S"Available settings:" ZT_EOL_S);
  111. fprintf(out," Settings to use with [get/set] may include property names from " ZT_EOL_S);
  112. fprintf(out," the JSON output of \"zerotier-cli -j listnetworks\". Additionally, " ZT_EOL_S);
  113. fprintf(out," (ip, ip4, ip6, ip6plane, and ip6prefix can be used). For instance:" ZT_EOL_S);
  114. fprintf(out," zerotier-cli get <network ID> ip6plane will return the 6PLANE address" ZT_EOL_S);
  115. fprintf(out," assigned to this node." ZT_EOL_S);
  116. }
  117. static std::string cliFixJsonCRs(const std::string &s)
  118. {
  119. std::string r;
  120. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  121. if (*c == '\n')
  122. r.append(ZT_EOL_S);
  123. else r.push_back(*c);
  124. }
  125. return r;
  126. }
  127. #ifdef __WINDOWS__
  128. static int cli(int argc, _TCHAR* argv[])
  129. #else
  130. static int cli(int argc,char **argv)
  131. #endif
  132. {
  133. unsigned int port = 0;
  134. std::string homeDir,command,arg1,arg2,authToken;
  135. std::string ip("127.0.0.1");
  136. bool json = false;
  137. for(int i=1;i<argc;++i) {
  138. if (argv[i][0] == '-') {
  139. switch(argv[i][1]) {
  140. case 'q': // ignore -q used to invoke this personality
  141. if (argv[i][2]) {
  142. cliPrintHelp(argv[0],stdout);
  143. return 1;
  144. }
  145. break;
  146. case 'j':
  147. if (argv[i][2]) {
  148. cliPrintHelp(argv[0],stdout);
  149. return 1;
  150. }
  151. json = true;
  152. break;
  153. case 'p':
  154. port = Utils::strToUInt(argv[i] + 2);
  155. if ((port > 0xffff)||(port == 0)) {
  156. cliPrintHelp(argv[0],stdout);
  157. return 1;
  158. }
  159. break;
  160. case 'D':
  161. if (argv[i][2]) {
  162. homeDir = argv[i] + 2;
  163. } else {
  164. cliPrintHelp(argv[0],stdout);
  165. return 1;
  166. }
  167. break;
  168. case 'H':
  169. if (argv[i][2]) {
  170. ip = argv[i] + 2;
  171. } else {
  172. cliPrintHelp(argv[0],stdout);
  173. return 1;
  174. }
  175. break;
  176. case 'T':
  177. if (argv[i][2]) {
  178. authToken = argv[i] + 2;
  179. } else {
  180. cliPrintHelp(argv[0],stdout);
  181. return 1;
  182. }
  183. break;
  184. case 'v':
  185. if (argv[i][2]) {
  186. cliPrintHelp(argv[0],stdout);
  187. return 1;
  188. }
  189. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  190. return 0;
  191. case 'h':
  192. case '?':
  193. default:
  194. cliPrintHelp(argv[0],stdout);
  195. return 0;
  196. }
  197. } else {
  198. if (arg1.length())
  199. arg2 = argv[i];
  200. else if (command.length())
  201. arg1 = argv[i];
  202. else command = argv[i];
  203. }
  204. }
  205. if (!homeDir.length())
  206. homeDir = OneService::platformDefaultHomePath();
  207. // TODO: cleanup this logic
  208. // A lot of generic CLI errors land here; missing admin rights cause a bit of this.
  209. if ((!port)||(!authToken.length())) {
  210. if (!homeDir.length()) {
  211. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  212. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  213. return 2;
  214. }
  215. if (!port) {
  216. std::string portStr;
  217. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  218. port = Utils::strToUInt(portStr.c_str());
  219. if ((port == 0)||(port > 0xffff)) {
  220. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  221. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  222. return 2;
  223. }
  224. }
  225. if (!authToken.length()) {
  226. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  227. #ifdef __UNIX_LIKE__
  228. if (!authToken.length()) {
  229. const char *hd = getenv("HOME");
  230. if (hd) {
  231. char p[4096];
  232. #ifdef __APPLE__
  233. OSUtils::ztsnprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  234. #else
  235. OSUtils::ztsnprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  236. #endif
  237. OSUtils::readFile(p,authToken);
  238. }
  239. }
  240. #endif
  241. if (!authToken.length()) {
  242. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  243. fprintf(stderr, "If you did not, please run this command as an Administrator / sudo / Root user. Thanks!");
  244. return 2;
  245. }
  246. }
  247. }
  248. InetAddress addr;
  249. {
  250. char addrtmp[256];
  251. OSUtils::ztsnprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  252. addr = InetAddress(addrtmp);
  253. }
  254. std::map<std::string,std::string> requestHeaders;
  255. std::map<std::string,std::string> responseHeaders;
  256. std::string responseBody;
  257. requestHeaders["X-ZT1-Auth"] = authToken;
  258. if ((command.length() > 0)&&(command[0] == '/')) {
  259. unsigned int scode = Http::GET(
  260. 1024 * 1024 * 16,
  261. 60000,
  262. (const struct sockaddr *)&addr,
  263. command.c_str(),
  264. requestHeaders,
  265. responseHeaders,
  266. responseBody);
  267. if (scode == 200) {
  268. printf("%s", cliFixJsonCRs(responseBody).c_str());
  269. return 0;
  270. } else {
  271. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  272. return 1;
  273. }
  274. } else if ((command == "info")||(command == "status")) {
  275. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  276. if (scode == 0) {
  277. 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());
  278. return 1;
  279. }
  280. nlohmann::json j;
  281. try {
  282. j = OSUtils::jsonParse(responseBody);
  283. } catch (std::exception &exc) {
  284. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  285. return 1;
  286. } catch ( ... ) {
  287. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  288. return 1;
  289. }
  290. if (scode == 200) {
  291. if (json) {
  292. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  293. } else {
  294. if (j.is_object()) {
  295. printf("200 info %s %s %s" ZT_EOL_S,
  296. OSUtils::jsonString(j["address"],"-").c_str(),
  297. OSUtils::jsonString(j["version"],"-").c_str(),
  298. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  299. }
  300. }
  301. return 0;
  302. } else {
  303. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  304. return 1;
  305. }
  306. } else if (command == "listpeers") {
  307. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  308. if (scode == 0) {
  309. 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());
  310. return 1;
  311. }
  312. nlohmann::json j;
  313. try {
  314. j = OSUtils::jsonParse(responseBody);
  315. } catch (std::exception &exc) {
  316. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  317. return 1;
  318. } catch ( ... ) {
  319. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  320. return 1;
  321. }
  322. if (scode == 200) {
  323. if (json) {
  324. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  325. } else {
  326. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  327. if (j.is_array()) {
  328. for(unsigned long k=0;k<j.size();++k) {
  329. nlohmann::json &p = j[k];
  330. std::string bestPath;
  331. nlohmann::json &paths = p["paths"];
  332. if (paths.is_array()) {
  333. for(unsigned long i=0;i<paths.size();++i) {
  334. nlohmann::json &path = paths[i];
  335. if (path["preferred"]) {
  336. char tmp[256];
  337. std::string addr = path["address"];
  338. const int64_t now = OSUtils::now();
  339. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%s;%lld;%lld",addr.c_str(),now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"]);
  340. bestPath = tmp;
  341. break;
  342. }
  343. }
  344. }
  345. if (bestPath.length() == 0) bestPath = "-";
  346. char ver[128];
  347. int64_t vmaj = p["versionMajor"];
  348. int64_t vmin = p["versionMinor"];
  349. int64_t vrev = p["versionRev"];
  350. if (vmaj >= 0) {
  351. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  352. } else {
  353. ver[0] = '-';
  354. ver[1] = (char)0;
  355. }
  356. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  357. OSUtils::jsonString(p["address"],"-").c_str(),
  358. bestPath.c_str(),
  359. (int)OSUtils::jsonInt(p["latency"],0),
  360. ver,
  361. OSUtils::jsonString(p["role"],"-").c_str());
  362. }
  363. }
  364. }
  365. return 0;
  366. } else {
  367. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  368. return 1;
  369. }
  370. } else if (command == "peers") {
  371. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  372. if (scode == 0) {
  373. 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());
  374. return 1;
  375. }
  376. nlohmann::json j;
  377. try {
  378. j = OSUtils::jsonParse(responseBody);
  379. } catch (std::exception &exc) {
  380. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  381. return 1;
  382. } catch ( ... ) {
  383. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  384. return 1;
  385. }
  386. if (scode == 200) {
  387. if (json) {
  388. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  389. } else {
  390. printf("200 peers\n<ztaddr> <ver> <role> <lat> <link> <lastTX> <lastRX> <path>" ZT_EOL_S);
  391. if (j.is_array()) {
  392. for(unsigned long k=0;k<j.size();++k) {
  393. nlohmann::json &p = j[k];
  394. std::string bestPath;
  395. nlohmann::json &paths = p["paths"];
  396. if (paths.is_array()) {
  397. for(unsigned long i=0;i<paths.size();++i) {
  398. nlohmann::json &path = paths[i];
  399. if (path["preferred"]) {
  400. char tmp[256];
  401. std::string addr = path["address"];
  402. const int64_t now = OSUtils::now();
  403. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%-8lld %-8lld %s",now - (int64_t)path["lastSend"],now - (int64_t)path["lastReceive"],addr.c_str());
  404. bestPath = std::string("DIRECT ") + tmp;
  405. break;
  406. }
  407. }
  408. }
  409. if (bestPath.length() == 0) bestPath = "RELAY";
  410. char ver[128];
  411. int64_t vmaj = p["versionMajor"];
  412. int64_t vmin = p["versionMinor"];
  413. int64_t vrev = p["versionRev"];
  414. if (vmaj >= 0) {
  415. OSUtils::ztsnprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  416. } else {
  417. ver[0] = '-';
  418. ver[1] = (char)0;
  419. }
  420. printf("%s %-6s %-6s %5d %s" ZT_EOL_S,
  421. OSUtils::jsonString(p["address"],"-").c_str(),
  422. ver,
  423. OSUtils::jsonString(p["role"],"-").c_str(),
  424. (int)OSUtils::jsonInt(p["latency"],0),
  425. bestPath.c_str());
  426. }
  427. }
  428. }
  429. return 0;
  430. } else {
  431. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  432. return 1;
  433. }
  434. } else if (command == "listbonds") {
  435. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/bonds",requestHeaders,responseHeaders,responseBody);
  436. if (scode == 0) {
  437. 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());
  438. return 1;
  439. }
  440. nlohmann::json j;
  441. try {
  442. j = OSUtils::jsonParse(responseBody);
  443. } catch (std::exception &exc) {
  444. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  445. return 1;
  446. } catch ( ... ) {
  447. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  448. return 1;
  449. }
  450. if (scode == 200) {
  451. if (json) {
  452. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  453. } else {
  454. bool bFoundBond = false;
  455. printf(" <peer> <bondtype> <status> <links>" ZT_EOL_S);
  456. if (j.is_array()) {
  457. for(unsigned long k=0;k<j.size();++k) {
  458. nlohmann::json &p = j[k];
  459. bool isBonded = p["isBonded"];
  460. int8_t bondingPolicy = p["bondingPolicy"];
  461. bool isHealthy = p["isHealthy"];
  462. int8_t numAliveLinks = p["numAliveLinks"];
  463. int8_t numTotalLinks = p["numTotalLinks"];
  464. if (isBonded) {
  465. bFoundBond = true;
  466. std::string healthStr;
  467. if (isHealthy) {
  468. healthStr = "HEALTHY";
  469. } else {
  470. healthStr = "DEGRADED";
  471. }
  472. std::string policyStr = "none";
  473. if (bondingPolicy >= ZT_BONDING_POLICY_NONE && bondingPolicy <= ZT_BONDING_POLICY_BALANCE_AWARE) {
  474. policyStr = BondController::getPolicyStrByCode(bondingPolicy);
  475. }
  476. printf("%10s %32s %8s %d/%d" ZT_EOL_S,
  477. OSUtils::jsonString(p ["address"],"-").c_str(),
  478. policyStr.c_str(),
  479. healthStr.c_str(),
  480. numAliveLinks,
  481. numTotalLinks);
  482. }
  483. }
  484. }
  485. if (!bFoundBond) {
  486. printf(" NONE\t\t\t\tNONE\t NONE NONE" ZT_EOL_S);
  487. }
  488. }
  489. return 0;
  490. } else {
  491. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  492. return 1;
  493. }
  494. } else if (command == "listnetworks") {
  495. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  496. if (scode == 0) {
  497. 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());
  498. return 1;
  499. }
  500. nlohmann::json j;
  501. try {
  502. j = OSUtils::jsonParse(responseBody);
  503. } catch (std::exception &exc) {
  504. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  505. return 1;
  506. } catch ( ... ) {
  507. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  508. return 1;
  509. }
  510. if (scode == 200) {
  511. if (json) {
  512. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  513. } else {
  514. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  515. if (j.is_array()) {
  516. for(unsigned long i=0;i<j.size();++i) {
  517. nlohmann::json &n = j[i];
  518. if (n.is_object()) {
  519. std::string aa;
  520. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  521. if (assignedAddresses.is_array()) {
  522. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  523. nlohmann::json &addr = assignedAddresses[j];
  524. if (addr.is_string()) {
  525. if (aa.length() > 0) aa.push_back(',');
  526. aa.append(addr.get<std::string>());
  527. }
  528. }
  529. }
  530. if (aa.length() == 0) aa = "-";
  531. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  532. OSUtils::jsonString(n["nwid"],"-").c_str(),
  533. OSUtils::jsonString(n["name"],"-").c_str(),
  534. OSUtils::jsonString(n["mac"],"-").c_str(),
  535. OSUtils::jsonString(n["status"],"-").c_str(),
  536. OSUtils::jsonString(n["type"],"-").c_str(),
  537. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  538. aa.c_str());
  539. }
  540. }
  541. }
  542. }
  543. return 0;
  544. } else {
  545. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  546. return 1;
  547. }
  548. } else if (command == "join") {
  549. if (arg1.length() != 16) {
  550. printf("invalid network id" ZT_EOL_S);
  551. return 2;
  552. }
  553. requestHeaders["Content-Type"] = "application/json";
  554. requestHeaders["Content-Length"] = "2";
  555. unsigned int scode = Http::POST(
  556. 1024 * 1024 * 16,
  557. 60000,
  558. (const struct sockaddr *)&addr,
  559. (std::string("/network/") + arg1).c_str(),
  560. requestHeaders,
  561. "{}",
  562. 2,
  563. responseHeaders,
  564. responseBody);
  565. if (scode == 200) {
  566. if (json) {
  567. printf("%s",cliFixJsonCRs(responseBody).c_str());
  568. } else {
  569. printf("200 join OK" ZT_EOL_S);
  570. }
  571. return 0;
  572. } else {
  573. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  574. return 1;
  575. }
  576. } else if (command == "leave") {
  577. if (arg1.length() != 16) {
  578. printf("invalid network id" ZT_EOL_S);
  579. return 2;
  580. }
  581. unsigned int scode = Http::DEL(
  582. 1024 * 1024 * 16,
  583. 60000,
  584. (const struct sockaddr *)&addr,
  585. (std::string("/network/") + arg1).c_str(),
  586. requestHeaders,
  587. responseHeaders,
  588. responseBody);
  589. if (scode == 200) {
  590. if (json) {
  591. printf("%s",cliFixJsonCRs(responseBody).c_str());
  592. } else {
  593. printf("200 leave OK" ZT_EOL_S);
  594. }
  595. return 0;
  596. } else {
  597. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  598. return 1;
  599. }
  600. } else if (command == "listmoons") {
  601. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/moon",requestHeaders,responseHeaders,responseBody);
  602. if (scode == 0) {
  603. 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());
  604. return 1;
  605. }
  606. nlohmann::json j;
  607. try {
  608. j = OSUtils::jsonParse(responseBody);
  609. } catch (std::exception &exc) {
  610. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  611. return 1;
  612. } catch ( ... ) {
  613. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  614. return 1;
  615. }
  616. if (scode == 200) {
  617. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  618. return 0;
  619. } else {
  620. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  621. return 1;
  622. }
  623. } else if (command == "orbit") {
  624. const uint64_t worldId = Utils::hexStrToU64(arg1.c_str());
  625. const uint64_t seed = Utils::hexStrToU64(arg2.c_str());
  626. if ((worldId)&&(seed)) {
  627. char jsons[1024];
  628. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"seed\":\"%s\"}",arg2.c_str());
  629. char cl[128];
  630. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  631. requestHeaders["Content-Type"] = "application/json";
  632. requestHeaders["Content-Length"] = cl;
  633. unsigned int scode = Http::POST(
  634. 1024 * 1024 * 16,
  635. 60000,
  636. (const struct sockaddr *)&addr,
  637. (std::string("/moon/") + arg1).c_str(),
  638. requestHeaders,
  639. jsons,
  640. (unsigned long)strlen(jsons),
  641. responseHeaders,
  642. responseBody);
  643. if (scode == 200) {
  644. printf("200 orbit OK" ZT_EOL_S);
  645. return 0;
  646. } else {
  647. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  648. return 1;
  649. }
  650. }
  651. } else if (command == "deorbit") {
  652. unsigned int scode = Http::DEL(
  653. 1024 * 1024 * 16,
  654. 60000,
  655. (const struct sockaddr *)&addr,
  656. (std::string("/moon/") + arg1).c_str(),
  657. requestHeaders,
  658. responseHeaders,
  659. responseBody);
  660. if (scode == 200) {
  661. if (json) {
  662. printf("%s",cliFixJsonCRs(responseBody).c_str());
  663. } else {
  664. printf("200 deorbit OK" ZT_EOL_S);
  665. }
  666. return 0;
  667. } else {
  668. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  669. return 1;
  670. }
  671. } else if (command == "set") {
  672. if (arg1.length() != 16) {
  673. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  674. return 2;
  675. }
  676. if (!arg2.length()) {
  677. fprintf(stderr,"invalid format: include a property name to set\n");
  678. return 2;
  679. }
  680. std::size_t eqidx = arg2.find('=');
  681. if (eqidx != std::string::npos) {
  682. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")) {
  683. char jsons[1024];
  684. OSUtils::ztsnprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  685. arg2.substr(0,eqidx).c_str(),
  686. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  687. char cl[128];
  688. OSUtils::ztsnprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  689. requestHeaders["Content-Type"] = "application/json";
  690. requestHeaders["Content-Length"] = cl;
  691. unsigned int scode = Http::POST(
  692. 1024 * 1024 * 16,
  693. 60000,
  694. (const struct sockaddr *)&addr,
  695. (std::string("/network/") + arg1).c_str(),
  696. requestHeaders,
  697. jsons,
  698. (unsigned long)strlen(jsons),
  699. responseHeaders,
  700. responseBody);
  701. if (scode == 200) {
  702. printf("%s",cliFixJsonCRs(responseBody).c_str());
  703. return 0;
  704. } else {
  705. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  706. return 1;
  707. }
  708. }
  709. } else {
  710. cliPrintHelp(argv[0],stderr);
  711. return 2;
  712. }
  713. } else if (command == "get") {
  714. if (arg1.length() != 16) {
  715. fprintf(stderr,"invalid format: must be a 16-digit (network) ID\n");
  716. return 2;
  717. }
  718. if (!arg2.length()) {
  719. fprintf(stderr,"invalid format: include a property name to get\n");
  720. return 2;
  721. }
  722. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  723. if (scode == 0) {
  724. 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());
  725. return 1;
  726. }
  727. nlohmann::json j;
  728. try {
  729. j = OSUtils::jsonParse(responseBody);
  730. } catch (std::exception &exc) {
  731. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  732. return 1;
  733. } catch ( ... ) {
  734. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  735. return 1;
  736. }
  737. bool bNetworkFound = false;
  738. if (j.is_array()) {
  739. for(unsigned long i=0;i<j.size();++i) {
  740. nlohmann::json &n = j[i];
  741. if (n.is_object()) {
  742. if (n["id"] == arg1) {
  743. bNetworkFound = true;
  744. std::string aa;
  745. if (arg2 != "ip" && arg2 != "ip4" && arg2 != "ip6" && arg2 != "ip6plane" && arg2 != "ip6prefix") {
  746. aa.append(OSUtils::jsonString(n[arg2],"-")); // Standard network property field
  747. if (aa == "-") {
  748. printf("error, unknown property name\n");
  749. break;
  750. }
  751. printf("%s\n",aa.c_str());
  752. break;
  753. }
  754. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  755. if (assignedAddresses.is_array()) {
  756. int matchingIdxs[ZT_MAX_ZT_ASSIGNED_ADDRESSES];
  757. int addressCountOfType = 0;
  758. for (int k = 0; k<std::min(ZT_MAX_ZT_ASSIGNED_ADDRESSES, (int)assignedAddresses.size());++k) {
  759. nlohmann::json &addr = assignedAddresses[k];
  760. if ((arg2 == "ip4" && addr.get<std::string>().find(".") != std::string::npos)
  761. || ((arg2.find("ip6") == 0) && addr.get<std::string>().find(":") != std::string::npos)
  762. || (arg2 == "ip")
  763. ) {
  764. matchingIdxs[addressCountOfType++] = k;
  765. }
  766. }
  767. for (int k=0; k<addressCountOfType; k++) {
  768. nlohmann::json &addr = assignedAddresses[matchingIdxs[k]];
  769. if (!addr.is_string()) {
  770. continue;
  771. }
  772. if (arg2.find("ip6p") == 0) {
  773. if (arg2 == "ip6plane") {
  774. if (addr.get<std::string>().find("fc") == 0) {
  775. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  776. if (k < addressCountOfType-1) aa.append("\n");
  777. }
  778. }
  779. if (arg2 == "ip6prefix") {
  780. if (addr.get<std::string>().find("fc") == 0) {
  781. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")).substr(0,24));
  782. if (k < addressCountOfType-1) aa.append("\n");
  783. }
  784. }
  785. }
  786. else {
  787. aa.append(addr.get<std::string>().substr(0,addr.get<std::string>().find("/")));
  788. if (k < addressCountOfType-1) aa.append("\n");
  789. }
  790. }
  791. }
  792. printf("%s\n",aa.c_str());
  793. }
  794. }
  795. }
  796. }
  797. if (!bNetworkFound) {
  798. fprintf(stderr,"unknown network ID, check that you are a member of the network\n");
  799. }
  800. if (scode == 200) {
  801. return 0;
  802. } else {
  803. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  804. return 1;
  805. }
  806. } else {
  807. cliPrintHelp(argv[0],stderr);
  808. return 0;
  809. }
  810. return 0;
  811. }
  812. /****************************************************************************/
  813. /* zerotier-idtool personality */
  814. /****************************************************************************/
  815. static void idtoolPrintHelp(FILE *out,const char *pn)
  816. {
  817. fprintf(out,
  818. "%s version %d.%d.%d" ZT_EOL_S,
  819. PROGRAM_NAME,
  820. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  821. fprintf(out,
  822. COPYRIGHT_NOTICE ZT_EOL_S
  823. LICENSE_GRANT ZT_EOL_S);
  824. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  825. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  826. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  827. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  828. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  829. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  830. fprintf(out," initmoon <identity.public of first seed>" ZT_EOL_S);
  831. fprintf(out," genmoon <moon json>" ZT_EOL_S);
  832. }
  833. static Identity getIdFromArg(char *arg)
  834. {
  835. Identity id;
  836. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  837. if (id.fromString(arg))
  838. return id;
  839. } else { // identity is to be read from a file
  840. std::string idser;
  841. if (OSUtils::readFile(arg,idser)) {
  842. if (id.fromString(idser.c_str()))
  843. return id;
  844. }
  845. }
  846. return Identity();
  847. }
  848. #ifdef __WINDOWS__
  849. static int idtool(int argc, _TCHAR* argv[])
  850. #else
  851. static int idtool(int argc,char **argv)
  852. #endif
  853. {
  854. if (argc < 2) {
  855. idtoolPrintHelp(stdout,argv[0]);
  856. return 1;
  857. }
  858. if (!strcmp(argv[1],"generate")) {
  859. uint64_t vanity = 0;
  860. int vanityBits = 0;
  861. if (argc >= 5) {
  862. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  863. vanityBits = 4 * (int)strlen(argv[4]);
  864. if (vanityBits > 40)
  865. vanityBits = 40;
  866. }
  867. Identity id;
  868. for(;;) {
  869. id.generate();
  870. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  871. if (vanityBits > 0) {
  872. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  873. }
  874. break;
  875. } else {
  876. 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)));
  877. }
  878. }
  879. char idtmp[1024];
  880. std::string idser = id.toString(true,idtmp);
  881. if (argc >= 3) {
  882. if (!OSUtils::writeFile(argv[2],idser)) {
  883. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  884. return 1;
  885. } else printf("%s written" ZT_EOL_S,argv[2]);
  886. if (argc >= 4) {
  887. idser = id.toString(false,idtmp);
  888. if (!OSUtils::writeFile(argv[3],idser)) {
  889. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  890. return 1;
  891. } else printf("%s written" ZT_EOL_S,argv[3]);
  892. }
  893. } else printf("%s",idser.c_str());
  894. } else if (!strcmp(argv[1],"validate")) {
  895. if (argc < 3) {
  896. idtoolPrintHelp(stdout,argv[0]);
  897. return 1;
  898. }
  899. Identity id = getIdFromArg(argv[2]);
  900. if (!id) {
  901. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  902. return 1;
  903. }
  904. if (!id.locallyValidate()) {
  905. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  906. return 1;
  907. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  908. } else if (!strcmp(argv[1],"getpublic")) {
  909. if (argc < 3) {
  910. idtoolPrintHelp(stdout,argv[0]);
  911. return 1;
  912. }
  913. Identity id = getIdFromArg(argv[2]);
  914. if (!id) {
  915. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  916. return 1;
  917. }
  918. char idtmp[1024];
  919. printf("%s",id.toString(false,idtmp));
  920. } else if (!strcmp(argv[1],"sign")) {
  921. if (argc < 4) {
  922. idtoolPrintHelp(stdout,argv[0]);
  923. return 1;
  924. }
  925. Identity id = getIdFromArg(argv[2]);
  926. if (!id) {
  927. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  928. return 1;
  929. }
  930. if (!id.hasPrivate()) {
  931. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  932. return 1;
  933. }
  934. std::string inf;
  935. if (!OSUtils::readFile(argv[3],inf)) {
  936. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  937. return 1;
  938. }
  939. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  940. char hexbuf[1024];
  941. printf("%s",Utils::hex(signature.data,ZT_C25519_SIGNATURE_LEN,hexbuf));
  942. } else if (!strcmp(argv[1],"verify")) {
  943. if (argc < 5) {
  944. idtoolPrintHelp(stdout,argv[0]);
  945. return 1;
  946. }
  947. Identity id = getIdFromArg(argv[2]);
  948. if (!id) {
  949. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  950. return 1;
  951. }
  952. std::string inf;
  953. if (!OSUtils::readFile(argv[3],inf)) {
  954. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  955. return 1;
  956. }
  957. char buf[4096];
  958. std::string signature(buf,Utils::unhex(argv[4],buf,(unsigned int)sizeof(buf)));
  959. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  960. printf("%s signature valid" ZT_EOL_S,argv[3]);
  961. } else {
  962. signature.clear();
  963. if (OSUtils::readFile(argv[4],signature)) {
  964. signature.assign(buf,Utils::unhex(signature.c_str(),buf,(unsigned int)sizeof(buf)));
  965. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  966. printf("%s signature valid" ZT_EOL_S,argv[3]);
  967. } else {
  968. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  969. return 1;
  970. }
  971. } else {
  972. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  973. return 1;
  974. }
  975. }
  976. } else if (!strcmp(argv[1],"initmoon")) {
  977. if (argc < 3) {
  978. idtoolPrintHelp(stdout,argv[0]);
  979. } else {
  980. const Identity id = getIdFromArg(argv[2]);
  981. if (!id) {
  982. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  983. return 1;
  984. }
  985. C25519::Pair kp(C25519::generate());
  986. char idtmp[4096];
  987. nlohmann::json mj;
  988. mj["objtype"] = "world";
  989. mj["worldType"] = "moon";
  990. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,ZT_C25519_PUBLIC_KEY_LEN,idtmp);
  991. mj["signingKey_SECRET"] = Utils::hex(kp.priv.data,ZT_C25519_PRIVATE_KEY_LEN,idtmp);
  992. mj["id"] = id.address().toString(idtmp);
  993. nlohmann::json seedj;
  994. seedj["identity"] = id.toString(false,idtmp);
  995. seedj["stableEndpoints"] = nlohmann::json::array();
  996. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  997. std::string mjd(OSUtils::jsonDump(mj));
  998. printf("%s" ZT_EOL_S,mjd.c_str());
  999. }
  1000. } else if (!strcmp(argv[1],"genmoon")) {
  1001. if (argc < 3) {
  1002. idtoolPrintHelp(stdout,argv[0]);
  1003. } else {
  1004. std::string buf;
  1005. if (!OSUtils::readFile(argv[2],buf)) {
  1006. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  1007. return 1;
  1008. }
  1009. nlohmann::json mj(OSUtils::jsonParse(buf));
  1010. const uint64_t id = Utils::hexStrToU64(OSUtils::jsonString(mj["id"],"0").c_str());
  1011. if (!id) {
  1012. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  1013. return 1;
  1014. }
  1015. World::Type t;
  1016. if (mj["worldType"] == "moon") {
  1017. t = World::TYPE_MOON;
  1018. } else if (mj["worldType"] == "planet") {
  1019. t = World::TYPE_PLANET;
  1020. } else {
  1021. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  1022. return 1;
  1023. }
  1024. C25519::Pair signingKey;
  1025. C25519::Public updatesMustBeSignedBy;
  1026. Utils::unhex(OSUtils::jsonString(mj["signingKey"],"").c_str(),signingKey.pub.data,ZT_C25519_PUBLIC_KEY_LEN);
  1027. Utils::unhex(OSUtils::jsonString(mj["signingKey_SECRET"],"").c_str(),signingKey.priv.data,ZT_C25519_PRIVATE_KEY_LEN);
  1028. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],"").c_str(),updatesMustBeSignedBy.data,ZT_C25519_PUBLIC_KEY_LEN);
  1029. std::vector<World::Root> roots;
  1030. nlohmann::json &rootsj = mj["roots"];
  1031. if (rootsj.is_array()) {
  1032. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  1033. nlohmann::json &r = rootsj[i];
  1034. if (r.is_object()) {
  1035. roots.push_back(World::Root());
  1036. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],"").c_str());
  1037. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  1038. if (stableEndpointsj.is_array()) {
  1039. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  1040. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"").c_str()));
  1041. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  1042. }
  1043. }
  1044. }
  1045. }
  1046. std::sort(roots.begin(),roots.end());
  1047. const int64_t now = OSUtils::now();
  1048. World w(World::make(t,id,now,updatesMustBeSignedBy,roots,signingKey));
  1049. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  1050. w.serialize(wbuf);
  1051. char fn[128];
  1052. OSUtils::ztsnprintf(fn,sizeof(fn),"%.16llx.moon",w.id());
  1053. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  1054. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  1055. }
  1056. } else {
  1057. idtoolPrintHelp(stdout,argv[0]);
  1058. return 1;
  1059. }
  1060. return 0;
  1061. }
  1062. /****************************************************************************/
  1063. /* Unix helper functions and signal handlers */
  1064. /****************************************************************************/
  1065. #ifdef __UNIX_LIKE__
  1066. static void _sighandlerHup(int sig)
  1067. {
  1068. }
  1069. static void _sighandlerQuit(int sig)
  1070. {
  1071. OneService *s = zt1Service;
  1072. if (s)
  1073. s->terminate();
  1074. else exit(0);
  1075. }
  1076. #endif
  1077. // Drop privileges on Linux, if supported by libc etc. and "zerotier-one" user exists on system
  1078. #if defined(__LINUX__) && !defined(ZT_NO_CAPABILITIES)
  1079. #ifndef PR_CAP_AMBIENT
  1080. #define PR_CAP_AMBIENT 47
  1081. #define PR_CAP_AMBIENT_IS_SET 1
  1082. #define PR_CAP_AMBIENT_RAISE 2
  1083. #define PR_CAP_AMBIENT_LOWER 3
  1084. #define PR_CAP_AMBIENT_CLEAR_ALL 4
  1085. #endif
  1086. #define ZT_LINUX_USER "zerotier-one"
  1087. #define ZT_HAVE_DROP_PRIVILEGES 1
  1088. namespace {
  1089. // libc doesn't export capset, it is instead located in libcap
  1090. // We ignore libcap and call it manually.
  1091. struct cap_header_struct {
  1092. __u32 version;
  1093. int pid;
  1094. };
  1095. struct cap_data_struct {
  1096. __u32 effective;
  1097. __u32 permitted;
  1098. __u32 inheritable;
  1099. };
  1100. static inline int _zt_capset(cap_header_struct* hdrp, cap_data_struct* datap) { return syscall(SYS_capset, hdrp, datap); }
  1101. static void _notDropping(const char *procName,const std::string &homeDir)
  1102. {
  1103. struct stat buf;
  1104. if (lstat(homeDir.c_str(),&buf) < 0) {
  1105. if (buf.st_uid != 0 || buf.st_gid != 0) {
  1106. 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);
  1107. exit(1);
  1108. }
  1109. }
  1110. fprintf(stderr, "%s: WARNING: failed to drop privileges (kernel may not support required prctl features), running as root" ZT_EOL_S,procName);
  1111. }
  1112. static int _setCapabilities(int flags)
  1113. {
  1114. cap_header_struct capheader = {_LINUX_CAPABILITY_VERSION_1, 0};
  1115. cap_data_struct capdata;
  1116. capdata.inheritable = capdata.permitted = capdata.effective = flags;
  1117. return _zt_capset(&capheader, &capdata);
  1118. }
  1119. static void _recursiveChown(const char *path,uid_t uid,gid_t gid)
  1120. {
  1121. struct dirent de;
  1122. struct dirent *dptr;
  1123. lchown(path,uid,gid);
  1124. DIR *d = opendir(path);
  1125. if (!d)
  1126. return;
  1127. dptr = (struct dirent *)0;
  1128. for(;;) {
  1129. if (readdir_r(d,&de,&dptr) != 0)
  1130. break;
  1131. if (!dptr)
  1132. break;
  1133. if ((strcmp(dptr->d_name,".") != 0)&&(strcmp(dptr->d_name,"..") != 0)&&(strlen(dptr->d_name) > 0)) {
  1134. std::string p(path);
  1135. p.push_back(ZT_PATH_SEPARATOR);
  1136. p.append(dptr->d_name);
  1137. _recursiveChown(p.c_str(),uid,gid); // will just fail and return on regular files
  1138. }
  1139. }
  1140. closedir(d);
  1141. }
  1142. static void dropPrivileges(const char *procName,const std::string &homeDir)
  1143. {
  1144. if (getuid() != 0)
  1145. return;
  1146. // dropPrivileges switches to zerotier-one user while retaining CAP_NET_ADMIN
  1147. // and CAP_NET_RAW capabilities.
  1148. struct passwd *targetUser = getpwnam(ZT_LINUX_USER);
  1149. if (!targetUser)
  1150. return;
  1151. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, CAP_NET_RAW, 0, 0) < 0) {
  1152. // Kernel has no support for ambient capabilities.
  1153. _notDropping(procName,homeDir);
  1154. return;
  1155. }
  1156. if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NOROOT) < 0) {
  1157. _notDropping(procName,homeDir);
  1158. return;
  1159. }
  1160. // Change ownership of our home directory if everything looks good (does nothing if already chown'd)
  1161. _recursiveChown(homeDir.c_str(),targetUser->pw_uid,targetUser->pw_gid);
  1162. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_SETUID) | (1 << CAP_SETGID) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1163. _notDropping(procName,homeDir);
  1164. return;
  1165. }
  1166. int oldDumpable = prctl(PR_GET_DUMPABLE);
  1167. if (prctl(PR_SET_DUMPABLE, 0) < 0) {
  1168. // Disable ptracing. Otherwise there is a small window when previous
  1169. // compromised ZeroTier process could ptrace us, when we still have CAP_SETUID.
  1170. // (this is mitigated anyway on most distros by ptrace_scope=1)
  1171. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1172. exit(1);
  1173. }
  1174. // Relinquish root
  1175. if (setgid(targetUser->pw_gid) < 0) {
  1176. perror("setgid");
  1177. exit(1);
  1178. }
  1179. if (setuid(targetUser->pw_uid) < 0) {
  1180. perror("setuid");
  1181. exit(1);
  1182. }
  1183. if (_setCapabilities((1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW) | (1 << CAP_NET_BIND_SERVICE)) < 0) {
  1184. fprintf(stderr,"%s: FATAL: unable to drop capabilities after relinquishing root" ZT_EOL_S,procName);
  1185. exit(1);
  1186. }
  1187. if (prctl(PR_SET_DUMPABLE, oldDumpable) < 0) {
  1188. fprintf(stderr,"%s: FATAL: prctl(PR_SET_DUMPABLE) failed while attempting to relinquish root permissions" ZT_EOL_S,procName);
  1189. exit(1);
  1190. }
  1191. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_ADMIN, 0, 0) < 0) {
  1192. 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);
  1193. exit(1);
  1194. }
  1195. if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_NET_RAW, 0, 0) < 0) {
  1196. 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);
  1197. exit(1);
  1198. }
  1199. }
  1200. } // anonymous namespace
  1201. #endif // __LINUX__
  1202. /****************************************************************************/
  1203. /* Windows helper functions and signal handlers */
  1204. /****************************************************************************/
  1205. #ifdef __WINDOWS__
  1206. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  1207. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  1208. {
  1209. switch(dwCtrlType) {
  1210. case CTRL_C_EVENT:
  1211. case CTRL_BREAK_EVENT:
  1212. case CTRL_CLOSE_EVENT:
  1213. case CTRL_SHUTDOWN_EVENT:
  1214. OneService *s = zt1Service;
  1215. if (s)
  1216. s->terminate();
  1217. return TRUE;
  1218. }
  1219. return FALSE;
  1220. }
  1221. // TODO: revisit this with https://support.microsoft.com/en-us/help/947709/how-to-use-the-netsh-advfirewall-firewall-context-instead-of-the-netsh
  1222. static void _winPokeAHole()
  1223. {
  1224. char myPath[MAX_PATH];
  1225. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  1226. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  1227. STARTUPINFOA startupInfo;
  1228. PROCESS_INFORMATION processInfo;
  1229. startupInfo.cb = sizeof(startupInfo);
  1230. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1231. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1232. 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)) {
  1233. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1234. CloseHandle(processInfo.hProcess);
  1235. CloseHandle(processInfo.hThread);
  1236. }
  1237. startupInfo.cb = sizeof(startupInfo);
  1238. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1239. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1240. 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)) {
  1241. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1242. CloseHandle(processInfo.hProcess);
  1243. CloseHandle(processInfo.hThread);
  1244. }
  1245. startupInfo.cb = sizeof(startupInfo);
  1246. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  1247. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  1248. 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)) {
  1249. WaitForSingleObject(processInfo.hProcess,INFINITE);
  1250. CloseHandle(processInfo.hProcess);
  1251. CloseHandle(processInfo.hThread);
  1252. }
  1253. }
  1254. }
  1255. // Returns true if this is running as the local administrator
  1256. static BOOL IsCurrentUserLocalAdministrator(void)
  1257. {
  1258. BOOL fReturn = FALSE;
  1259. DWORD dwStatus;
  1260. DWORD dwAccessMask;
  1261. DWORD dwAccessDesired;
  1262. DWORD dwACLSize;
  1263. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  1264. PACL pACL = NULL;
  1265. PSID psidAdmin = NULL;
  1266. HANDLE hToken = NULL;
  1267. HANDLE hImpersonationToken = NULL;
  1268. PRIVILEGE_SET ps;
  1269. GENERIC_MAPPING GenericMapping;
  1270. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  1271. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  1272. const DWORD ACCESS_READ = 1;
  1273. const DWORD ACCESS_WRITE = 2;
  1274. __try
  1275. {
  1276. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  1277. {
  1278. if (GetLastError() != ERROR_NO_TOKEN)
  1279. __leave;
  1280. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  1281. __leave;
  1282. }
  1283. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  1284. __leave;
  1285. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  1286. SECURITY_BUILTIN_DOMAIN_RID,
  1287. DOMAIN_ALIAS_RID_ADMINS,
  1288. 0, 0, 0, 0, 0, 0, &psidAdmin))
  1289. __leave;
  1290. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  1291. if (psdAdmin == NULL)
  1292. __leave;
  1293. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  1294. __leave;
  1295. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  1296. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  1297. if (pACL == NULL)
  1298. __leave;
  1299. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  1300. __leave;
  1301. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  1302. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  1303. __leave;
  1304. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  1305. __leave;
  1306. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  1307. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  1308. if (!IsValidSecurityDescriptor(psdAdmin))
  1309. __leave;
  1310. dwAccessDesired = ACCESS_READ;
  1311. GenericMapping.GenericRead = ACCESS_READ;
  1312. GenericMapping.GenericWrite = ACCESS_WRITE;
  1313. GenericMapping.GenericExecute = 0;
  1314. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  1315. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  1316. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  1317. &fReturn))
  1318. {
  1319. fReturn = FALSE;
  1320. __leave;
  1321. }
  1322. }
  1323. __finally
  1324. {
  1325. // Clean up.
  1326. if (pACL) LocalFree(pACL);
  1327. if (psdAdmin) LocalFree(psdAdmin);
  1328. if (psidAdmin) FreeSid(psidAdmin);
  1329. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  1330. if (hToken) CloseHandle (hToken);
  1331. }
  1332. return fReturn;
  1333. }
  1334. #endif // __WINDOWS__
  1335. /****************************************************************************/
  1336. /* main() and friends */
  1337. /****************************************************************************/
  1338. static void printHelp(const char *cn,FILE *out)
  1339. {
  1340. fprintf(out,
  1341. "%s version %d.%d.%d" ZT_EOL_S,
  1342. PROGRAM_NAME,
  1343. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  1344. fprintf(out,
  1345. COPYRIGHT_NOTICE ZT_EOL_S
  1346. LICENSE_GRANT ZT_EOL_S);
  1347. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  1348. fprintf(out,"Available switches:" ZT_EOL_S);
  1349. fprintf(out," -h - Display this help" ZT_EOL_S);
  1350. fprintf(out," -v - Show version" ZT_EOL_S);
  1351. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  1352. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  1353. #ifdef __UNIX_LIKE__
  1354. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  1355. #endif // __UNIX_LIKE__
  1356. #ifdef __WINDOWS__
  1357. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  1358. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  1359. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  1360. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  1361. #endif // __WINDOWS__
  1362. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  1363. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  1364. }
  1365. class _OneServiceRunner
  1366. {
  1367. public:
  1368. _OneServiceRunner(const char *pn,const std::string &hd,unsigned int p) : progname(pn),returnValue(0),port(p),homeDir(hd) {}
  1369. void threadMain()
  1370. throw()
  1371. {
  1372. try {
  1373. for(;;) {
  1374. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1375. switch(zt1Service->run()) {
  1376. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1377. case OneService::ONE_NORMAL_TERMINATION:
  1378. break;
  1379. case OneService::ONE_UNRECOVERABLE_ERROR:
  1380. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,progname,zt1Service->fatalErrorMessage().c_str());
  1381. returnValue = 1;
  1382. break;
  1383. case OneService::ONE_IDENTITY_COLLISION: {
  1384. delete zt1Service;
  1385. zt1Service = (OneService *)0;
  1386. std::string oldid;
  1387. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1388. if (oldid.length()) {
  1389. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1390. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1391. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1392. }
  1393. } continue; // restart!
  1394. }
  1395. break; // terminate loop -- normally we don't keep restarting
  1396. }
  1397. delete zt1Service;
  1398. zt1Service = (OneService *)0;
  1399. } catch ( ... ) {
  1400. fprintf(stderr,"%s: unexpected exception starting main OneService instance" ZT_EOL_S,progname);
  1401. returnValue = 1;
  1402. }
  1403. }
  1404. const char *progname;
  1405. unsigned int returnValue;
  1406. unsigned int port;
  1407. const std::string &homeDir;
  1408. };
  1409. #ifdef __WINDOWS__
  1410. int __cdecl _tmain(int argc, _TCHAR* argv[])
  1411. #else
  1412. int main(int argc,char **argv)
  1413. #endif
  1414. {
  1415. #ifdef __UNIX_LIKE__
  1416. signal(SIGHUP,&_sighandlerHup);
  1417. signal(SIGPIPE,SIG_IGN);
  1418. signal(SIGIO,SIG_IGN);
  1419. signal(SIGUSR1,SIG_IGN);
  1420. signal(SIGUSR2,SIG_IGN);
  1421. signal(SIGALRM,SIG_IGN);
  1422. signal(SIGINT,&_sighandlerQuit);
  1423. signal(SIGTERM,&_sighandlerQuit);
  1424. signal(SIGQUIT,&_sighandlerQuit);
  1425. signal(SIGINT,&_sighandlerQuit);
  1426. /* Ensure that there are no inherited file descriptors open from a previous
  1427. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  1428. * of it do not return, and should not do anything otherwise bad. */
  1429. {
  1430. int mfd = STDIN_FILENO;
  1431. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  1432. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  1433. for(int f=mfd+1;f<1024;++f)
  1434. ::close(f);
  1435. }
  1436. bool runAsDaemon = false;
  1437. #endif // __UNIX_LIKE__
  1438. #ifdef __WINDOWS__
  1439. {
  1440. WSADATA wsaData;
  1441. WSAStartup(MAKEWORD(2,2),&wsaData);
  1442. }
  1443. #ifdef ZT_WIN_RUN_IN_CONSOLE
  1444. bool winRunFromCommandLine = true;
  1445. #else
  1446. bool winRunFromCommandLine = false;
  1447. #endif
  1448. #endif // __WINDOWS__
  1449. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  1450. return idtool(argc,argv);
  1451. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  1452. return cli(argc,argv);
  1453. std::string homeDir;
  1454. unsigned int port = ZT_DEFAULT_PORT;
  1455. bool skipRootCheck = false;
  1456. for(int i=1;i<argc;++i) {
  1457. if (argv[i][0] == '-') {
  1458. switch(argv[i][1]) {
  1459. case 'p': // port -- for both UDP and TCP, packets and control plane
  1460. port = Utils::strToUInt(argv[i] + 2);
  1461. if (port > 0xffff) {
  1462. printHelp(argv[0],stdout);
  1463. return 1;
  1464. }
  1465. break;
  1466. #ifdef __UNIX_LIKE__
  1467. case 'd': // Run in background as daemon
  1468. runAsDaemon = true;
  1469. break;
  1470. #endif // __UNIX_LIKE__
  1471. case 'U':
  1472. skipRootCheck = true;
  1473. break;
  1474. case 'v': // Display version
  1475. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  1476. return 0;
  1477. case 'i': // Invoke idtool personality
  1478. if (argv[i][2]) {
  1479. printHelp(argv[0],stdout);
  1480. return 0;
  1481. } else return idtool(argc-1,argv+1);
  1482. case 'q': // Invoke cli personality
  1483. if (argv[i][2]) {
  1484. printHelp(argv[0],stdout);
  1485. return 0;
  1486. } else return cli(argc,argv);
  1487. #ifdef __WINDOWS__
  1488. case 'C': // Run from command line instead of as Windows service
  1489. winRunFromCommandLine = true;
  1490. break;
  1491. case 'I': { // Install this binary as a Windows service
  1492. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1493. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1494. return 1;
  1495. }
  1496. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  1497. if (ret.length()) {
  1498. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1499. return 3;
  1500. }
  1501. return 0;
  1502. } break;
  1503. case 'R': { // Uninstall this binary as Windows service
  1504. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1505. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1506. return 1;
  1507. }
  1508. std::string ret(UninstallService(ZT_SERVICE_NAME));
  1509. if (ret.length()) {
  1510. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  1511. return 3;
  1512. }
  1513. return 0;
  1514. } break;
  1515. case 'D': {
  1516. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1517. if (err.length() > 0) {
  1518. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1519. return 3;
  1520. }
  1521. return 0;
  1522. } break;
  1523. #endif // __WINDOWS__
  1524. case 'h':
  1525. case '?':
  1526. default:
  1527. printHelp(argv[0],stdout);
  1528. return 0;
  1529. }
  1530. } else {
  1531. if (homeDir.length()) {
  1532. printHelp(argv[0],stdout);
  1533. return 0;
  1534. } else {
  1535. homeDir = argv[i];
  1536. }
  1537. }
  1538. }
  1539. if (!homeDir.length())
  1540. homeDir = OneService::platformDefaultHomePath();
  1541. if (!homeDir.length()) {
  1542. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1543. return 1;
  1544. } else {
  1545. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1546. std::string ptmp;
  1547. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1548. ptmp.push_back(ZT_PATH_SEPARATOR);
  1549. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1550. if (ptmp.length() > 0)
  1551. ptmp.push_back(ZT_PATH_SEPARATOR);
  1552. ptmp.append(*pi);
  1553. if ((*pi != ".")&&(*pi != "..")) {
  1554. if (!OSUtils::mkdir(ptmp))
  1555. throw std::runtime_error("home path does not exist, and could not create. Please verify local system permissions.");
  1556. }
  1557. }
  1558. }
  1559. // This can be removed once the new controller code has been around for many versions
  1560. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1561. 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());
  1562. return 1;
  1563. }
  1564. #ifdef __UNIX_LIKE__
  1565. #ifndef ZT_ONE_NO_ROOT_CHECK
  1566. if ((!skipRootCheck)&&(getuid() != 0)) {
  1567. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1568. return 1;
  1569. }
  1570. #endif // !ZT_ONE_NO_ROOT_CHECK
  1571. if (runAsDaemon) {
  1572. long p = (long)fork();
  1573. if (p < 0) {
  1574. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1575. return 1;
  1576. } else if (p > 0)
  1577. return 0; // forked
  1578. // else p == 0, so we are daemonized
  1579. }
  1580. #endif // __UNIX_LIKE__
  1581. #ifdef __WINDOWS__
  1582. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1583. // when tap instances are created.
  1584. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1585. if (winRunFromCommandLine) {
  1586. // Running in "interactive" mode (mostly for debugging)
  1587. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1588. if (!skipRootCheck) {
  1589. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1590. return 1;
  1591. }
  1592. } else {
  1593. _winPokeAHole();
  1594. }
  1595. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1596. // continues on to ordinary command line execution code below...
  1597. } else {
  1598. // Running from service manager
  1599. _winPokeAHole();
  1600. ZeroTierOneService zt1WindowsService;
  1601. if (CServiceBase::Run(zt1WindowsService) == TRUE) {
  1602. return 0;
  1603. } else {
  1604. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1605. return 1;
  1606. }
  1607. }
  1608. #endif // __WINDOWS__
  1609. #ifdef __UNIX_LIKE__
  1610. #ifdef ZT_HAVE_DROP_PRIVILEGES
  1611. if (!skipRootCheck)
  1612. dropPrivileges(argv[0],homeDir);
  1613. #endif
  1614. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1615. {
  1616. // Write .pid file to home folder
  1617. FILE *pf = fopen(pidPath.c_str(),"w");
  1618. if (pf) {
  1619. fprintf(pf,"%ld",(long)getpid());
  1620. fclose(pf);
  1621. }
  1622. }
  1623. #endif // __UNIX_LIKE__
  1624. _OneServiceRunner thr(argv[0],homeDir,port);
  1625. thr.threadMain();
  1626. //Thread::join(Thread::start(&thr));
  1627. #ifdef __UNIX_LIKE__
  1628. OSUtils::rm(pidPath.c_str());
  1629. #endif
  1630. return thr.returnValue;
  1631. }