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