one.cpp 39 KB

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