one.cpp 36 KB

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