one.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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. std::string name = n["name"];
  368. if (name.length() == 0) name = "-";
  369. out << "200 listnetworks " << n["nwid"].get<std::string>() << " " << name << " " << n["mac"].get<std::string>() << " " << n["status"].get<std::string>() << " " << n["type"].get<std::string>() << " " << n["portDeviceName"].get<std::string>() << " " << aa << ZT_EOL_S;
  370. }
  371. }
  372. }
  373. }
  374. printf("%s",out.str().c_str());
  375. return 0;
  376. } else {
  377. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  378. return 1;
  379. }
  380. } else if (command == "join") {
  381. if (arg1.length() != 16) {
  382. cliPrintHelp(argv[0],stderr);
  383. return 2;
  384. }
  385. requestHeaders["Content-Type"] = "application/json";
  386. requestHeaders["Content-Length"] = "2";
  387. unsigned int scode = Http::POST(
  388. 1024 * 1024 * 16,
  389. 60000,
  390. (const struct sockaddr *)&addr,
  391. (std::string("/network/") + arg1).c_str(),
  392. requestHeaders,
  393. "{}",
  394. 2,
  395. responseHeaders,
  396. responseBody);
  397. if (scode == 200) {
  398. if (json) {
  399. printf("%s",cliFixJsonCRs(responseBody).c_str());
  400. } else {
  401. printf("200 join OK" ZT_EOL_S);
  402. }
  403. return 0;
  404. } else {
  405. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  406. return 1;
  407. }
  408. } else if (command == "leave") {
  409. if (arg1.length() != 16) {
  410. cliPrintHelp(argv[0],stderr);
  411. return 2;
  412. }
  413. unsigned int scode = Http::DEL(
  414. 1024 * 1024 * 16,
  415. 60000,
  416. (const struct sockaddr *)&addr,
  417. (std::string("/network/") + arg1).c_str(),
  418. requestHeaders,
  419. responseHeaders,
  420. responseBody);
  421. if (scode == 200) {
  422. if (json) {
  423. printf("%s",cliFixJsonCRs(responseBody).c_str());
  424. } else {
  425. printf("200 leave OK" ZT_EOL_S);
  426. }
  427. return 0;
  428. } else {
  429. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  430. return 1;
  431. }
  432. } else if (command == "set") {
  433. if (arg1.length() != 16) {
  434. cliPrintHelp(argv[0],stderr);
  435. return 2;
  436. }
  437. std::size_t eqidx = arg2.find('=');
  438. if (eqidx != std::string::npos) {
  439. if ((arg2.substr(0,eqidx) == "allowManaged")||(arg2.substr(0,eqidx) == "allowGlobal")||(arg2.substr(0,eqidx) == "allowDefault")) {
  440. char jsons[1024];
  441. Utils::snprintf(jsons,sizeof(jsons),"{\"%s\":%s}",
  442. arg2.substr(0,eqidx).c_str(),
  443. (((arg2.substr(eqidx,2) == "=t")||(arg2.substr(eqidx,2) == "=1")) ? "true" : "false"));
  444. char cl[128];
  445. Utils::snprintf(cl,sizeof(cl),"%u",(unsigned int)strlen(jsons));
  446. requestHeaders["Content-Type"] = "application/json";
  447. requestHeaders["Content-Length"] = cl;
  448. unsigned int scode = Http::POST(
  449. 1024 * 1024 * 16,
  450. 60000,
  451. (const struct sockaddr *)&addr,
  452. (std::string("/network/") + arg1).c_str(),
  453. requestHeaders,
  454. jsons,
  455. strlen(jsons),
  456. responseHeaders,
  457. responseBody);
  458. if (scode == 200) {
  459. printf("%s",cliFixJsonCRs(responseBody).c_str());
  460. return 0;
  461. } else {
  462. printf("%u %s %s" ZT_EOL_S,scode,command.c_str(),responseBody.c_str());
  463. return 1;
  464. }
  465. }
  466. } else {
  467. cliPrintHelp(argv[0],stderr);
  468. return 2;
  469. }
  470. } else {
  471. cliPrintHelp(argv[0],stderr);
  472. return 0;
  473. }
  474. return 0;
  475. }
  476. /****************************************************************************/
  477. /* zerotier-idtool personality */
  478. /****************************************************************************/
  479. static void idtoolPrintHelp(FILE *out,const char *pn)
  480. {
  481. fprintf(out,
  482. "%s version %d.%d.%d" ZT_EOL_S,
  483. PROGRAM_NAME,
  484. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  485. fprintf(out,
  486. COPYRIGHT_NOTICE ZT_EOL_S
  487. LICENSE_GRANT ZT_EOL_S);
  488. fprintf(out,"Usage: %s <command> [<args>]" ZT_EOL_S"" ZT_EOL_S"Commands:" ZT_EOL_S,pn);
  489. fprintf(out," generate [<identity.secret>] [<identity.public>] [<vanity>]" ZT_EOL_S);
  490. fprintf(out," validate <identity.secret/public>" ZT_EOL_S);
  491. fprintf(out," getpublic <identity.secret>" ZT_EOL_S);
  492. fprintf(out," sign <identity.secret> <file>" ZT_EOL_S);
  493. fprintf(out," verify <identity.secret/public> <file> <signature>" ZT_EOL_S);
  494. fprintf(out," mkcom <identity.secret> [<id,value,maxDelta> ...] (hexadecimal integers)" ZT_EOL_S);
  495. }
  496. static Identity getIdFromArg(char *arg)
  497. {
  498. Identity id;
  499. if ((strlen(arg) > 32)&&(arg[10] == ':')) { // identity is a literal on the command line
  500. if (id.fromString(arg))
  501. return id;
  502. } else { // identity is to be read from a file
  503. std::string idser;
  504. if (OSUtils::readFile(arg,idser)) {
  505. if (id.fromString(idser))
  506. return id;
  507. }
  508. }
  509. return Identity();
  510. }
  511. #ifdef __WINDOWS__
  512. static int idtool(int argc, _TCHAR* argv[])
  513. #else
  514. static int idtool(int argc,char **argv)
  515. #endif
  516. {
  517. if (argc < 2) {
  518. idtoolPrintHelp(stdout,argv[0]);
  519. return 1;
  520. }
  521. if (!strcmp(argv[1],"generate")) {
  522. uint64_t vanity = 0;
  523. int vanityBits = 0;
  524. if (argc >= 5) {
  525. vanity = Utils::hexStrToU64(argv[4]) & 0xffffffffffULL;
  526. vanityBits = 4 * strlen(argv[4]);
  527. if (vanityBits > 40)
  528. vanityBits = 40;
  529. }
  530. Identity id;
  531. for(;;) {
  532. id.generate();
  533. if ((id.address().toInt() >> (40 - vanityBits)) == vanity) {
  534. if (vanityBits > 0) {
  535. fprintf(stderr,"vanity address: found %.10llx !\n",(unsigned long long)id.address().toInt());
  536. }
  537. break;
  538. } else {
  539. 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)));
  540. }
  541. }
  542. std::string idser = id.toString(true);
  543. if (argc >= 3) {
  544. if (!OSUtils::writeFile(argv[2],idser)) {
  545. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[2]);
  546. return 1;
  547. } else printf("%s written" ZT_EOL_S,argv[2]);
  548. if (argc >= 4) {
  549. idser = id.toString(false);
  550. if (!OSUtils::writeFile(argv[3],idser)) {
  551. fprintf(stderr,"Error writing to %s" ZT_EOL_S,argv[3]);
  552. return 1;
  553. } else printf("%s written" ZT_EOL_S,argv[3]);
  554. }
  555. } else printf("%s",idser.c_str());
  556. } else if (!strcmp(argv[1],"validate")) {
  557. if (argc < 3) {
  558. idtoolPrintHelp(stdout,argv[0]);
  559. return 1;
  560. }
  561. Identity id = getIdFromArg(argv[2]);
  562. if (!id) {
  563. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  564. return 1;
  565. }
  566. if (!id.locallyValidate()) {
  567. fprintf(stderr,"%s FAILED validation." ZT_EOL_S,argv[2]);
  568. return 1;
  569. } else printf("%s is a valid identity" ZT_EOL_S,argv[2]);
  570. } else if (!strcmp(argv[1],"getpublic")) {
  571. if (argc < 3) {
  572. idtoolPrintHelp(stdout,argv[0]);
  573. return 1;
  574. }
  575. Identity id = getIdFromArg(argv[2]);
  576. if (!id) {
  577. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  578. return 1;
  579. }
  580. printf("%s",id.toString(false).c_str());
  581. } else if (!strcmp(argv[1],"sign")) {
  582. if (argc < 4) {
  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. if (!id.hasPrivate()) {
  592. fprintf(stderr,"%s does not contain a private key (must use private to sign)" ZT_EOL_S,argv[2]);
  593. return 1;
  594. }
  595. std::string inf;
  596. if (!OSUtils::readFile(argv[3],inf)) {
  597. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  598. return 1;
  599. }
  600. C25519::Signature signature = id.sign(inf.data(),(unsigned int)inf.length());
  601. printf("%s",Utils::hex(signature.data,(unsigned int)signature.size()).c_str());
  602. } else if (!strcmp(argv[1],"verify")) {
  603. if (argc < 4) {
  604. idtoolPrintHelp(stdout,argv[0]);
  605. return 1;
  606. }
  607. Identity id = getIdFromArg(argv[2]);
  608. if (!id) {
  609. fprintf(stderr,"Identity argument invalid or file unreadable: %s" ZT_EOL_S,argv[2]);
  610. return 1;
  611. }
  612. std::string inf;
  613. if (!OSUtils::readFile(argv[3],inf)) {
  614. fprintf(stderr,"%s is not readable" ZT_EOL_S,argv[3]);
  615. return 1;
  616. }
  617. std::string signature(Utils::unhex(argv[4]));
  618. if ((signature.length() > ZT_ADDRESS_LENGTH)&&(id.verify(inf.data(),(unsigned int)inf.length(),signature.data(),(unsigned int)signature.length()))) {
  619. printf("%s signature valid" ZT_EOL_S,argv[3]);
  620. } else {
  621. fprintf(stderr,"%s signature check FAILED" ZT_EOL_S,argv[3]);
  622. return 1;
  623. }
  624. } else if (!strcmp(argv[1],"mkcom")) {
  625. if (argc < 3) {
  626. idtoolPrintHelp(stdout,argv[0]);
  627. return 1;
  628. }
  629. Identity id = getIdFromArg(argv[2]);
  630. if ((!id)||(!id.hasPrivate())) {
  631. fprintf(stderr,"Identity argument invalid, does not include private key, or file unreadable: %s" ZT_EOL_S,argv[2]);
  632. return 1;
  633. }
  634. CertificateOfMembership com;
  635. for(int a=3;a<argc;++a) {
  636. std::vector<std::string> params(Utils::split(argv[a],",","",""));
  637. if (params.size() == 3) {
  638. uint64_t qId = Utils::hexStrToU64(params[0].c_str());
  639. uint64_t qValue = Utils::hexStrToU64(params[1].c_str());
  640. uint64_t qMaxDelta = Utils::hexStrToU64(params[2].c_str());
  641. com.setQualifier(qId,qValue,qMaxDelta);
  642. }
  643. }
  644. if (!com.sign(id)) {
  645. fprintf(stderr,"Signature of certificate of membership failed." ZT_EOL_S);
  646. return 1;
  647. }
  648. printf("%s",com.toString().c_str());
  649. } else {
  650. idtoolPrintHelp(stdout,argv[0]);
  651. return 1;
  652. }
  653. return 0;
  654. }
  655. /****************************************************************************/
  656. /* Unix helper functions and signal handlers */
  657. /****************************************************************************/
  658. #ifdef __UNIX_LIKE__
  659. static void _sighandlerHup(int sig)
  660. {
  661. }
  662. static void _sighandlerQuit(int sig)
  663. {
  664. OneService *s = zt1Service;
  665. if (s)
  666. s->terminate();
  667. else exit(0);
  668. }
  669. #endif
  670. /****************************************************************************/
  671. /* Windows helper functions and signal handlers */
  672. /****************************************************************************/
  673. #ifdef __WINDOWS__
  674. // Console signal handler routine to allow CTRL+C to work, mostly for testing
  675. static BOOL WINAPI _winConsoleCtrlHandler(DWORD dwCtrlType)
  676. {
  677. switch(dwCtrlType) {
  678. case CTRL_C_EVENT:
  679. case CTRL_BREAK_EVENT:
  680. case CTRL_CLOSE_EVENT:
  681. case CTRL_SHUTDOWN_EVENT:
  682. OneService *s = zt1Service;
  683. if (s)
  684. s->terminate();
  685. return TRUE;
  686. }
  687. return FALSE;
  688. }
  689. static void _winPokeAHole()
  690. {
  691. char myPath[MAX_PATH];
  692. DWORD ps = GetModuleFileNameA(NULL,myPath,sizeof(myPath));
  693. if ((ps > 0)&&(ps < (DWORD)sizeof(myPath))) {
  694. STARTUPINFOA startupInfo;
  695. PROCESS_INFORMATION processInfo;
  696. startupInfo.cb = sizeof(startupInfo);
  697. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  698. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  699. 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)) {
  700. WaitForSingleObject(processInfo.hProcess,INFINITE);
  701. CloseHandle(processInfo.hProcess);
  702. CloseHandle(processInfo.hThread);
  703. }
  704. startupInfo.cb = sizeof(startupInfo);
  705. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  706. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  707. 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)) {
  708. WaitForSingleObject(processInfo.hProcess,INFINITE);
  709. CloseHandle(processInfo.hProcess);
  710. CloseHandle(processInfo.hThread);
  711. }
  712. startupInfo.cb = sizeof(startupInfo);
  713. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  714. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  715. 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)) {
  716. WaitForSingleObject(processInfo.hProcess,INFINITE);
  717. CloseHandle(processInfo.hProcess);
  718. CloseHandle(processInfo.hThread);
  719. }
  720. }
  721. }
  722. // Returns true if this is running as the local administrator
  723. static BOOL IsCurrentUserLocalAdministrator(void)
  724. {
  725. BOOL fReturn = FALSE;
  726. DWORD dwStatus;
  727. DWORD dwAccessMask;
  728. DWORD dwAccessDesired;
  729. DWORD dwACLSize;
  730. DWORD dwStructureSize = sizeof(PRIVILEGE_SET);
  731. PACL pACL = NULL;
  732. PSID psidAdmin = NULL;
  733. HANDLE hToken = NULL;
  734. HANDLE hImpersonationToken = NULL;
  735. PRIVILEGE_SET ps;
  736. GENERIC_MAPPING GenericMapping;
  737. PSECURITY_DESCRIPTOR psdAdmin = NULL;
  738. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  739. const DWORD ACCESS_READ = 1;
  740. const DWORD ACCESS_WRITE = 2;
  741. __try
  742. {
  743. if (!OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE|TOKEN_QUERY,TRUE,&hToken))
  744. {
  745. if (GetLastError() != ERROR_NO_TOKEN)
  746. __leave;
  747. if (!OpenProcessToken(GetCurrentProcess(),TOKEN_DUPLICATE|TOKEN_QUERY, &hToken))
  748. __leave;
  749. }
  750. if (!DuplicateToken (hToken, SecurityImpersonation,&hImpersonationToken))
  751. __leave;
  752. if (!AllocateAndInitializeSid(&SystemSidAuthority, 2,
  753. SECURITY_BUILTIN_DOMAIN_RID,
  754. DOMAIN_ALIAS_RID_ADMINS,
  755. 0, 0, 0, 0, 0, 0, &psidAdmin))
  756. __leave;
  757. psdAdmin = LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
  758. if (psdAdmin == NULL)
  759. __leave;
  760. if (!InitializeSecurityDescriptor(psdAdmin,SECURITY_DESCRIPTOR_REVISION))
  761. __leave;
  762. dwACLSize = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psidAdmin) - sizeof(DWORD);
  763. pACL = (PACL)LocalAlloc(LPTR, dwACLSize);
  764. if (pACL == NULL)
  765. __leave;
  766. if (!InitializeAcl(pACL, dwACLSize, ACL_REVISION2))
  767. __leave;
  768. dwAccessMask= ACCESS_READ | ACCESS_WRITE;
  769. if (!AddAccessAllowedAce(pACL, ACL_REVISION2, dwAccessMask, psidAdmin))
  770. __leave;
  771. if (!SetSecurityDescriptorDacl(psdAdmin, TRUE, pACL, FALSE))
  772. __leave;
  773. SetSecurityDescriptorGroup(psdAdmin, psidAdmin, FALSE);
  774. SetSecurityDescriptorOwner(psdAdmin, psidAdmin, FALSE);
  775. if (!IsValidSecurityDescriptor(psdAdmin))
  776. __leave;
  777. dwAccessDesired = ACCESS_READ;
  778. GenericMapping.GenericRead = ACCESS_READ;
  779. GenericMapping.GenericWrite = ACCESS_WRITE;
  780. GenericMapping.GenericExecute = 0;
  781. GenericMapping.GenericAll = ACCESS_READ | ACCESS_WRITE;
  782. if (!AccessCheck(psdAdmin, hImpersonationToken, dwAccessDesired,
  783. &GenericMapping, &ps, &dwStructureSize, &dwStatus,
  784. &fReturn))
  785. {
  786. fReturn = FALSE;
  787. __leave;
  788. }
  789. }
  790. __finally
  791. {
  792. // Clean up.
  793. if (pACL) LocalFree(pACL);
  794. if (psdAdmin) LocalFree(psdAdmin);
  795. if (psidAdmin) FreeSid(psidAdmin);
  796. if (hImpersonationToken) CloseHandle (hImpersonationToken);
  797. if (hToken) CloseHandle (hToken);
  798. }
  799. return fReturn;
  800. }
  801. #endif // __WINDOWS__
  802. /****************************************************************************/
  803. /* main() and friends */
  804. /****************************************************************************/
  805. static void printHelp(const char *cn,FILE *out)
  806. {
  807. fprintf(out,
  808. "%s version %d.%d.%d" ZT_EOL_S,
  809. PROGRAM_NAME,
  810. ZEROTIER_ONE_VERSION_MAJOR, ZEROTIER_ONE_VERSION_MINOR, ZEROTIER_ONE_VERSION_REVISION);
  811. fprintf(out,
  812. COPYRIGHT_NOTICE ZT_EOL_S
  813. LICENSE_GRANT ZT_EOL_S);
  814. std::string updateUrl(OneService::autoUpdateUrl());
  815. if (updateUrl.length())
  816. 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());
  817. fprintf(out,"Usage: %s [-switches] [home directory]" ZT_EOL_S"" ZT_EOL_S,cn);
  818. fprintf(out,"Available switches:" ZT_EOL_S);
  819. fprintf(out," -h - Display this help" ZT_EOL_S);
  820. fprintf(out," -v - Show version" ZT_EOL_S);
  821. fprintf(out," -U - Run as unprivileged user (skip privilege check)" ZT_EOL_S);
  822. fprintf(out," -p<port> - Port for UDP and TCP/HTTP (default: 9993, 0 for random)" ZT_EOL_S);
  823. #ifdef __UNIX_LIKE__
  824. fprintf(out," -d - Fork and run as daemon (Unix-ish OSes)" ZT_EOL_S);
  825. #endif // __UNIX_LIKE__
  826. #ifdef __WINDOWS__
  827. fprintf(out," -C - Run from command line instead of as service (Windows)" ZT_EOL_S);
  828. fprintf(out," -I - Install Windows service (Windows)" ZT_EOL_S);
  829. fprintf(out," -R - Uninstall Windows service (Windows)" ZT_EOL_S);
  830. fprintf(out," -D - Remove all instances of Windows tap device (Windows)" ZT_EOL_S);
  831. #endif // __WINDOWS__
  832. fprintf(out," -i - Generate and manage identities (zerotier-idtool)" ZT_EOL_S);
  833. fprintf(out," -q - Query API (zerotier-cli)" ZT_EOL_S);
  834. }
  835. #ifdef __WINDOWS__
  836. int _tmain(int argc, _TCHAR* argv[])
  837. #else
  838. int main(int argc,char **argv)
  839. #endif
  840. {
  841. #ifdef __UNIX_LIKE__
  842. signal(SIGHUP,&_sighandlerHup);
  843. signal(SIGPIPE,SIG_IGN);
  844. signal(SIGUSR1,SIG_IGN);
  845. signal(SIGUSR2,SIG_IGN);
  846. signal(SIGALRM,SIG_IGN);
  847. signal(SIGINT,&_sighandlerQuit);
  848. signal(SIGTERM,&_sighandlerQuit);
  849. signal(SIGQUIT,&_sighandlerQuit);
  850. /* Ensure that there are no inherited file descriptors open from a previous
  851. * incarnation. This is a hack to ensure that GitHub issue #61 or variants
  852. * of it do not return, and should not do anything otherwise bad. */
  853. {
  854. int mfd = STDIN_FILENO;
  855. if (STDOUT_FILENO > mfd) mfd = STDOUT_FILENO;
  856. if (STDERR_FILENO > mfd) mfd = STDERR_FILENO;
  857. for(int f=mfd+1;f<1024;++f)
  858. ::close(f);
  859. }
  860. bool runAsDaemon = false;
  861. #endif // __UNIX_LIKE__
  862. #ifdef __WINDOWS__
  863. {
  864. WSADATA wsaData;
  865. WSAStartup(MAKEWORD(2,2),&wsaData);
  866. }
  867. #ifdef ZT_WIN_RUN_IN_CONSOLE
  868. bool winRunFromCommandLine = true;
  869. #else
  870. bool winRunFromCommandLine = false;
  871. #endif
  872. #endif // __WINDOWS__
  873. if ((strstr(argv[0],"zerotier-idtool"))||(strstr(argv[0],"ZEROTIER-IDTOOL")))
  874. return idtool(argc,argv);
  875. if ((strstr(argv[0],"zerotier-cli"))||(strstr(argv[0],"ZEROTIER-CLI")))
  876. return cli(argc,argv);
  877. std::string homeDir;
  878. unsigned int port = ZT_DEFAULT_PORT;
  879. bool skipRootCheck = false;
  880. for(int i=1;i<argc;++i) {
  881. if (argv[i][0] == '-') {
  882. switch(argv[i][1]) {
  883. case 'p': // port -- for both UDP and TCP, packets and control plane
  884. port = Utils::strToUInt(argv[i] + 2);
  885. if (port > 0xffff) {
  886. printHelp(argv[0],stdout);
  887. return 1;
  888. }
  889. break;
  890. #ifdef __UNIX_LIKE__
  891. case 'd': // Run in background as daemon
  892. runAsDaemon = true;
  893. break;
  894. #endif // __UNIX_LIKE__
  895. case 'U':
  896. skipRootCheck = true;
  897. break;
  898. case 'v': // Display version
  899. printf("%d.%d.%d" ZT_EOL_S,ZEROTIER_ONE_VERSION_MAJOR,ZEROTIER_ONE_VERSION_MINOR,ZEROTIER_ONE_VERSION_REVISION);
  900. return 0;
  901. case 'i': // Invoke idtool personality
  902. if (argv[i][2]) {
  903. printHelp(argv[0],stdout);
  904. return 0;
  905. } else return idtool(argc,argv);
  906. case 'q': // Invoke cli personality
  907. if (argv[i][2]) {
  908. printHelp(argv[0],stdout);
  909. return 0;
  910. } else return cli(argc,argv);
  911. #ifdef __WINDOWS__
  912. case 'C': // Run from command line instead of as Windows service
  913. winRunFromCommandLine = true;
  914. break;
  915. case 'I': { // Install this binary as a Windows service
  916. if (IsCurrentUserLocalAdministrator() != TRUE) {
  917. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  918. return 1;
  919. }
  920. std::string ret(InstallService(ZT_SERVICE_NAME,ZT_SERVICE_DISPLAY_NAME,ZT_SERVICE_START_TYPE,ZT_SERVICE_DEPENDENCIES,ZT_SERVICE_ACCOUNT,ZT_SERVICE_PASSWORD));
  921. if (ret.length()) {
  922. fprintf(stderr,"%s: unable to install service: %s" ZT_EOL_S,argv[0],ret.c_str());
  923. return 3;
  924. }
  925. return 0;
  926. } break;
  927. case 'R': { // Uninstall this binary as Windows service
  928. if (IsCurrentUserLocalAdministrator() != TRUE) {
  929. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  930. return 1;
  931. }
  932. std::string ret(UninstallService(ZT_SERVICE_NAME));
  933. if (ret.length()) {
  934. fprintf(stderr,"%s: unable to uninstall service: %s" ZT_EOL_S,argv[0],ret.c_str());
  935. return 3;
  936. }
  937. return 0;
  938. } break;
  939. case 'D': {
  940. std::string err = WindowsEthernetTap::destroyAllPersistentTapDevices();
  941. if (err.length() > 0) {
  942. fprintf(stderr,"%s: unable to uninstall one or more persistent tap devices: %s" ZT_EOL_S,argv[0],err.c_str());
  943. return 3;
  944. }
  945. return 0;
  946. } break;
  947. #endif // __WINDOWS__
  948. case 'h':
  949. case '?':
  950. default:
  951. printHelp(argv[0],stdout);
  952. return 0;
  953. }
  954. } else {
  955. if (homeDir.length()) {
  956. printHelp(argv[0],stdout);
  957. return 0;
  958. } else {
  959. homeDir = argv[i];
  960. }
  961. }
  962. }
  963. if (!homeDir.length())
  964. homeDir = OneService::platformDefaultHomePath();
  965. if (!homeDir.length()) {
  966. fprintf(stderr,"%s: no home path specified and no platform default available" ZT_EOL_S,argv[0]);
  967. return 1;
  968. } else {
  969. std::vector<std::string> hpsp(Utils::split(homeDir.c_str(),ZT_PATH_SEPARATOR_S,"",""));
  970. std::string ptmp;
  971. if (homeDir[0] == ZT_PATH_SEPARATOR)
  972. ptmp.push_back(ZT_PATH_SEPARATOR);
  973. for(std::vector<std::string>::iterator pi(hpsp.begin());pi!=hpsp.end();++pi) {
  974. if (ptmp.length() > 0)
  975. ptmp.push_back(ZT_PATH_SEPARATOR);
  976. ptmp.append(*pi);
  977. if ((*pi != ".")&&(*pi != "..")) {
  978. if (!OSUtils::mkdir(ptmp))
  979. throw std::runtime_error("home path does not exist, and could not create");
  980. }
  981. }
  982. }
  983. // This can be removed once the new controller code has been around for many versions
  984. if (OSUtils::fileExists((homeDir + ZT_PATH_SEPARATOR_S + "controller.db").c_str(),true)) {
  985. 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());
  986. return 1;
  987. }
  988. #ifdef __UNIX_LIKE__
  989. #ifndef ZT_ONE_NO_ROOT_CHECK
  990. if ((!skipRootCheck)&&(getuid() != 0)) {
  991. fprintf(stderr,"%s: must be run as root (uid 0)" ZT_EOL_S,argv[0]);
  992. return 1;
  993. }
  994. #endif // !ZT_ONE_NO_ROOT_CHECK
  995. if (runAsDaemon) {
  996. long p = (long)fork();
  997. if (p < 0) {
  998. fprintf(stderr,"%s: could not fork" ZT_EOL_S,argv[0]);
  999. return 1;
  1000. } else if (p > 0)
  1001. return 0; // forked
  1002. // else p == 0, so we are daemonized
  1003. }
  1004. #endif // __UNIX_LIKE__
  1005. #ifdef __WINDOWS__
  1006. // Uninstall legacy tap devices. New devices will automatically be installed and configured
  1007. // when tap instances are created.
  1008. WindowsEthernetTap::destroyAllLegacyPersistentTapDevices();
  1009. if (winRunFromCommandLine) {
  1010. // Running in "interactive" mode (mostly for debugging)
  1011. if (IsCurrentUserLocalAdministrator() != TRUE) {
  1012. if (!skipRootCheck) {
  1013. fprintf(stderr,"%s: must be run as a local administrator." ZT_EOL_S,argv[0]);
  1014. return 1;
  1015. }
  1016. } else {
  1017. _winPokeAHole();
  1018. }
  1019. SetConsoleCtrlHandler(&_winConsoleCtrlHandler,TRUE);
  1020. // continues on to ordinary command line execution code below...
  1021. } else {
  1022. // Running from service manager
  1023. _winPokeAHole();
  1024. ZeroTierOneService zt1Service;
  1025. if (CServiceBase::Run(zt1Service) == TRUE) {
  1026. return 0;
  1027. } else {
  1028. fprintf(stderr,"%s: unable to start service (try -h for help)" ZT_EOL_S,argv[0]);
  1029. return 1;
  1030. }
  1031. }
  1032. #endif // __WINDOWS__
  1033. #ifdef __UNIX_LIKE__
  1034. std::string pidPath(homeDir + ZT_PATH_SEPARATOR_S + ZT_PID_PATH);
  1035. {
  1036. // Write .pid file to home folder
  1037. FILE *pf = fopen(pidPath.c_str(),"w");
  1038. if (pf) {
  1039. fprintf(pf,"%ld",(long)getpid());
  1040. fclose(pf);
  1041. }
  1042. }
  1043. #endif // __UNIX_LIKE__
  1044. unsigned int returnValue = 0;
  1045. for(;;) {
  1046. zt1Service = OneService::newInstance(homeDir.c_str(),port);
  1047. switch(zt1Service->run()) {
  1048. case OneService::ONE_STILL_RUNNING: // shouldn't happen, run() won't return until done
  1049. case OneService::ONE_NORMAL_TERMINATION:
  1050. break;
  1051. case OneService::ONE_UNRECOVERABLE_ERROR:
  1052. fprintf(stderr,"%s: fatal error: %s" ZT_EOL_S,argv[0],zt1Service->fatalErrorMessage().c_str());
  1053. returnValue = 1;
  1054. break;
  1055. case OneService::ONE_IDENTITY_COLLISION: {
  1056. delete zt1Service;
  1057. zt1Service = (OneService *)0;
  1058. std::string oldid;
  1059. OSUtils::readFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str(),oldid);
  1060. if (oldid.length()) {
  1061. OSUtils::writeFile((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret.saved_after_collision").c_str(),oldid);
  1062. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.secret").c_str());
  1063. OSUtils::rm((homeDir + ZT_PATH_SEPARATOR_S + "identity.public").c_str());
  1064. }
  1065. } continue; // restart!
  1066. }
  1067. break; // terminate loop -- normally we don't keep restarting
  1068. }
  1069. delete zt1Service;
  1070. zt1Service = (OneService *)0;
  1071. #ifdef __UNIX_LIKE__
  1072. OSUtils::rm(pidPath.c_str());
  1073. #endif
  1074. return returnValue;
  1075. }