one.cpp 40 KB

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