Debian Codegraph @

contrib/chg/chg.c

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