one.cpp 54 KB

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