one.cpp 38 KB

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