one.cpp 38 KB

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