##// END OF EJS Templates
chg: close file descriptors when starting the daemon...
Mathias De Mare -
r46416:8711dc13 stable
parent child Browse files
Show More
@@ -1,517 +1,543 b''
1 1 /*
2 2 * A fast client for Mercurial command server
3 3 *
4 4 * Copyright (c) 2011 Yuya Nishihara <yuya@tcha.org>
5 5 *
6 6 * This software may be used and distributed according to the terms of the
7 7 * GNU General Public License version 2 or any later version.
8 8 */
9 9
10 10 #include <assert.h>
11 #include <dirent.h>
11 12 #include <errno.h>
12 13 #include <fcntl.h>
13 14 #include <signal.h>
14 15 #include <stdio.h>
15 16 #include <stdlib.h>
16 17 #include <string.h>
17 18 #include <sys/file.h>
18 19 #include <sys/stat.h>
19 20 #include <sys/types.h>
20 21 #include <sys/un.h>
21 22 #include <sys/wait.h>
22 23 #include <time.h>
23 24 #include <unistd.h>
24 25
25 26 #include "hgclient.h"
26 27 #include "procutil.h"
27 28 #include "util.h"
28 29
29 30 #ifndef PATH_MAX
30 31 #define PATH_MAX 4096
31 32 #endif
32 33
33 34 struct cmdserveropts {
34 35 char sockname[PATH_MAX];
35 36 char initsockname[PATH_MAX];
36 37 char redirectsockname[PATH_MAX];
37 38 size_t argsize;
38 39 const char **args;
39 40 };
40 41
41 42 static void initcmdserveropts(struct cmdserveropts *opts)
42 43 {
43 44 memset(opts, 0, sizeof(struct cmdserveropts));
44 45 }
45 46
46 47 static void freecmdserveropts(struct cmdserveropts *opts)
47 48 {
48 49 free(opts->args);
49 50 opts->args = NULL;
50 51 opts->argsize = 0;
51 52 }
52 53
53 54 /*
54 55 * Test if an argument is a sensitive flag that should be passed to the server.
55 56 * Return 0 if not, otherwise the number of arguments starting from the current
56 57 * one that should be passed to the server.
57 58 */
58 59 static size_t testsensitiveflag(const char *arg)
59 60 {
60 61 static const struct {
61 62 const char *name;
62 63 size_t narg;
63 64 } flags[] = {
64 65 {"--config", 1}, {"--cwd", 1}, {"--repo", 1},
65 66 {"--repository", 1}, {"--traceback", 0}, {"-R", 1},
66 67 };
67 68 size_t i;
68 69 for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i) {
69 70 size_t len = strlen(flags[i].name);
70 71 size_t narg = flags[i].narg;
71 72 if (memcmp(arg, flags[i].name, len) == 0) {
72 73 if (arg[len] == '\0') {
73 74 /* --flag (value) */
74 75 return narg + 1;
75 76 } else if (arg[len] == '=' && narg > 0) {
76 77 /* --flag=value */
77 78 return 1;
78 79 } else if (flags[i].name[1] != '-') {
79 80 /* short flag */
80 81 return 1;
81 82 }
82 83 }
83 84 }
84 85 return 0;
85 86 }
86 87
87 88 /*
88 89 * Parse argv[] and put sensitive flags to opts->args
89 90 */
90 91 static void setcmdserverargs(struct cmdserveropts *opts, int argc,
91 92 const char *argv[])
92 93 {
93 94 size_t i, step;
94 95 opts->argsize = 0;
95 96 for (i = 0, step = 1; i < (size_t)argc; i += step, step = 1) {
96 97 if (!argv[i])
97 98 continue; /* pass clang-analyse */
98 99 if (strcmp(argv[i], "--") == 0)
99 100 break;
100 101 size_t n = testsensitiveflag(argv[i]);
101 102 if (n == 0 || i + n > (size_t)argc)
102 103 continue;
103 104 opts->args =
104 105 reallocx(opts->args, (n + opts->argsize) * sizeof(char *));
105 106 memcpy(opts->args + opts->argsize, argv + i,
106 107 sizeof(char *) * n);
107 108 opts->argsize += n;
108 109 step = n;
109 110 }
110 111 }
111 112
112 113 static void preparesockdir(const char *sockdir)
113 114 {
114 115 int r;
115 116 r = mkdir(sockdir, 0700);
116 117 if (r < 0 && errno != EEXIST)
117 118 abortmsgerrno("cannot create sockdir %s", sockdir);
118 119
119 120 struct stat st;
120 121 r = lstat(sockdir, &st);
121 122 if (r < 0)
122 123 abortmsgerrno("cannot stat %s", sockdir);
123 124 if (!S_ISDIR(st.st_mode))
124 125 abortmsg("cannot create sockdir %s (file exists)", sockdir);
125 126 if (st.st_uid != geteuid() || st.st_mode & 0077)
126 127 abortmsg("insecure sockdir %s", sockdir);
127 128 }
128 129
129 130 /*
130 131 * Check if a socket directory exists and is only owned by the current user.
131 132 * Return 1 if so, 0 if not. This is used to check if XDG_RUNTIME_DIR can be
132 133 * used or not. According to the specification [1], XDG_RUNTIME_DIR should be
133 134 * ignored if the directory is not owned by the user with mode 0700.
134 135 * [1]: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
135 136 */
136 137 static int checkruntimedir(const char *sockdir)
137 138 {
138 139 struct stat st;
139 140 int r = lstat(sockdir, &st);
140 141 if (r < 0) /* ex. does not exist */
141 142 return 0;
142 143 if (!S_ISDIR(st.st_mode)) /* ex. is a file, not a directory */
143 144 return 0;
144 145 return st.st_uid == geteuid() && (st.st_mode & 0777) == 0700;
145 146 }
146 147
147 148 static void getdefaultsockdir(char sockdir[], size_t size)
148 149 {
149 150 /* by default, put socket file in secure directory
150 151 * (${XDG_RUNTIME_DIR}/chg, or /${TMPDIR:-tmp}/chg$UID)
151 152 * (permission of socket file may be ignored on some Unices) */
152 153 const char *runtimedir = getenv("XDG_RUNTIME_DIR");
153 154 int r;
154 155 if (runtimedir && checkruntimedir(runtimedir)) {
155 156 r = snprintf(sockdir, size, "%s/chg", runtimedir);
156 157 } else {
157 158 const char *tmpdir = getenv("TMPDIR");
158 159 if (!tmpdir)
159 160 tmpdir = "/tmp";
160 161 r = snprintf(sockdir, size, "%s/chg%d", tmpdir, geteuid());
161 162 }
162 163 if (r < 0 || (size_t)r >= size)
163 164 abortmsg("too long TMPDIR (r = %d)", r);
164 165 }
165 166
166 167 static void setcmdserveropts(struct cmdserveropts *opts)
167 168 {
168 169 int r;
169 170 char sockdir[PATH_MAX];
170 171 const char *envsockname = getenv("CHGSOCKNAME");
171 172 if (!envsockname) {
172 173 getdefaultsockdir(sockdir, sizeof(sockdir));
173 174 preparesockdir(sockdir);
174 175 }
175 176
176 177 const char *basename = (envsockname) ? envsockname : sockdir;
177 178 const char *sockfmt = (envsockname) ? "%s" : "%s/server";
178 179 r = snprintf(opts->sockname, sizeof(opts->sockname), sockfmt, basename);
179 180 if (r < 0 || (size_t)r >= sizeof(opts->sockname))
180 181 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
181 182 r = snprintf(opts->initsockname, sizeof(opts->initsockname), "%s.%u",
182 183 opts->sockname, (unsigned)getpid());
183 184 if (r < 0 || (size_t)r >= sizeof(opts->initsockname))
184 185 abortmsg("too long TMPDIR or CHGSOCKNAME (r = %d)", r);
185 186 }
186 187
187 188 /* If the current program is, say, /a/b/c/chg, returns /a/b/c/hg. */
188 189 static char *getrelhgcmd(void)
189 190 {
190 191 ssize_t n;
191 192 char *res, *slash;
192 193 int maxsize = 4096;
193 194 res = malloc(maxsize);
194 195 if (res == NULL)
195 196 goto cleanup;
196 197 n = readlink("/proc/self/exe", res, maxsize);
197 198 if (n < 0 || n >= maxsize)
198 199 goto cleanup;
199 200 res[n] = '\0';
200 201 slash = strrchr(res, '/');
201 202 if (slash == NULL)
202 203 goto cleanup;
203 204 /* 4 is strlen("/hg") + nul byte */
204 205 if (slash + 4 >= res + maxsize)
205 206 goto cleanup;
206 207 memcpy(slash, "/hg", 4);
207 208 return res;
208 209 cleanup:
209 210 free(res);
210 211 return NULL;
211 212 }
212 213
213 214 static const char *gethgcmd(void)
214 215 {
215 216 static const char *hgcmd = NULL;
216 217 #ifdef HGPATHREL
217 218 int tryrelhgcmd = 1;
218 219 #else
219 220 int tryrelhgcmd = 0;
220 221 #endif
221 222 if (!hgcmd) {
222 223 hgcmd = getenv("CHGHG");
223 224 if (!hgcmd || hgcmd[0] == '\0')
224 225 hgcmd = getenv("HG");
225 226 if (tryrelhgcmd && (!hgcmd || hgcmd[0] == '\0'))
226 227 hgcmd = getrelhgcmd();
227 228 if (!hgcmd || hgcmd[0] == '\0')
228 229 #ifdef HGPATH
229 230 hgcmd = (HGPATH);
230 231 #else
231 232 hgcmd = "hg";
232 233 #endif
233 234 }
234 235 return hgcmd;
235 236 }
236 237
237 238 static void execcmdserver(const struct cmdserveropts *opts)
238 239 {
239 240 const char *hgcmd = gethgcmd();
240 241
241 242 const char *baseargv[] = {
242 243 hgcmd,
243 244 "serve",
244 245 "--cmdserver",
245 246 "chgunix",
246 247 "--address",
247 248 opts->initsockname,
248 249 "--daemon-postexec",
249 250 "chdir:/",
250 251 };
251 252 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
252 253 size_t argsize = baseargvsize + opts->argsize + 1;
253 254
254 255 const char **argv = mallocx(sizeof(char *) * argsize);
255 256 memcpy(argv, baseargv, sizeof(baseargv));
256 257 if (opts->args) {
257 258 size_t size = sizeof(char *) * opts->argsize;
258 259 memcpy(argv + baseargvsize, opts->args, size);
259 260 }
260 261 argv[argsize - 1] = NULL;
261 262
262 263 const char *lc_ctype_env = getenv("LC_CTYPE");
263 264 if (lc_ctype_env == NULL) {
264 265 if (putenv("CHG_CLEAR_LC_CTYPE=") != 0)
265 266 abortmsgerrno("failed to putenv CHG_CLEAR_LC_CTYPE");
266 267 } else {
267 268 if (setenv("CHGORIG_LC_CTYPE", lc_ctype_env, 1) != 0) {
268 269 abortmsgerrno("failed to setenv CHGORIG_LC_CTYPE");
269 270 }
270 271 }
271 272
273 /* close any open files to avoid hanging locks */
274 DIR *dp = opendir("/proc/self/fd");
275 if (dp != NULL) {
276 debugmsg("closing files based on /proc contents");
277 struct dirent *de;
278 while ((de = readdir(dp))) {
279 char *end;
280 long fd_value = strtol(de->d_name, &end, 10);
281 if (end == de->d_name) {
282 /* unable to convert to int (. or ..) */
283 continue;
284 }
285 if (errno == ERANGE) {
286 debugmsg("tried to parse %s, but range error occurred", de->d_name);
287 continue;
288 }
289 if (fd_value > STDERR_FILENO) {
290 int res = close(fd_value);
291 if (res) {
292 debugmsg("tried to close fd %ld: %d (errno: %d)", fd_value, res, errno);
293 }
294 }
295 }
296 }
297
272 298 if (putenv("CHGINTERNALMARK=") != 0)
273 299 abortmsgerrno("failed to putenv");
274 300 if (execvp(hgcmd, (char **)argv) < 0)
275 301 abortmsgerrno("failed to exec cmdserver");
276 302 free(argv);
277 303 }
278 304
279 305 /* Retry until we can connect to the server. Give up after some time. */
280 306 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
281 307 {
282 308 static const struct timespec sleepreq = {0, 10 * 1000000};
283 309 int pst = 0;
284 310
285 311 debugmsg("try connect to %s repeatedly", opts->initsockname);
286 312
287 313 unsigned int timeoutsec = 60; /* default: 60 seconds */
288 314 const char *timeoutenv = getenv("CHGTIMEOUT");
289 315 if (timeoutenv)
290 316 sscanf(timeoutenv, "%u", &timeoutsec);
291 317
292 318 for (unsigned int i = 0; !timeoutsec || i < timeoutsec * 100; i++) {
293 319 hgclient_t *hgc = hgc_open(opts->initsockname);
294 320 if (hgc) {
295 321 debugmsg("rename %s to %s", opts->initsockname,
296 322 opts->sockname);
297 323 int r = rename(opts->initsockname, opts->sockname);
298 324 if (r != 0)
299 325 abortmsgerrno("cannot rename");
300 326 return hgc;
301 327 }
302 328
303 329 if (pid > 0) {
304 330 /* collect zombie if child process fails to start */
305 331 int r = waitpid(pid, &pst, WNOHANG);
306 332 if (r != 0)
307 333 goto cleanup;
308 334 }
309 335
310 336 nanosleep(&sleepreq, NULL);
311 337 }
312 338
313 339 abortmsg("timed out waiting for cmdserver %s", opts->initsockname);
314 340 return NULL;
315 341
316 342 cleanup:
317 343 if (WIFEXITED(pst)) {
318 344 if (WEXITSTATUS(pst) == 0)
319 345 abortmsg("could not connect to cmdserver "
320 346 "(exited with status 0)");
321 347 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
322 348 exit(WEXITSTATUS(pst));
323 349 } else if (WIFSIGNALED(pst)) {
324 350 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
325 351 } else {
326 352 abortmsg("error while waiting for cmdserver");
327 353 }
328 354 return NULL;
329 355 }
330 356
331 357 /* Connect to a cmdserver. Will start a new server on demand. */
332 358 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
333 359 {
334 360 const char *sockname =
335 361 opts->redirectsockname[0] ? opts->redirectsockname : opts->sockname;
336 362 debugmsg("try connect to %s", sockname);
337 363 hgclient_t *hgc = hgc_open(sockname);
338 364 if (hgc)
339 365 return hgc;
340 366
341 367 /* prevent us from being connected to an outdated server: we were
342 368 * told by a server to redirect to opts->redirectsockname and that
343 369 * address does not work. we do not want to connect to the server
344 370 * again because it will probably tell us the same thing. */
345 371 if (sockname == opts->redirectsockname)
346 372 unlink(opts->sockname);
347 373
348 374 debugmsg("start cmdserver at %s", opts->initsockname);
349 375
350 376 pid_t pid = fork();
351 377 if (pid < 0)
352 378 abortmsg("failed to fork cmdserver process");
353 379 if (pid == 0) {
354 380 execcmdserver(opts);
355 381 } else {
356 382 hgc = retryconnectcmdserver(opts, pid);
357 383 }
358 384
359 385 return hgc;
360 386 }
361 387
362 388 static void killcmdserver(const struct cmdserveropts *opts)
363 389 {
364 390 /* resolve config hash */
365 391 char *resolvedpath = realpath(opts->sockname, NULL);
366 392 if (resolvedpath) {
367 393 unlink(resolvedpath);
368 394 free(resolvedpath);
369 395 }
370 396 }
371 397
372 398 /* Run instructions sent from the server like unlink and set redirect path
373 399 * Return 1 if reconnect is needed, otherwise 0 */
374 400 static int runinstructions(struct cmdserveropts *opts, const char **insts)
375 401 {
376 402 int needreconnect = 0;
377 403 if (!insts)
378 404 return needreconnect;
379 405
380 406 assert(insts);
381 407 opts->redirectsockname[0] = '\0';
382 408 const char **pinst;
383 409 for (pinst = insts; *pinst; pinst++) {
384 410 debugmsg("instruction: %s", *pinst);
385 411 if (strncmp(*pinst, "unlink ", 7) == 0) {
386 412 unlink(*pinst + 7);
387 413 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
388 414 int r = snprintf(opts->redirectsockname,
389 415 sizeof(opts->redirectsockname), "%s",
390 416 *pinst + 9);
391 417 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
392 418 abortmsg("redirect path is too long (%d)", r);
393 419 needreconnect = 1;
394 420 } else if (strncmp(*pinst, "exit ", 5) == 0) {
395 421 int n = 0;
396 422 if (sscanf(*pinst + 5, "%d", &n) != 1)
397 423 abortmsg("cannot read the exit code");
398 424 exit(n);
399 425 } else if (strcmp(*pinst, "reconnect") == 0) {
400 426 needreconnect = 1;
401 427 } else {
402 428 abortmsg("unknown instruction: %s", *pinst);
403 429 }
404 430 }
405 431 return needreconnect;
406 432 }
407 433
408 434 /*
409 435 * Test whether the command and the environment is unsupported or not.
410 436 *
411 437 * If any of the stdio file descriptors are not present (rare, but some tools
412 438 * might spawn new processes without stdio instead of redirecting them to the
413 439 * null device), then mark it as not supported because attachio won't work
414 440 * correctly.
415 441 *
416 442 * The command list is not designed to cover all cases. But it's fast, and does
417 443 * not depend on the server.
418 444 */
419 445 static int isunsupported(int argc, const char *argv[])
420 446 {
421 447 enum { SERVE = 1,
422 448 DAEMON = 2,
423 449 SERVEDAEMON = SERVE | DAEMON,
424 450 };
425 451 unsigned int state = 0;
426 452 int i;
427 453 /* use fcntl to test missing stdio fds */
428 454 if (fcntl(STDIN_FILENO, F_GETFD) == -1 ||
429 455 fcntl(STDOUT_FILENO, F_GETFD) == -1 ||
430 456 fcntl(STDERR_FILENO, F_GETFD) == -1) {
431 457 debugmsg("stdio fds are missing");
432 458 return 1;
433 459 }
434 460 for (i = 0; i < argc; ++i) {
435 461 if (strcmp(argv[i], "--") == 0)
436 462 break;
437 463 /*
438 464 * there can be false positives but no false negative
439 465 * we cannot assume `serve` will always be first argument
440 466 * because global options can be passed before the command name
441 467 */
442 468 if (strcmp("serve", argv[i]) == 0)
443 469 state |= SERVE;
444 470 else if (strcmp("-d", argv[i]) == 0 ||
445 471 strcmp("--daemon", argv[i]) == 0)
446 472 state |= DAEMON;
447 473 }
448 474 return (state & SERVEDAEMON) == SERVEDAEMON;
449 475 }
450 476
451 477 static void execoriginalhg(const char *argv[])
452 478 {
453 479 debugmsg("execute original hg");
454 480 if (execvp(gethgcmd(), (char **)argv) < 0)
455 481 abortmsgerrno("failed to exec original hg");
456 482 }
457 483
458 484 int main(int argc, const char *argv[], const char *envp[])
459 485 {
460 486 if (getenv("CHGDEBUG"))
461 487 enabledebugmsg();
462 488
463 489 if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
464 490 enablecolor();
465 491
466 492 if (getenv("CHGINTERNALMARK"))
467 493 abortmsg("chg started by chg detected.\n"
468 494 "Please make sure ${HG:-hg} is not a symlink or "
469 495 "wrapper to chg. Alternatively, set $CHGHG to the "
470 496 "path of real hg.");
471 497
472 498 if (isunsupported(argc - 1, argv + 1))
473 499 execoriginalhg(argv);
474 500
475 501 struct cmdserveropts opts;
476 502 initcmdserveropts(&opts);
477 503 setcmdserveropts(&opts);
478 504 setcmdserverargs(&opts, argc, argv);
479 505
480 506 if (argc == 2) {
481 507 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
482 508 killcmdserver(&opts);
483 509 return 0;
484 510 }
485 511 }
486 512
487 513 hgclient_t *hgc;
488 514 size_t retry = 0;
489 515 while (1) {
490 516 hgc = connectcmdserver(&opts);
491 517 if (!hgc)
492 518 abortmsg("cannot open hg client");
493 519 hgc_setenv(hgc, envp);
494 520 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
495 521 int needreconnect = runinstructions(&opts, insts);
496 522 free(insts);
497 523 if (!needreconnect)
498 524 break;
499 525 hgc_close(hgc);
500 526 if (++retry > 10)
501 527 abortmsg("too many redirections.\n"
502 528 "Please make sure %s is not a wrapper which "
503 529 "changes sensitive environment variables "
504 530 "before executing hg. If you have to use a "
505 531 "wrapper, wrap chg instead of hg.",
506 532 gethgcmd());
507 533 }
508 534
509 535 setupsignalhandler(hgc_peerpid(hgc), hgc_peerpgid(hgc));
510 536 atexit(waitpager);
511 537 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
512 538 restoresignalhandler();
513 539 hgc_close(hgc);
514 540 freecmdserveropts(&opts);
515 541
516 542 return exitcode;
517 543 }
General Comments 0
You need to be logged in to leave comments. Login now