one.cpp 36 KB

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