one.cpp 56 KB

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