##// END OF EJS Templates
chg: be stricter about checking invocation of `serve` command...
Pulkit Goyal -
r45107:1e459ac4 default
parent child Browse files
Show More
@@ -1,466 +1,470
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 187 static const char *gethgcmd(void)
188 188 {
189 189 static const char *hgcmd = NULL;
190 190 if (!hgcmd) {
191 191 hgcmd = getenv("CHGHG");
192 192 if (!hgcmd || hgcmd[0] == '\0')
193 193 hgcmd = getenv("HG");
194 194 if (!hgcmd || hgcmd[0] == '\0')
195 195 #ifdef HGPATH
196 196 hgcmd = (HGPATH);
197 197 #else
198 198 hgcmd = "hg";
199 199 #endif
200 200 }
201 201 return hgcmd;
202 202 }
203 203
204 204 static void execcmdserver(const struct cmdserveropts *opts)
205 205 {
206 206 const char *hgcmd = gethgcmd();
207 207
208 208 const char *baseargv[] = {
209 209 hgcmd,
210 210 "serve",
211 211 "--cmdserver",
212 212 "chgunix",
213 213 "--address",
214 214 opts->initsockname,
215 215 "--daemon-postexec",
216 216 "chdir:/",
217 217 };
218 218 size_t baseargvsize = sizeof(baseargv) / sizeof(baseargv[0]);
219 219 size_t argsize = baseargvsize + opts->argsize + 1;
220 220
221 221 const char **argv = mallocx(sizeof(char *) * argsize);
222 222 memcpy(argv, baseargv, sizeof(baseargv));
223 223 if (opts->args) {
224 224 size_t size = sizeof(char *) * opts->argsize;
225 225 memcpy(argv + baseargvsize, opts->args, size);
226 226 }
227 227 argv[argsize - 1] = NULL;
228 228
229 229 const char *lc_ctype_env = getenv("LC_CTYPE");
230 230 if (lc_ctype_env == NULL) {
231 231 if (putenv("CHG_CLEAR_LC_CTYPE=") != 0)
232 232 abortmsgerrno("failed to putenv CHG_CLEAR_LC_CTYPE");
233 233 } else {
234 234 if (setenv("CHGORIG_LC_CTYPE", lc_ctype_env, 1) != 0) {
235 235 abortmsgerrno("failed to setenv CHGORIG_LC_CTYYPE");
236 236 }
237 237 }
238 238
239 239 if (putenv("CHGINTERNALMARK=") != 0)
240 240 abortmsgerrno("failed to putenv");
241 241 if (execvp(hgcmd, (char **)argv) < 0)
242 242 abortmsgerrno("failed to exec cmdserver");
243 243 free(argv);
244 244 }
245 245
246 246 /* Retry until we can connect to the server. Give up after some time. */
247 247 static hgclient_t *retryconnectcmdserver(struct cmdserveropts *opts, pid_t pid)
248 248 {
249 249 static const struct timespec sleepreq = {0, 10 * 1000000};
250 250 int pst = 0;
251 251
252 252 debugmsg("try connect to %s repeatedly", opts->initsockname);
253 253
254 254 unsigned int timeoutsec = 60; /* default: 60 seconds */
255 255 const char *timeoutenv = getenv("CHGTIMEOUT");
256 256 if (timeoutenv)
257 257 sscanf(timeoutenv, "%u", &timeoutsec);
258 258
259 259 for (unsigned int i = 0; !timeoutsec || i < timeoutsec * 100; i++) {
260 260 hgclient_t *hgc = hgc_open(opts->initsockname);
261 261 if (hgc) {
262 262 debugmsg("rename %s to %s", opts->initsockname,
263 263 opts->sockname);
264 264 int r = rename(opts->initsockname, opts->sockname);
265 265 if (r != 0)
266 266 abortmsgerrno("cannot rename");
267 267 return hgc;
268 268 }
269 269
270 270 if (pid > 0) {
271 271 /* collect zombie if child process fails to start */
272 272 int r = waitpid(pid, &pst, WNOHANG);
273 273 if (r != 0)
274 274 goto cleanup;
275 275 }
276 276
277 277 nanosleep(&sleepreq, NULL);
278 278 }
279 279
280 280 abortmsg("timed out waiting for cmdserver %s", opts->initsockname);
281 281 return NULL;
282 282
283 283 cleanup:
284 284 if (WIFEXITED(pst)) {
285 285 if (WEXITSTATUS(pst) == 0)
286 286 abortmsg("could not connect to cmdserver "
287 287 "(exited with status 0)");
288 288 debugmsg("cmdserver exited with status %d", WEXITSTATUS(pst));
289 289 exit(WEXITSTATUS(pst));
290 290 } else if (WIFSIGNALED(pst)) {
291 291 abortmsg("cmdserver killed by signal %d", WTERMSIG(pst));
292 292 } else {
293 293 abortmsg("error while waiting for cmdserver");
294 294 }
295 295 return NULL;
296 296 }
297 297
298 298 /* Connect to a cmdserver. Will start a new server on demand. */
299 299 static hgclient_t *connectcmdserver(struct cmdserveropts *opts)
300 300 {
301 301 const char *sockname =
302 302 opts->redirectsockname[0] ? opts->redirectsockname : opts->sockname;
303 303 debugmsg("try connect to %s", sockname);
304 304 hgclient_t *hgc = hgc_open(sockname);
305 305 if (hgc)
306 306 return hgc;
307 307
308 308 /* prevent us from being connected to an outdated server: we were
309 309 * told by a server to redirect to opts->redirectsockname and that
310 310 * address does not work. we do not want to connect to the server
311 311 * again because it will probably tell us the same thing. */
312 312 if (sockname == opts->redirectsockname)
313 313 unlink(opts->sockname);
314 314
315 315 debugmsg("start cmdserver at %s", opts->initsockname);
316 316
317 317 pid_t pid = fork();
318 318 if (pid < 0)
319 319 abortmsg("failed to fork cmdserver process");
320 320 if (pid == 0) {
321 321 execcmdserver(opts);
322 322 } else {
323 323 hgc = retryconnectcmdserver(opts, pid);
324 324 }
325 325
326 326 return hgc;
327 327 }
328 328
329 329 static void killcmdserver(const struct cmdserveropts *opts)
330 330 {
331 331 /* resolve config hash */
332 332 char *resolvedpath = realpath(opts->sockname, NULL);
333 333 if (resolvedpath) {
334 334 unlink(resolvedpath);
335 335 free(resolvedpath);
336 336 }
337 337 }
338 338
339 339 /* Run instructions sent from the server like unlink and set redirect path
340 340 * Return 1 if reconnect is needed, otherwise 0 */
341 341 static int runinstructions(struct cmdserveropts *opts, const char **insts)
342 342 {
343 343 int needreconnect = 0;
344 344 if (!insts)
345 345 return needreconnect;
346 346
347 347 assert(insts);
348 348 opts->redirectsockname[0] = '\0';
349 349 const char **pinst;
350 350 for (pinst = insts; *pinst; pinst++) {
351 351 debugmsg("instruction: %s", *pinst);
352 352 if (strncmp(*pinst, "unlink ", 7) == 0) {
353 353 unlink(*pinst + 7);
354 354 } else if (strncmp(*pinst, "redirect ", 9) == 0) {
355 355 int r = snprintf(opts->redirectsockname,
356 356 sizeof(opts->redirectsockname), "%s",
357 357 *pinst + 9);
358 358 if (r < 0 || r >= (int)sizeof(opts->redirectsockname))
359 359 abortmsg("redirect path is too long (%d)", r);
360 360 needreconnect = 1;
361 361 } else if (strncmp(*pinst, "exit ", 5) == 0) {
362 362 int n = 0;
363 363 if (sscanf(*pinst + 5, "%d", &n) != 1)
364 364 abortmsg("cannot read the exit code");
365 365 exit(n);
366 366 } else if (strcmp(*pinst, "reconnect") == 0) {
367 367 needreconnect = 1;
368 368 } else {
369 369 abortmsg("unknown instruction: %s", *pinst);
370 370 }
371 371 }
372 372 return needreconnect;
373 373 }
374 374
375 375 /*
376 376 * Test whether the command is unsupported or not. This is not designed to
377 * cover all cases. But it's fast, does not depend on the server and does
378 * not return false positives.
377 * cover all cases. But it's fast, does not depend on the server.
379 378 */
380 379 static int isunsupported(int argc, const char *argv[])
381 380 {
382 381 enum { SERVE = 1,
383 382 DAEMON = 2,
384 383 SERVEDAEMON = SERVE | DAEMON,
385 384 };
386 385 unsigned int state = 0;
387 386 int i;
388 387 for (i = 0; i < argc; ++i) {
389 388 if (strcmp(argv[i], "--") == 0)
390 389 break;
391 if (i == 0 && strcmp("serve", argv[i]) == 0)
390 /*
391 * there can be false positives but no false negative
392 * we cannot assume `serve` will always be first argument
393 * because global options can be passed before the command name
394 */
395 if (strcmp("serve", argv[i]) == 0)
392 396 state |= SERVE;
393 397 else if (strcmp("-d", argv[i]) == 0 ||
394 398 strcmp("--daemon", argv[i]) == 0)
395 399 state |= DAEMON;
396 400 }
397 401 return (state & SERVEDAEMON) == SERVEDAEMON;
398 402 }
399 403
400 404 static void execoriginalhg(const char *argv[])
401 405 {
402 406 debugmsg("execute original hg");
403 407 if (execvp(gethgcmd(), (char **)argv) < 0)
404 408 abortmsgerrno("failed to exec original hg");
405 409 }
406 410
407 411 int main(int argc, const char *argv[], const char *envp[])
408 412 {
409 413 if (getenv("CHGDEBUG"))
410 414 enabledebugmsg();
411 415
412 416 if (!getenv("HGPLAIN") && isatty(fileno(stderr)))
413 417 enablecolor();
414 418
415 419 if (getenv("CHGINTERNALMARK"))
416 420 abortmsg("chg started by chg detected.\n"
417 421 "Please make sure ${HG:-hg} is not a symlink or "
418 422 "wrapper to chg. Alternatively, set $CHGHG to the "
419 423 "path of real hg.");
420 424
421 425 if (isunsupported(argc - 1, argv + 1))
422 426 execoriginalhg(argv);
423 427
424 428 struct cmdserveropts opts;
425 429 initcmdserveropts(&opts);
426 430 setcmdserveropts(&opts);
427 431 setcmdserverargs(&opts, argc, argv);
428 432
429 433 if (argc == 2) {
430 434 if (strcmp(argv[1], "--kill-chg-daemon") == 0) {
431 435 killcmdserver(&opts);
432 436 return 0;
433 437 }
434 438 }
435 439
436 440 hgclient_t *hgc;
437 441 size_t retry = 0;
438 442 while (1) {
439 443 hgc = connectcmdserver(&opts);
440 444 if (!hgc)
441 445 abortmsg("cannot open hg client");
442 446 hgc_setenv(hgc, envp);
443 447 const char **insts = hgc_validate(hgc, argv + 1, argc - 1);
444 448 int needreconnect = runinstructions(&opts, insts);
445 449 free(insts);
446 450 if (!needreconnect)
447 451 break;
448 452 hgc_close(hgc);
449 453 if (++retry > 10)
450 454 abortmsg("too many redirections.\n"
451 455 "Please make sure %s is not a wrapper which "
452 456 "changes sensitive environment variables "
453 457 "before executing hg. If you have to use a "
454 458 "wrapper, wrap chg instead of hg.",
455 459 gethgcmd());
456 460 }
457 461
458 462 setupsignalhandler(hgc_peerpid(hgc), hgc_peerpgid(hgc));
459 463 atexit(waitpager);
460 464 int exitcode = hgc_runcommand(hgc, argv + 1, argc - 1);
461 465 restoresignalhandler();
462 466 hgc_close(hgc);
463 467 freecmdserveropts(&opts);
464 468
465 469 return exitcode;
466 470 }
General Comments 0
You need to be logged in to leave comments. Login now