one.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdint.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include "node/Constants.hpp"
  25. #ifdef __WINDOWS__
  26. #include <WinSock2.h>
  27. #include <Windows.h>
  28. #include <tchar.h>
  29. #include <wchar.h>
  30. #include <lmcons.h>
  31. #include <newdev.h>
  32. #include <atlbase.h>
  33. #include "osdep/WindowsEthernetTap.hpp"
  34. #include "windows/ZeroTierOne/ServiceInstaller.h"
  35. #include "windows/ZeroTierOne/ServiceBase.h"
  36. #include "windows/ZeroTierOne/ZeroTierOneService.h"
  37. #else
  38. #include <unistd.h>
  39. #include <pwd.h>
  40. #include <fcntl.h>
  41. #include <sys/types.h>
  42. #include <sys/stat.h>
  43. #include <signal.h>
  44. #ifdef __linux__
  45. #include "osdep/LinuxDropPrivileges.hpp"
  46. #endif
  47. #endif
  48. #include <string>
  49. #include <stdexcept>
  50. #include <iostream>
  51. #include <sstream>
  52. #include "version.h"
  53. #include "include/ZeroTierOne.h"
  54. #include "node/Identity.hpp"
  55. #include "node/CertificateOfMembership.hpp"
  56. #include "node/Utils.hpp"
  57. #include "node/NetworkController.hpp"
  58. #include "node/Buffer.hpp"
  59. #include "node/World.hpp"
  60. #include "osdep/OSUtils.hpp"
  61. #include "osdep/Http.hpp"
  62. #include "service/OneService.hpp"
  63. #include "ext/json/json.hpp"
  64. #define ZT_PID_PATH "zerotier-one.pid"
  65. using namespace ZeroTier;
  66. static OneService *volatile zt1Service = (OneService *)0;
  67. #define PROGRAM_NAME "ZeroTier One"
  68. #define COPYRIGHT_NOTICE "Copyright © 2011–2016 ZeroTier, Inc."
  69. #define LICENSE_GRANT \
  70. "This is free software: you may copy, modify, and/or distribute this" ZT_EOL_S \
  71. "work under the terms of the GNU General Public License, version 3 or" ZT_EOL_S \
  72. "later as published by the Free Software Foundation." ZT_EOL_S \
  73. "No warranty expressed or implied." ZT_EOL_S
  74. /****************************************************************************/
  75. /* zerotier-cli personality */
  76. /****************************************************************************/
  77. // This is getting deprecated soon in favor of the stuff in cli/
  78. static void cliPrintHelp(const char *pn,FILE *out)
  79. {
  80. fprintf(out,
  81. "%s version %d.%d.%d" ZT_EOL_S,
  82. PROGRAM_NAME,
  83. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  84. fprintf(out,
  85. COPYRIGHT_NOTICE ZT_EOL_S
  86. LICENSE_GRANT ZT_EOL_S);
  87. fprintf(out,"Usage: %s [-switches] <command/path> [<args>]" ZT_EOL_S"" ZT_EOL_S,pn);
  88. fprintf(out,"Available switches:" ZT_EOL_S);
  89. fprintf(out," -h - Display this help" ZT_EOL_S);
  90. fprintf(out," -v - Show version" ZT_EOL_S);
  91. fprintf(out," -j - Display full raw JSON output" ZT_EOL_S);
  92. fprintf(out," -D<path> - ZeroTier home path for parameter auto-detect" ZT_EOL_S);
  93. fprintf(out," -p<port> - HTTP port (default: auto)" ZT_EOL_S);
  94. fprintf(out," -T<token> - Authentication token (default: auto)" ZT_EOL_S);
  95. fprintf(out,ZT_EOL_S"Available commands:" ZT_EOL_S);
  96. fprintf(out," info - Display status info" ZT_EOL_S);
  97. fprintf(out," listpeers - List all peers" ZT_EOL_S);
  98. fprintf(out," listnetworks - List all networks" ZT_EOL_S);
  99. fprintf(out," join <network> - Join a network" ZT_EOL_S);
  100. fprintf(out," leave <network> - Leave a network" ZT_EOL_S);
  101. fprintf(out," set <network> <setting> - Set a network setting" ZT_EOL_S);
  102. }
  103. static std::string cliFixJsonCRs(const std::string &s)
  104. {
  105. std::string r;
  106. for(std::string::const_iterator c(s.begin());c!=s.end();++c) {
  107. if (*c == '\n')
  108. r.append(ZT_EOL_S);
  109. else r.push_back(*c);
  110. }
  111. return r;
  112. }
  113. #ifdef __WINDOWS__
  114. static int cli(int argc, _TCHAR* argv[])
  115. #else
  116. static int cli(int argc,char **argv)
  117. #endif
  118. {
  119. unsigned int port = 0;
  120. std::string homeDir,command,arg1,arg2,authToken;
  121. std::string ip("127.0.0.1");
  122. bool json = false;
  123. for(int i=1;i<argc;++i) {
  124. if (argv[i][0] == '-') {
  125. switch(argv[i][1]) {
  126. case 'q': // ignore -q used to invoke this personality
  127. if (argv[i][2]) {
  128. cliPrintHelp(argv[0],stdout);
  129. return 1;
  130. }
  131. break;
  132. case 'j':
  133. if (argv[i][2]) {
  134. cliPrintHelp(argv[0],stdout);
  135. return 1;
  136. }
  137. json = true;
  138. break;
  139. case 'p':
  140. port = Utils::strToUInt(argv[i] + 2);
  141. if ((port > 0xffff)||(port == 0)) {
  142. cliPrintHelp(argv[0],stdout);
  143. return 1;
  144. }
  145. break;
  146. case 'D':
  147. if (argv[i][2]) {
  148. homeDir = argv[i] + 2;
  149. } else {
  150. cliPrintHelp(argv[0],stdout);
  151. return 1;
  152. }
  153. break;
  154. case 'H':
  155. if (argv[i][2]) {
  156. ip = argv[i] + 2;
  157. } else {
  158. cliPrintHelp(argv[0],stdout);
  159. return 1;
  160. }
  161. break;
  162. case 'T':
  163. if (argv[i][2]) {
  164. authToken = argv[i] + 2;
  165. } else {
  166. cliPrintHelp(argv[0],stdout);
  167. return 1;
  168. }
  169. break;
  170. case 'v':
  171. if (argv[i][2]) {
  172. cliPrintHelp(argv[0],stdout);
  173. return 1;
  174. }
  175. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  176. return 0;
  177. case 'h':
  178. case '?':
  179. default:
  180. cliPrintHelp(argv[0],stdout);
  181. return 0;
  182. }
  183. } else {
  184. if (arg1.length())
  185. arg2 = argv[i];
  186. else if (command.length())
  187. arg1 = argv[i];
  188. else command = argv[i];
  189. }
  190. }
  191. if (!homeDir.length())
  192. homeDir = OneService::platformDefaultHomePath();
  193. if ((!port)||(!authToken.length())) {
  194. if (!homeDir.length()) {
  195. fprintf(stderr,"%s: missing port or authentication token and no home directory specified to auto-detect" ZT_EOL_S,argv[0]);
  196. return 2;
  197. }
  198. if (!port) {
  199. std::string portStr;
  200. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "zerotier-one.port").c_str(),portStr);
  201. port = Utils::strToUInt(portStr.c_str());
  202. if ((port == 0)||(port > 0xffff)) {
  203. fprintf(stderr,"%s: missing port and zerotier-one.port not found in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  204. return 2;
  205. }
  206. }
  207. if (!authToken.length()) {
  208. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),authToken);
  209. #ifdef __UNIX_LIKE__
  210. if (!authToken.length()) {
  211. const char *hd = getenv("HOME");
  212. if (hd) {
  213. char p[4096];
  214. #ifdef __APPLE__
  215. Utils::snprintf(p,sizeof(p),"%s/Library/Application Support/ZeroTier/One/authtoken.secret",hd);
  216. #else
  217. Utils::snprintf(p,sizeof(p),"%s/.zeroTierOneAuthToken",hd);
  218. #endif
  219. OSUtils::readFile(p,authToken);
  220. }
  221. }
  222. #endif
  223. if (!authToken.length()) {
  224. fprintf(stderr,"%s: missing authentication token and authtoken.secret not found (or readable) in %s" ZT_EOL_S,argv[0],homeDir.c_str());
  225. return 2;
  226. }
  227. }
  228. }
  229. InetAddress addr;
  230. {
  231. char addrtmp[256];
  232. Utils::snprintf(addrtmp,sizeof(addrtmp),"%s/%u",ip.c_str(),port);
  233. addr = InetAddress(addrtmp);
  234. }
  235. std::map<std::string,std::string> requestHeaders;
  236. std::map<std::string,std::string> responseHeaders;
  237. std::string responseBody;
  238. requestHeaders["X-ZT1-Auth"] = authToken;
  239. if ((command.length() > 0)&&(command[0] == '/')) {
  240. unsigned int scode = Http::GET(
  241. 1024 * 1024 * 16,
  242. 60000,
  243. (const struct sockaddr *)&addr,
  244. command.c_str(),
  245. requestHeaders,
  246. responseHeaders,
  247. responseBody);
  248. if (scode == 200) {
  249. printf("%s",cliFixJsonCRs(responseBody).c_str());
  250. return 0;
  251. } else {
  252. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  253. return 1;
  254. }
  255. } else if ((command == "info")||(command == "status")) {
  256. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/status",requestHeaders,responseHeaders,responseBody);
  257. nlohmann::json j;
  258. try {
  259. j = OSUtils::jsonParse(responseBody);
  260. } catch (std::exception &exc) {
  261. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  262. return 1;
  263. } catch ( ... ) {
  264. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  265. return 1;
  266. }
  267. if (scode == 200) {
  268. if (json) {
  269. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  270. } else {
  271. if (j.is_object()) {
  272. printf("200 info %s %s %s" ZT_EOL_S,
  273. OSUtils::jsonString(j["address"],"-").c_str(),
  274. OSUtils::jsonString(j["version"],"-").c_str(),
  275. ((j["tcpFallbackActive"]) ? "TUNNELED" : ((j["online"]) ? "ONLINE" : "OFFLINE")));
  276. }
  277. }
  278. return 0;
  279. } else {
  280. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  281. return 1;
  282. }
  283. } else if (command == "listpeers") {
  284. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/peer",requestHeaders,responseHeaders,responseBody);
  285. nlohmann::json j;
  286. try {
  287. j = OSUtils::jsonParse(responseBody);
  288. } catch (std::exception &exc) {
  289. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  290. return 1;
  291. } catch ( ... ) {
  292. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  293. return 1;
  294. }
  295. if (scode == 200) {
  296. if (json) {
  297. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  298. } else {
  299. printf("200 listpeers <ztaddr> <path> <latency> <version> <role>" ZT_EOL_S);
  300. if (j.is_array()) {
  301. for(unsigned long k=0;k<j.size();++k) {
  302. nlohmann::json &p = j[k];
  303. std::string bestPath;
  304. nlohmann::json &paths = p["paths"];
  305. if (paths.is_array()) {
  306. for(unsigned long i=0;i<paths.size();++i) {
  307. nlohmann::json &path = paths[i];
  308. if (path["preferred"]) {
  309. char tmp[256];
  310. std::string addr = path["address"];
  311. const uint64_t now = OSUtils::now();
  312. Utils::snprintf(tmp,sizeof(tmp),"%s;%llu;%llu",addr.c_str(),now - (uint64_t)path["lastSend"],now - (uint64_t)path["lastReceive"]);
  313. bestPath = tmp;
  314. break;
  315. }
  316. }
  317. }
  318. if (bestPath.length() == 0) bestPath = "-";
  319. char ver[128];
  320. int64_t vmaj = p["versionMajor"];
  321. int64_t vmin = p["versionMinor"];
  322. int64_t vrev = p["versionRev"];
  323. if (vmaj >= 0) {
  324. Utils::snprintf(ver,sizeof(ver),"%lld.%lld.%lld",vmaj,vmin,vrev);
  325. } else {
  326. ver[0] = '-';
  327. ver[1] = (char)0;
  328. }
  329. printf("200 listpeers %s %s %d %s %s" ZT_EOL_S,
  330. OSUtils::jsonString(p["address"],"-").c_str(),
  331. bestPath.c_str(),
  332. (int)OSUtils::jsonInt(p["latency"],0),
  333. ver,
  334. OSUtils::jsonString(p["role"],"-").c_str());
  335. }
  336. }
  337. }
  338. return 0;
  339. } else {
  340. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  341. return 1;
  342. }
  343. } else if (command == "listnetworks") {
  344. const unsigned int scode = Http::GET(1024 * 1024 * 16,60000,(const struct sockaddr *)&addr,"/network",requestHeaders,responseHeaders,responseBody);
  345. nlohmann::json j;
  346. try {
  347. j = OSUtils::jsonParse(responseBody);
  348. } catch (std::exception &exc) {
  349. printf("%u %s invalid JSON response (%s)" ZT_EOL_S,scode,command.c_str(),exc.what());
  350. return 1;
  351. } catch ( ... ) {
  352. printf("%u %s invalid JSON response (unknown exception)" ZT_EOL_S,scode,command.c_str());
  353. return 1;
  354. }
  355. if (scode == 200) {
  356. if (json) {
  357. printf("%s" ZT_EOL_S,OSUtils::jsonDump(j).c_str());
  358. } else {
  359. printf("200 listnetworks <nwid> <name> <mac> <status> <type> <dev> <ZT assigned ips>" ZT_EOL_S);
  360. if (j.is_array()) {
  361. for(unsigned long i=0;i<j.size();++i) {
  362. nlohmann::json &n = j[i];
  363. if (n.is_object()) {
  364. std::string aa;
  365. nlohmann::json &assignedAddresses = n["assignedAddresses"];
  366. if (assignedAddresses.is_array()) {
  367. for(unsigned long j=0;j<assignedAddresses.size();++j) {
  368. nlohmann::json &addr = assignedAddresses[j];
  369. if (addr.is_string()) {
  370. if (aa.length() > 0) aa.push_back(',');
  371. aa.append(addr.get<std::string>());
  372. }
  373. }
  374. }
  375. if (aa.length() == 0) aa = "-";
  376. printf("200 listnetworks %s %s %s %s %s %s %s" ZT_EOL_S,
  377. OSUtils::jsonString(n["nwid"],"-").c_str(),
  378. OSUtils::jsonString(n["name"],"-").c_str(),
  379. OSUtils::jsonString(n["mac"],"-").c_str(),
  380. OSUtils::jsonString(n["status"],"-").c_str(),
  381. OSUtils::jsonString(n["type"],"-").c_str(),
  382. OSUtils::jsonString(n["portDeviceName"],"-").c_str(),
  383. aa.c_str());
  384. }
  385. }
  386. }
  387. }
  388. return 0;
  389. } else {
  390. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  391. return 1;
  392. }
  393. } else if (command == "join") {
  394. if (arg1.length() != 16) {
  395. cliPrintHelp(argv[0],stderr);
  396. return 2;
  397. }
  398. requestHeaders["Content-Type"] = "application/json";
  399. requestHeaders["Content-Length"] = "2";
  400. unsigned int scode = Http::POST(
  401. 1024 * 1024 * 16,
  402. 60000,
  403. (const struct sockaddr *)&addr,
  404. (std::string("/network/") + arg1).c_str(),
  405. requestHeaders,
  406. "{}",
  407. 2,
  408. responseHeaders,
  409. responseBody);
  410. if (scode == 200) {
  411. if (json) {
  412. printf("%s",cliFixJsonCRs(responseBody).c_str());
  413. } else {
  414. printf("200 join OK" ZT_EOL_S);
  415. }
  416. return 0;
  417. } else {
  418. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  419. return 1;
  420. }
  421. } else if (command == "leave") {
  422. if (arg1.length() != 16) {
  423. cliPrintHelp(argv[0],stderr);
  424. return 2;
  425. }
  426. unsigned int scode = Http::DEL(
  427. 1024 * 1024 * 16,
  428. 60000,
  429. (const struct sockaddr *)&addr,
  430. (std::string("/network/") + arg1).c_str(),
  431. requestHeaders,
  432. responseHeaders,
  433. responseBody);
  434. if (scode == 200) {
  435. if (json) {
  436. printf("%s",cliFixJsonCRs(responseBody).c_str());
  437. } else {
  438. printf("200 leave OK" ZT_EOL_S);
  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 == "set") {
  446. if (arg1.length() != 16) {
  447. cliPrintHelp(argv[0],stderr);
  448. return 2;
  449. }
  450. std::size_t eqidx = arg2.find('=');
  451. if (eqidx != std::string::npos) {
  452. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")) {
  453. char jsons[1024];
  454. Utils::snprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  455. arg2.substr(0,eqidx).c_str(),
  456. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  457. char cl[128];
  458. Utils::snprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  459. requestHeaders["Content-Type"] = "application/json";
  460. requestHeaders["Content-Length"] = cl;
  461. unsigned int scode = Http::POST(
  462. 1024 * 1024 * 16,
  463. 60000,
  464. (const struct sockaddr *)&addr,
  465. (std::string("/network/") + arg1).c_str(),
  466. requestHeaders,
  467. jsons,
  468. (unsigned long)strlen(jsons),
  469. responseHeaders,
  470. responseBody);
  471. if (scode == 200) {
  472. printf("%s",cliFixJsonCRs(responseBody).c_str());
  473. return 0;
  474. } else {
  475. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  476. return 1;
  477. }
  478. }
  479. } else {
  480. cliPrintHelp(argv[0],stderr);
  481. return 2;
  482. }
  483. } else {
  484. cliPrintHelp(argv[0],stderr);
  485. return 0;
  486. }
  487. return 0;
  488. }
  489. /****************************************************************************/
  490. /* zerotier-idtool personality */
  491. /****************************************************************************/
  492. static void idtoolPrintHelp(FILE *out,const char *pn)
  493. {
  494. fprintf(out,
  495. "%s version %d.%d.%d" ZT_EOL_S,
  496. PROGRAM_NAME,
  497. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  498. fprintf(out,
  499. COPYRIGHT_NOTICE ZT_EOL_S
  500. LICENSE_GRANT ZT_EOL_S);
  501. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  502. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  503. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  504. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  505. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  506. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  507. fprintf(out," initmoon <identity.public of first seed>" ZT_EOL_S);
  508. fprintf(out," genmoon <moon json>" ZT_EOL_S);
  509. }
  510. static Identity getIdFromArg(char *arg)
  511. {
  512. Identity id;
  513. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  514. if (id.fromString(arg))
  515. return id;
  516. } else { // identity is to be read from a file
  517. std::string idser;
  518. if (OSUtils::readFile(arg,idser)) {
  519. if (id.fromString(idser))
  520. return id;
  521. }
  522. }
  523. return Identity();
  524. }
  525. #ifdef __WINDOWS__
  526. static int idtool(int argc, _TCHAR* argv[])
  527. #else
  528. static int idtool(int argc,char **argv)
  529. #endif
  530. {
  531. if (argc < 2) {
  532. idtoolPrintHelp(stdout,argv[0]);
  533. return 1;
  534. }
  535. if (!strcmp(argv[1],"generate")) {
  536. uint64_t vanity = 0;
  537. int vanityBits = 0;
  538. if (argc >= 5) {
  539. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  540. vanityBits = 4 * (int)strlen(argv[4]);
  541. if (vanityBits > 40)
  542. vanityBits = 40;
  543. }
  544. Identity id;
  545. for(;;) {
  546. id.generate();
  547. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  548. if (vanityBits > 0) {
  549. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  550. }
  551. break;
  552. } else {
  553. 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)));
  554. }
  555. }
  556. std::string idser = id.toString(true);
  557. if (argc >= 3) {
  558. if (!OSUtils::writeFile(argv[2],idser)) {
  559. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  560. return 1;
  561. } else printf("%s written" ZT_EOL_S,argv[2]);
  562. if (argc >= 4) {
  563. idser = id.toString(false);
  564. if (!OSUtils::writeFile(argv[3],idser)) {
  565. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  566. return 1;
  567. } else printf("%s written" ZT_EOL_S,argv[3]);
  568. }
  569. } else printf("%s",idser.c_str());
  570. } else if (!strcmp(argv[1],"validate")) {
  571. if (argc < 3) {
  572. idtoolPrintHelp(stdout,argv[0]);
  573. return 1;
  574. }
  575. Identity id = getIdFromArg(argv[2]);
  576. if (!id) {
  577. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  578. return 1;
  579. }
  580. if (!id.locallyValidate()) {
  581. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  582. return 1;
  583. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  584. } else if (!strcmp(argv[1],"getpublic")) {
  585. if (argc < 3) {
  586. idtoolPrintHelp(stdout,argv[0]);
  587. return 1;
  588. }
  589. Identity id = getIdFromArg(argv[2]);
  590. if (!id) {
  591. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  592. return 1;
  593. }
  594. printf("%s",id.toString(false).c_str());
  595. } else if (!strcmp(argv[1],"sign")) {
  596. if (argc < 4) {
  597. idtoolPrintHelp(stdout,argv[0]);
  598. return 1;
  599. }
  600. Identity id = getIdFromArg(argv[2]);
  601. if (!id) {
  602. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  603. return 1;
  604. }
  605. if (!id.hasPrivate()) {
  606. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  607. return 1;
  608. }
  609. std::string inf;
  610. if (!OSUtils::readFile(argv[3],inf)) {
  611. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  612. return 1;
  613. }
  614. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  615. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  616. } else if (!strcmp(argv[1],"verify")) {
  617. if (argc < 4) {
  618. idtoolPrintHelp(stdout,argv[0]);
  619. return 1;
  620. }
  621. Identity id = getIdFromArg(argv[2]);
  622. if (!id) {
  623. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  624. return 1;
  625. }
  626. std::string inf;
  627. if (!OSUtils::readFile(argv[3],inf)) {
  628. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  629. return 1;
  630. }
  631. std::string signature(Utils::unhex(argv[4]));
  632. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  633. printf("%s signature valid" ZT_EOL_S,argv[3]);
  634. } else {
  635. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  636. return 1;
  637. }
  638. } else if (!strcmp(argv[1],"initmoon")) {
  639. if (argc < 3) {
  640. idtoolPrintHelp(stdout,argv[0]);
  641. } else {
  642. const Identity id = getIdFromArg(argv[2]);
  643. if (!id) {
  644. fprintf(stderr,"%s is not a valid identity" ZT_EOL_S,argv[2]);
  645. return 1;
  646. }
  647. C25519::Pair kp(C25519::generate());
  648. nlohmann::json mj;
  649. mj["objtype"] = "world";
  650. mj["worldType"] = "moon";
  651. mj["updatesMustBeSignedBy"] = mj["signingKey"] = Utils::hex(kp.pub.data,(unsigned int)kp.pub.size());
  652. mj["updatesMustBeSignedBy_SECRET"] = Utils::hex(kp.priv.data,(unsigned int)kp.priv.size());
  653. mj["id"] = id.address().toInt();
  654. nlohmann::json seedj;
  655. seedj["identity"] = id.toString(false);
  656. seedj["stableEndpoints"] = nlohmann::json::array();
  657. (mj["roots"] = nlohmann::json::array()).push_back(seedj);
  658. std::string mjd(OSUtils::jsonDump(mj));
  659. printf("%s" ZT_EOL_S,mjd.c_str());
  660. }
  661. } else if (!strcmp(argv[1],"genmoon")) {
  662. if (argc < 3) {
  663. idtoolPrintHelp(stdout,argv[0]);
  664. } else {
  665. std::string buf;
  666. if (!OSUtils::readFile(argv[2],buf)) {
  667. fprintf(stderr,"cannot read %s" ZT_EOL_S,argv[2]);
  668. return 1;
  669. }
  670. nlohmann::json mj(OSUtils::jsonParse(buf));
  671. const uint64_t id = OSUtils::jsonInt(mj["id"],0);
  672. if (!id) {
  673. fprintf(stderr,"ID in %s is invalid" ZT_EOL_S,argv[2]);
  674. return 1;
  675. }
  676. World::Type t;
  677. if (mj["worldType"] == "moon") {
  678. t = World::TYPE_MOON;
  679. } else if (mj["worldType"] == "planet") {
  680. t = World::TYPE_PLANET;
  681. } else {
  682. fprintf(stderr,"invalid worldType" ZT_EOL_S);
  683. return 1;
  684. }
  685. C25519::Pair signingKey;
  686. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy"],""),signingKey.pub.data,(unsigned int)signingKey.pub.size());
  687. Utils::unhex(OSUtils::jsonString(mj["updatesMustBeSignedBy_SECRET"],""),signingKey.priv.data,(unsigned int)signingKey.priv.size());
  688. std::vector<World::Root> roots;
  689. nlohmann::json &rootsj = mj["roots"];
  690. if (rootsj.is_array()) {
  691. for(unsigned long i=0;i<(unsigned long)rootsj.size();++i) {
  692. nlohmann::json &r = rootsj[i];
  693. if (r.is_object()) {
  694. roots.push_back(World::Root());
  695. roots.back().identity = Identity(OSUtils::jsonString(r["identity"],""));
  696. nlohmann::json &stableEndpointsj = r["stableEndpoints"];
  697. if (stableEndpointsj.is_array()) {
  698. for(unsigned long k=0;k<(unsigned long)stableEndpointsj.size();++k)
  699. roots.back().stableEndpoints.push_back(InetAddress(OSUtils::jsonString(stableEndpointsj[k],"")));
  700. std::sort(roots.back().stableEndpoints.begin(),roots.back().stableEndpoints.end());
  701. }
  702. }
  703. }
  704. }
  705. std::sort(roots.begin(),roots.end());
  706. const uint64_t now = OSUtils::now();
  707. World w(World::make(t,id,now,signingKey.pub,roots,signingKey));
  708. Buffer<ZT_WORLD_MAX_SERIALIZED_LENGTH> wbuf;
  709. w.serialize(wbuf);
  710. char fn[128];
  711. Utils::snprintf(fn,sizeof(fn),"%.16llx_%.16llx.moon",w.id(),now);
  712. OSUtils::writeFile(fn,wbuf.data(),wbuf.size());
  713. printf("wrote %s (signed world with timestamp %llu)" ZT_EOL_S,fn,(unsigned long long)now);
  714. }
  715. } else {
  716. idtoolPrintHelp(stdout,argv[0]);
  717. return 1;
  718. }
  719. return 0;
  720. }
  721. /****************************************************************************/
  722. /* Unix helper functions and signal handlers */
  723. /****************************************************************************/
  724. #ifdef __UNIX_LIKE__
  725. static void _sighandlerHup(int sig)
  726. {
  727. }
  728. static void _sighandlerQuit(int sig)
  729. {
  730. OneService *s = zt1Service;
  731. if (s)
  732. s->terminate();
  733. else exit(0);
  734. }
  735. #endif
  736. /****************************************************************************/
  737. /* Windows helper functions and signal handlers */
  738. /****************************************************************************/
  739. #ifdef __WINDOWS__
  740. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  741. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  742. {
  743. switch(dwCtrlType) {
  744. case CTRL_C_EVENT:
  745. case CTRL_BREAK_EVENT:
  746. case CTRL_CLOSE_EVENT:
  747. case CTRL_SHUTDOWN_EVENT:
  748. OneService *s = zt1Service;
  749. if (s)
  750. s->terminate();
  751. return TRUE;
  752. }
  753. return FALSE;
  754. }
  755. static void _winPokeAHole()
  756. {
  757. char myPath[MAX_PATH];
  758. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  759. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  760. STARTUPINFOA startupInfo;
  761. PROCESS_INFORMATION processInfo;
  762. startupInfo.cb = sizeof(startupInfo);
  763. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  764. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  765. 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)) {
  766. WaitForSingleObject(processInfo.hProcess,INFINITE);
  767. CloseHandle(processInfo.hProcess);
  768. CloseHandle(processInfo.hThread);
  769. }
  770. startupInfo.cb = sizeof(startupInfo);
  771. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  772. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  773. 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)) {
  774. WaitForSingleObject(processInfo.hProcess,INFINITE);
  775. CloseHandle(processInfo.hProcess);
  776. CloseHandle(processInfo.hThread);
  777. }
  778. startupInfo.cb = sizeof(startupInfo);
  779. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  780. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  781. 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)) {
  782. WaitForSingleObject(processInfo.hProcess,INFINITE);
  783. CloseHandle(processInfo.hProcess);
  784. CloseHandle(processInfo.hThread);
  785. }
  786. }
  787. }
  788. // Returns true if this is running as the local administrator
  789. static BOOL IsCurrentUserLocalAdministrator(void)
  790. {
  791. BOOL fReturn = FALSE;
  792. DWORD dwStatus;
  793. DWORD dwAccessMask;
  794. DWORD dwAccessDesired;
  795. DWORD dwACLSize;
  796. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  797. PACL pACL = NULL;
  798. PSID psidAdmin = NULL;
  799. HANDLE hToken = NULL;
  800. HANDLE hImpersonationToken = NULL;
  801. PRIVILEGE_SET ps;
  802. GENERIC_MAPPING GenericMapping;
  803. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  804. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  805. const DWORD ACCESS_READ = 1;
  806. const DWORD ACCESS_WRITE = 2;
  807. __try
  808. {
  809. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  810. {
  811. if (GetLastError() != ERROR_NO_TOKEN)
  812. __leave;
  813. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  814. __leave;
  815. }
  816. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  817. __leave;
  818. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  819. SECURITY_BUILTIN_DOMAIN_RID,
  820. DOMAIN_ALIAS_RID_ADMINS,
  821. 0, 0, 0, 0, 0, 0, &psidAdmin))
  822. __leave;
  823. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  824. if (psdAdmin == NULL)
  825. __leave;
  826. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  827. __leave;
  828. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  829. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  830. if (pACL == NULL)
  831. __leave;
  832. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  833. __leave;
  834. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  835. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  836. __leave;
  837. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  838. __leave;
  839. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  840. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  841. if (!IsValidSecurityDescriptor(psdAdmin))
  842. __leave;
  843. dwAccessDesired = ACCESS_READ;
  844. GenericMapping.GenericRead = ACCESS_READ;
  845. GenericMapping.GenericWrite = ACCESS_WRITE;
  846. GenericMapping.GenericExecute = 0;
  847. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  848. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  849. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  850. &fReturn))
  851. {
  852. fReturn = FALSE;
  853. __leave;
  854. }
  855. }
  856. __finally
  857. {
  858. // Clean up.
  859. if (pACL) LocalFree(pACL);
  860. if (psdAdmin) LocalFree(psdAdmin);
  861. if (psidAdmin) FreeSid(psidAdmin);
  862. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  863. if (hToken) CloseHandle (hToken);
  864. }
  865. return fReturn;
  866. }
  867. #endif // __WINDOWS__
  868. /****************************************************************************/
  869. /* main() and friends */
  870. /****************************************************************************/
  871. static void printHelp(const char *cn,FILE *out)
  872. {
  873. fprintf(out,
  874. "%s version %d.%d.%d" ZT_EOL_S,
  875. PROGRAM_NAME,
  876. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  877. fprintf(out,
  878. COPYRIGHT_NOTICE ZT_EOL_S
  879. LICENSE_GRANT ZT_EOL_S);
  880. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  881. fprintf(out,"Available switches:" ZT_EOL_S);
  882. fprintf(out," -h - Display this help" ZT_EOL_S);
  883. fprintf(out," -v - Show version" ZT_EOL_S);
  884. fprintf(out," -U - Skip privilege check and do not attempt to drop privileges" ZT_EOL_S);
  885. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  886. #ifdef __UNIX_LIKE__
  887. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  888. #endif // __UNIX_LIKE__
  889. #ifdef __WINDOWS__
  890. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  891. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  892. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  893. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  894. #endif // __WINDOWS__
  895. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  896. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  897. }
  898. #ifdef __WINDOWS__
  899. int _tmain(int argc, _TCHAR* argv[])
  900. #else
  901. int main(int argc,char **argv)
  902. #endif
  903. {
  904. #ifdef __UNIX_LIKE__
  905. signal(SIGHUP,&_sighandlerHup);
  906. signal(SIGPIPE,SIG_IGN);
  907. signal(SIGUSR1,SIG_IGN);
  908. signal(SIGUSR2,SIG_IGN);
  909. signal(SIGALRM,SIG_IGN);
  910. signal(SIGINT,&_sighandlerQuit);
  911. signal(SIGTERM,&_sighandlerQuit);
  912. signal(SIGQUIT,&_sighandlerQuit);
  913. /* Ensure that there are no inherited file descriptors open from a previous
  914. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  915. * of it do not return, and should not do anything otherwise bad. */
  916. {
  917. int mfd = STDIN_FILENO;
  918. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  919. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  920. for(int f=mfd+1;f<1024;++f)
  921. ::close(f);
  922. }
  923. bool runAsDaemon = false;
  924. #endif // __UNIX_LIKE__
  925. #ifdef __WINDOWS__
  926. {
  927. WSADATA wsaData;
  928. WSAStartup(MAKEWORD(2,2),&wsaData);
  929. }
  930. #ifdef ZT_WIN_RUN_IN_CONSOLE
  931. bool winRunFromCommandLine = true;
  932. #else
  933. bool winRunFromCommandLine = false;
  934. #endif
  935. #endif // __WINDOWS__
  936. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  937. return idtool(argc,argv);
  938. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  939. return cli(argc,argv);
  940. std::string homeDir;
  941. unsigned int port = ZT_DEFAULT_PORT;
  942. bool skipRootCheck = false;
  943. for(int i=1;i<argc;++i) {
  944. if (argv[i][0] == '-') {
  945. switch(argv[i][1]) {
  946. case 'p': // port -- for both UDP and TCP, packets and control plane
  947. port = Utils::strToUInt(argv[i] + 2);
  948. if (port > 0xffff) {
  949. printHelp(argv[0],stdout);
  950. return 1;
  951. }
  952. break;
  953. #ifdef __UNIX_LIKE__
  954. case 'd': // Run in background as daemon
  955. runAsDaemon = true;
  956. break;
  957. #endif // __UNIX_LIKE__
  958. case 'U':
  959. skipRootCheck = true;
  960. break;
  961. case 'v': // Display version
  962. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  963. return 0;
  964. case 'i': // Invoke idtool personality
  965. if (argv[i][2]) {
  966. printHelp(argv[0],stdout);
  967. return 0;
  968. } else return idtool(argc,argv);
  969. case 'q': // Invoke cli personality
  970. if (argv[i][2]) {
  971. printHelp(argv[0],stdout);
  972. return 0;
  973. } else return cli(argc,argv);
  974. #ifdef __WINDOWS__
  975. case 'C': // Run from command line instead of as Windows service
  976. winRunFromCommandLine = true;
  977. break;
  978. case 'I': { // Install this binary as a Windows service
  979. if (IsCurrentUserLocalAdministrator() != TRUE) {
  980. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  981. return 1;
  982. }
  983. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  984. if (ret.length()) {
  985. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  986. return 3;
  987. }
  988. return 0;
  989. } break;
  990. case 'R': { // Uninstall this binary as Windows service
  991. if (IsCurrentUserLocalAdministrator() != TRUE) {
  992. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  993. return 1;
  994. }
  995. std::string ret(UninstallService(ZT_SERVICE_NAME));
  996. if (ret.length()) {
  997. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  998. return 3;
  999. }
  1000. return 0;
  1001. } break;
  1002. case 'D': {
  1003. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  1004. if (err.length() > 0) {
  1005. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  1006. return 3;
  1007. }
  1008. return 0;
  1009. } break;
  1010. #endif // __WINDOWS__
  1011. case 'h':
  1012. case '?':
  1013. default:
  1014. printHelp(argv[0],stdout);
  1015. return 0;
  1016. }
  1017. } else {
  1018. if (homeDir.length()) {
  1019. printHelp(argv[0],stdout);
  1020. return 0;
  1021. } else {
  1022. homeDir = argv[i];
  1023. }
  1024. }
  1025. }
  1026. if (!homeDir.length())
  1027. homeDir = OneService::platformDefaultHomePath();
  1028. if (!homeDir.length()) {
  1029. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  1030. return 1;
  1031. } else {
  1032. std::vector<std::string> hpsp(OSUtils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  1033. std::string ptmp;
  1034. if (homeDir[0] == ZT_PATH_SEPARATOR)
  1035. ptmp.push_back(ZT_PATH_SEPARATOR);
  1036. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  1037. if (ptmp.length() > 0)
  1038. ptmp.push_back(ZT_PATH_SEPARATOR);
  1039. ptmp.append(*pi);
  1040. if ((*pi != ".")&&(*pi != "..")) {
  1041. if (!OSUtils::mkdir(ptmp))
  1042. throw std::runtime_error("home path does not exist, and could not create");
  1043. }
  1044. }
  1045. }
  1046. // This can be removed once the new controller code has been around for many versions
  1047. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  1048. 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());
  1049. return 1;
  1050. }
  1051. #ifdef __UNIX_LIKE__
  1052. #ifndef ZT_ONE_NO_ROOT_CHECK
  1053. if ((!skipRootCheck)&&(getuid() != 0)) {
  1054. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  1055. return 1;
  1056. }
  1057. #endif // !ZT_ONE_NO_ROOT_CHECK
  1058. if (runAsDaemon) {
  1059. long p = (long)fork();
  1060. if (p < 0) {
  1061. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  1062. return 1;
  1063. } else if (p > 0)
  1064. return 0; // forked
  1065. // else p == 0, so we are daemonized
  1066. }
  1067. #endif // __UNIX_LIKE__
  1068. #ifdef __WINDOWS__
  1069. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1070. // when tap instances are created.
  1071. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1072. if (winRunFromCommandLine) {
  1073. // Running in "interactive" mode (mostly for debugging)
  1074. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1075. if (!skipRootCheck) {
  1076. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1077. return 1;
  1078. }
  1079. } else {
  1080. _winPokeAHole();
  1081. }
  1082. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1083. // continues on to ordinary command line execution code below...
  1084. } else {
  1085. // Running from service manager
  1086. _winPokeAHole();
  1087. ZeroTierOneService zt1Service;
  1088. if (CServiceBase::Run(zt1Service) == TRUE) {
  1089. return 0;
  1090. } else {
  1091. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1092. return 1;
  1093. }
  1094. }
  1095. #endif // __WINDOWS__
  1096. #ifdef __UNIX_LIKE__
  1097. #ifndef ZT_ONE_RUN_AS_ROOT
  1098. #ifdef __linux__
  1099. if (!skipRootCheck)
  1100. dropPrivileges(homeDir);
  1101. #endif
  1102. #endif
  1103. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1104. {
  1105. // Write .pid file to home folder
  1106. FILE *pf = fopen(pidPath.c_str(),"w");
  1107. if (pf) {
  1108. fprintf(pf,"%ld",(long)getpid());
  1109. fclose(pf);
  1110. }
  1111. }
  1112. #endif // __UNIX_LIKE__
  1113. unsigned int returnValue = 0;
  1114. for(;;) {
  1115. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1116. switch(zt1Service->run()) {
  1117. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1118. case OneService::ONE_NORMAL_TERMINATION:
  1119. break;
  1120. case OneService::ONE_UNRECOVERABLE_ERROR:
  1121. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  1122. returnValue = 1;
  1123. break;
  1124. case OneService::ONE_IDENTITY_COLLISION: {
  1125. delete zt1Service;
  1126. zt1Service = (OneService *)0;
  1127. std::string oldid;
  1128. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1129. if (oldid.length()) {
  1130. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1131. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1132. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1133. }
  1134. } continue; // restart!
  1135. }
  1136. break; // terminate loop -- normally we don't keep restarting
  1137. }
  1138. delete zt1Service;
  1139. zt1Service = (OneService *)0;
  1140. return returnValue;
  1141. }