##// END OF EJS Templates
chg: populate CHGHG if not set...
Arun Kulshreshtha -
r51279:cf4d2f31 stable
parent child Browse files
Show More
@@ -1,546 +1,559 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 /* Set $CHGHG to the path to the seleted hg executable if it wasn't
236 * already set. This has the effect of ensuring that a new command
237 * server will be spawned if the existing command server is running from
238 * an executable at a different path. */
239 if (setenv("CHGHG", hgcmd, 1) != 0)
240 abortmsgerrno("failed to setenv");
235 241 return hgcmd;
236 242 }
237 243
238 static void execcmdserver(const struct cmdserveropts *opts)
244 static void execcmdserver(const char *hgcmd, const struct cmdserveropts *opts)
239 245 {
240 const char *hgcmd = gethgcmd();
241 246
242 247 const char *baseargv[] = {
243 248 hgcmd, "serve", "--no-profile", "--cmdserver",
244 249 "chgunix", "--address", opts->initsockname, "--daemon-postexec",
245 250 "chdir:/",
246 251 };
247 252 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
248 253 size_t argsize = baseargvsize + opts->argsize + 1;
249 254
250 255 const char **argv = mallocx(sizeof(char *) * argsize);
251 256 memcpy(argv, baseargv, sizeof(baseargv));
252 257 if (opts->args) {
253 258 size_t size = sizeof(char *) * opts->argsize;
254 259 memcpy(argv + baseargvsize, opts->args, size);
255 260 }
256 261 argv[argsize - 1] = NULL;
257 262
258 263 const char *lc_ctype_env = getenv("LC_CTYPE");
259 264 if (lc_ctype_env == NULL) {
260 265 if (putenv("CHG_CLEAR_LC_CTYPE=") != 0)
261 266 abortmsgerrno("failed to putenv CHG_CLEAR_LC_CTYPE");
262 267 } else {
263 268 if (setenv("CHGORIG_LC_CTYPE", lc_ctype_env, 1) != 0) {
264 269 abortmsgerrno("failed to setenv CHGORIG_LC_CTYPE");
265 270 }
266 271 }
267 272
268 273 /* close any open files to avoid hanging locks */
269 274 DIR *dp = opendir("/proc/self/fd");
270 275 if (dp != NULL) {
271 276 debugmsg("closing files based on /proc contents");
272 277 struct dirent *de;
273 278 while ((de = readdir(dp))) {
274 279 errno = 0;
275 280 char *end;
276 281 long fd_value = strtol(de->d_name, &end, 10);
277 282 if (end == de->d_name) {
278 283 /* unable to convert to int (. or ..) */
279 284 continue;
280 285 }
281 286 if (errno == ERANGE) {
282 287 debugmsg("tried to parse %s, but range error "
283 288 "occurred",
284 289 de->d_name);
285 290 continue;
286 291 }
287 292 if (fd_value > STDERR_FILENO && fd_value != dirfd(dp)) {
288 293 debugmsg("closing fd %ld", fd_value);
289 294 int res = close(fd_value);
290 295 if (res) {
291 296 debugmsg("tried to close fd %ld: %d "
292 297 "(errno: %d)",
293 298 fd_value, res, errno);
294 299 }
295 300 }
296 301 }
297 302 closedir(dp);
298 303 }
299 304
300 305 if (putenv("CHGINTERNALMARK=") != 0)
301 306 abortmsgerrno("failed to putenv");
302 307 if (execvp(hgcmd, (char **)argv) < 0)
303 308 abortmsgerrno("failed to exec cmdserver");
304 309 free(argv);
305 310 }
306 311
307 312 /* Retry until we can connect to the server. Give up after some time. */
308 313 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
309 314 {
310 315 static const struct timespec sleepreq = {0, 10 * 1000000};
311 316 int pst = 0;
312 317
313 318 debugmsg("try connect to %s repeatedly", opts->initsockname);
314 319
315 320 unsigned int timeoutsec = 60; /* default: 60 seconds */
316 321 const char *timeoutenv = getenv("CHGTIMEOUT");
317 322 if (timeoutenv)
318 323 sscanf(timeoutenv, "%u", &timeoutsec);
319 324
320 325 for (unsigned int i = 0; !timeoutsec || i < timeoutsec * 100; i++) {
321 326 hgclient_t *hgc = hgc_open(opts->initsockname);
322 327 if (hgc) {
323 328 debugmsg("rename %s to %s", opts->initsockname,
324 329 opts->sockname);
325 330 int r = rename(opts->initsockname, opts->sockname);
326 331 if (r != 0)
327 332 abortmsgerrno("cannot rename");
328 333 return hgc;
329 334 }
330 335
331 336 if (pid > 0) {
332 337 /* collect zombie if child process fails to start */
333 338 int r = waitpid(pid, &pst, WNOHANG);
334 339 if (r != 0)
335 340 goto cleanup;
336 341 }
337 342
338 343 nanosleep(&sleepreq, NULL);
339 344 }
340 345
341 346 abortmsg("timed out waiting for cmdserver %s", opts->initsockname);
342 347 return NULL;
343 348
344 349 cleanup:
345 350 if (WIFEXITED(pst)) {
346 351 if (WEXITSTATUS(pst) == 0)
347 352 abortmsg("could not connect to cmdserver "
348 353 "(exited with status 0)");
349 354 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
350 355 exit(WEXITSTATUS(pst));
351 356 } else if (WIFSIGNALED(pst)) {
352 357 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
353 358 } else {
354 359 abortmsg("error while waiting for cmdserver");
355 360 }
356 361 return NULL;
357 362 }
358 363
359 364 /* Connect to a cmdserver. Will start a new server on demand. */
360 365 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
361 366 {
362 367 const char *sockname =
363 368 opts->redirectsockname[0] ? opts->redirectsockname : opts->sockname;
364 369 debugmsg("try connect to %s", sockname);
365 370 hgclient_t *hgc = hgc_open(sockname);
366 371 if (hgc)
367 372 return hgc;
368 373
369 374 /* prevent us from being connected to an outdated server: we were
370 375 * told by a server to redirect to opts->redirectsockname and that
371 376 * address does not work. we do not want to connect to the server
372 377 * again because it will probably tell us the same thing. */
373 378 if (sockname == opts->redirectsockname)
374 379 unlink(opts->sockname);
375 380
376 381 debugmsg("start cmdserver at %s", opts->initsockname);
377 382
383 /* Get the path to the hg executable before we fork because this
384 * function might update the environment, and we want this to be
385 * reflected in both the parent and child processes. */
386 const char *hgcmd = gethgcmd();
387
378 388 pid_t pid = fork();
379 389 if (pid < 0)
380 390 abortmsg("failed to fork cmdserver process");
381 391 if (pid == 0) {
382 execcmdserver(opts);
392 execcmdserver(hgcmd, opts);
383 393 } else {
384 394 hgc = retryconnectcmdserver(opts, pid);
385 395 }
386 396
387 397 return hgc;
388 398 }
389 399
390 400 static void killcmdserver(const struct cmdserveropts *opts)
391 401 {
392 402 /* resolve config hash */
393 403 char *resolvedpath = realpath(opts->sockname, NULL);
394 404 if (resolvedpath) {
395 405 unlink(resolvedpath);
396 406 free(resolvedpath);
397 407 }
398 408 }
399 409
400 410 /* Run instructions sent from the server like unlink and set redirect path
401 411 * Return 1 if reconnect is needed, otherwise 0 */
402 412 static int runinstructions(struct cmdserveropts *opts, const char **insts)
403 413 {
404 414 int needreconnect = 0;
405 415 if (!insts)
406 416 return needreconnect;
407 417
408 418 assert(insts);
409 419 opts->redirectsockname[0] = '\0';
410 420 const char **pinst;
411 421 for (pinst = insts; *pinst; pinst++) {
412 422 debugmsg("instruction: %s", *pinst);
413 423 if (strncmp(*pinst, "unlink ", 7) == 0) {
414 424 unlink(*pinst + 7);
415 425 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
416 426 int r = snprintf(opts->redirectsockname,
417 427 sizeof(opts->redirectsockname), "%s",
418 428 *pinst + 9);
419 429 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
420 430 abortmsg("redirect path is too long (%d)", r);
421 431 needreconnect = 1;
422 432 } else if (strncmp(*pinst, "exit ", 5) == 0) {
423 433 int n = 0;
424 434 if (sscanf(*pinst + 5, "%d", &n) != 1)
425 435 abortmsg("cannot read the exit code");
426 436 exit(n);
427 437 } else if (strcmp(*pinst, "reconnect") == 0) {
428 438 needreconnect = 1;
429 439 } else {
430 440 abortmsg("unknown instruction: %s", *pinst);
431 441 }
432 442 }
433 443 return needreconnect;
434 444 }
435 445
436 446 /*
437 447 * Test whether the command and the environment is unsupported or not.
438 448 *
439 449 * If any of the stdio file descriptors are not present (rare, but some tools
440 450 * might spawn new processes without stdio instead of redirecting them to the
441 451 * null device), then mark it as not supported because attachio won't work
442 452 * correctly.
443 453 *
444 454 * The command list is not designed to cover all cases. But it's fast, and does
445 455 * not depend on the server.
446 456 */
447 457 static int isunsupported(int argc, const char *argv[])
448 458 {
449 459 enum {
450 460 SERVE = 1,
451 461 DAEMON = 2,
452 462 SERVEDAEMON = SERVE | DAEMON,
453 463 };
454 464 unsigned int state = 0;
455 465 int i;
456 466 /* use fcntl to test missing stdio fds */
457 467 if (fcntl(STDIN_FILENO, F_GETFD) == -1 ||
458 468 fcntl(STDOUT_FILENO, F_GETFD) == -1 ||
459 469 fcntl(STDERR_FILENO, F_GETFD) == -1) {
460 470 debugmsg("stdio fds are missing");
461 471 return 1;
462 472 }
463 473 for (i = 0; i < argc; ++i) {
464 474 if (strcmp(argv[i], "--") == 0)
465 475 break;
466 476 /*
467 477 * there can be false positives but no false negative
468 478 * we cannot assume `serve` will always be first argument
469 479 * because global options can be passed before the command name
470 480 */
471 481 if (strcmp("serve", argv[i]) == 0)
472 482 state |= SERVE;
473 483 else if (strcmp("-d", argv[i]) == 0 ||
474 484 strcmp("--daemon", argv[i]) == 0)
475 485 state |= DAEMON;
476 486 }
477 487 return (state & SERVEDAEMON) == SERVEDAEMON;
478 488 }
479 489
480 490 static void execoriginalhg(const char *argv[])
481 491 {
482 492 debugmsg("execute original hg");
483 493 if (execvp(gethgcmd(), (char **)argv) < 0)
484 494 abortmsgerrno("failed to exec original hg");
485 495 }
486 496
487 int main(int argc, const char *argv[], const char *envp[])
497 int main(int argc, const char *argv[])
488 498 {
489 499 if (getenv("CHGDEBUG"))
490 500 enabledebugmsg();
491 501
492 502 if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
493 503 enablecolor();
494 504
495 505 if (getenv("CHGINTERNALMARK"))
496 506 abortmsg("chg started by chg detected.\n"
497 507 "Please make sure ${HG:-hg} is not a symlink or "
498 508 "wrapper to chg. Alternatively, set $CHGHG to the "
499 509 "path of real hg.");
500 510
501 511 if (isunsupported(argc - 1, argv + 1))
502 512 execoriginalhg(argv);
503 513
504 514 struct cmdserveropts opts;
505 515 initcmdserveropts(&opts);
506 516 setcmdserveropts(&opts);
507 517 setcmdserverargs(&opts, argc, argv);
508 518
509 519 if (argc == 2) {
510 520 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
511 521 killcmdserver(&opts);
512 522 return 0;
513 523 }
514 524 }
515 525
516 526 hgclient_t *hgc;
517 527 size_t retry = 0;
518 528 while (1) {
519 529 hgc = connectcmdserver(&opts);
520 530 if (!hgc)
521 531 abortmsg("cannot open hg client");
522 hgc_setenv(hgc, envp);
532 /* Use `environ(7)` instead of the optional `envp` argument to
533 * `main` because `envp` does not update when the environment
534 * changes, but `environ` does. */
535 hgc_setenv(hgc, (const char *const *)environ);
523 536 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
524 537 int needreconnect = runinstructions(&opts, insts);
525 538 free(insts);
526 539 if (!needreconnect)
527 540 break;
528 541 hgc_close(hgc);
529 542 if (++retry > 10)
530 543 abortmsg("too many redirections.\n"
531 544 "Please make sure %s is not a wrapper which "
532 545 "changes sensitive environment variables "
533 546 "before executing hg. If you have to use a "
534 547 "wrapper, wrap chg instead of hg.",
535 548 gethgcmd());
536 549 }
537 550
538 551 setupsignalhandler(hgc_peerpid(hgc), hgc_peerpgid(hgc));
539 552 atexit(waitpager);
540 553 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
541 554 restoresignalhandler();
542 555 hgc_close(hgc);
543 556 freecmdserveropts(&opts);
544 557
545 558 return exitcode;
546 559 }
General Comments 0
You need to be logged in to leave comments. Login now