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