one.cpp 55 KB

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