one.cpp 40 KB

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