one.cpp 39 KB

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