tests: fix overeager scrubbing of environment variables
[alt-git.git] / run-command.c
blob8619c769a93c48e724957c019af5765ebee6af9f
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec_cmd.h"
5 static inline void close_pair(int fd[2])
7 close(fd[0]);
8 close(fd[1]);
11 #ifndef WIN32
12 static inline void dup_devnull(int to)
14 int fd = open("/dev/null", O_RDWR);
15 dup2(fd, to);
16 close(fd);
18 #endif
20 static const char **prepare_shell_cmd(const char **argv)
22 int argc, nargc = 0;
23 const char **nargv;
25 for (argc = 0; argv[argc]; argc++)
26 ; /* just counting */
27 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
28 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
30 if (argc < 1)
31 die("BUG: shell command is empty");
33 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
34 nargv[nargc++] = "sh";
35 nargv[nargc++] = "-c";
37 if (argc < 2)
38 nargv[nargc++] = argv[0];
39 else {
40 struct strbuf arg0 = STRBUF_INIT;
41 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
42 nargv[nargc++] = strbuf_detach(&arg0, NULL);
46 for (argc = 0; argv[argc]; argc++)
47 nargv[nargc++] = argv[argc];
48 nargv[nargc] = NULL;
50 return nargv;
53 #ifndef WIN32
54 static int execv_shell_cmd(const char **argv)
56 const char **nargv = prepare_shell_cmd(argv);
57 trace_argv_printf(nargv, "trace: exec:");
58 execvp(nargv[0], (char **)nargv);
59 free(nargv);
60 return -1;
62 #endif
64 #ifndef WIN32
65 static int child_err = 2;
66 static int child_notifier = -1;
68 static void notify_parent(void)
71 * execvp failed. If possible, we'd like to let start_command
72 * know, so failures like ENOENT can be handled right away; but
73 * otherwise, finish_command will still report the error.
75 if (write(child_notifier, "", 1))
76 ; /* yes, dear gcc -D_FORTIFY_SOURCE, there was an error. */
79 static NORETURN void die_child(const char *err, va_list params)
81 char msg[4096];
82 int len = vsnprintf(msg, sizeof(msg), err, params);
83 if (len > sizeof(msg))
84 len = sizeof(msg);
86 if (write(child_err, "fatal: ", 7) ||
87 write(child_err, msg, len) ||
88 write(child_err, "\n", 1))
89 ; /* yes, gcc -D_FORTIFY_SOURCE, we know there was an error. */
90 exit(128);
92 #endif
94 static inline void set_cloexec(int fd)
96 int flags = fcntl(fd, F_GETFD);
97 if (flags >= 0)
98 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
101 static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
103 int status, code = -1;
104 pid_t waiting;
105 int failed_errno = 0;
107 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
108 ; /* nothing */
110 if (waiting < 0) {
111 failed_errno = errno;
112 error("waitpid for %s failed: %s", argv0, strerror(errno));
113 } else if (waiting != pid) {
114 error("waitpid is confused (%s)", argv0);
115 } else if (WIFSIGNALED(status)) {
116 code = WTERMSIG(status);
117 error("%s died of signal %d", argv0, code);
119 * This return value is chosen so that code & 0xff
120 * mimics the exit code that a POSIX shell would report for
121 * a program that died from this signal.
123 code -= 128;
124 } else if (WIFEXITED(status)) {
125 code = WEXITSTATUS(status);
127 * Convert special exit code when execvp failed.
129 if (code == 127) {
130 code = -1;
131 failed_errno = ENOENT;
132 if (!silent_exec_failure)
133 error("cannot run %s: %s", argv0,
134 strerror(ENOENT));
136 } else {
137 error("waitpid is confused (%s)", argv0);
139 errno = failed_errno;
140 return code;
143 int start_command(struct child_process *cmd)
145 int need_in, need_out, need_err;
146 int fdin[2], fdout[2], fderr[2];
147 int failed_errno = failed_errno;
150 * In case of errors we must keep the promise to close FDs
151 * that have been passed in via ->in and ->out.
154 need_in = !cmd->no_stdin && cmd->in < 0;
155 if (need_in) {
156 if (pipe(fdin) < 0) {
157 failed_errno = errno;
158 if (cmd->out > 0)
159 close(cmd->out);
160 goto fail_pipe;
162 cmd->in = fdin[1];
165 need_out = !cmd->no_stdout
166 && !cmd->stdout_to_stderr
167 && cmd->out < 0;
168 if (need_out) {
169 if (pipe(fdout) < 0) {
170 failed_errno = errno;
171 if (need_in)
172 close_pair(fdin);
173 else if (cmd->in)
174 close(cmd->in);
175 goto fail_pipe;
177 cmd->out = fdout[0];
180 need_err = !cmd->no_stderr && cmd->err < 0;
181 if (need_err) {
182 if (pipe(fderr) < 0) {
183 failed_errno = errno;
184 if (need_in)
185 close_pair(fdin);
186 else if (cmd->in)
187 close(cmd->in);
188 if (need_out)
189 close_pair(fdout);
190 else if (cmd->out)
191 close(cmd->out);
192 fail_pipe:
193 error("cannot create pipe for %s: %s",
194 cmd->argv[0], strerror(failed_errno));
195 errno = failed_errno;
196 return -1;
198 cmd->err = fderr[0];
201 trace_argv_printf(cmd->argv, "trace: run_command:");
202 fflush(NULL);
204 #ifndef WIN32
206 int notify_pipe[2];
207 if (pipe(notify_pipe))
208 notify_pipe[0] = notify_pipe[1] = -1;
210 cmd->pid = fork();
211 if (!cmd->pid) {
213 * Redirect the channel to write syscall error messages to
214 * before redirecting the process's stderr so that all die()
215 * in subsequent call paths use the parent's stderr.
217 if (cmd->no_stderr || need_err) {
218 child_err = dup(2);
219 set_cloexec(child_err);
221 set_die_routine(die_child);
223 close(notify_pipe[0]);
224 set_cloexec(notify_pipe[1]);
225 child_notifier = notify_pipe[1];
226 atexit(notify_parent);
228 if (cmd->no_stdin)
229 dup_devnull(0);
230 else if (need_in) {
231 dup2(fdin[0], 0);
232 close_pair(fdin);
233 } else if (cmd->in) {
234 dup2(cmd->in, 0);
235 close(cmd->in);
238 if (cmd->no_stderr)
239 dup_devnull(2);
240 else if (need_err) {
241 dup2(fderr[1], 2);
242 close_pair(fderr);
243 } else if (cmd->err > 1) {
244 dup2(cmd->err, 2);
245 close(cmd->err);
248 if (cmd->no_stdout)
249 dup_devnull(1);
250 else if (cmd->stdout_to_stderr)
251 dup2(2, 1);
252 else if (need_out) {
253 dup2(fdout[1], 1);
254 close_pair(fdout);
255 } else if (cmd->out > 1) {
256 dup2(cmd->out, 1);
257 close(cmd->out);
260 if (cmd->dir && chdir(cmd->dir))
261 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
262 cmd->dir);
263 if (cmd->env) {
264 for (; *cmd->env; cmd->env++) {
265 if (strchr(*cmd->env, '='))
266 putenv((char *)*cmd->env);
267 else
268 unsetenv(*cmd->env);
271 if (cmd->preexec_cb) {
273 * We cannot predict what the pre-exec callback does.
274 * Forgo parent notification.
276 close(child_notifier);
277 child_notifier = -1;
279 cmd->preexec_cb();
281 if (cmd->git_cmd) {
282 execv_git_cmd(cmd->argv);
283 } else if (cmd->use_shell) {
284 execv_shell_cmd(cmd->argv);
285 } else {
286 execvp(cmd->argv[0], (char *const*) cmd->argv);
289 * Do not check for cmd->silent_exec_failure; the parent
290 * process will check it when it sees this exit code.
292 if (errno == ENOENT)
293 exit(127);
294 else
295 die_errno("cannot exec '%s'", cmd->argv[0]);
297 if (cmd->pid < 0)
298 error("cannot fork() for %s: %s", cmd->argv[0],
299 strerror(failed_errno = errno));
302 * Wait for child's execvp. If the execvp succeeds (or if fork()
303 * failed), EOF is seen immediately by the parent. Otherwise, the
304 * child process sends a single byte.
305 * Note that use of this infrastructure is completely advisory,
306 * therefore, we keep error checks minimal.
308 close(notify_pipe[1]);
309 if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
311 * At this point we know that fork() succeeded, but execvp()
312 * failed. Errors have been reported to our stderr.
314 wait_or_whine(cmd->pid, cmd->argv[0],
315 cmd->silent_exec_failure);
316 failed_errno = errno;
317 cmd->pid = -1;
319 close(notify_pipe[0]);
321 #else
323 int fhin = 0, fhout = 1, fherr = 2;
324 const char **sargv = cmd->argv;
325 char **env = environ;
327 if (cmd->no_stdin)
328 fhin = open("/dev/null", O_RDWR);
329 else if (need_in)
330 fhin = dup(fdin[0]);
331 else if (cmd->in)
332 fhin = dup(cmd->in);
334 if (cmd->no_stderr)
335 fherr = open("/dev/null", O_RDWR);
336 else if (need_err)
337 fherr = dup(fderr[1]);
338 else if (cmd->err > 2)
339 fherr = dup(cmd->err);
341 if (cmd->no_stdout)
342 fhout = open("/dev/null", O_RDWR);
343 else if (cmd->stdout_to_stderr)
344 fhout = dup(fherr);
345 else if (need_out)
346 fhout = dup(fdout[1]);
347 else if (cmd->out > 1)
348 fhout = dup(cmd->out);
350 if (cmd->env)
351 env = make_augmented_environ(cmd->env);
353 if (cmd->git_cmd) {
354 cmd->argv = prepare_git_cmd(cmd->argv);
355 } else if (cmd->use_shell) {
356 cmd->argv = prepare_shell_cmd(cmd->argv);
359 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
360 fhin, fhout, fherr);
361 failed_errno = errno;
362 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
363 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
365 if (cmd->env)
366 free_environ(env);
367 if (cmd->git_cmd)
368 free(cmd->argv);
370 cmd->argv = sargv;
371 if (fhin != 0)
372 close(fhin);
373 if (fhout != 1)
374 close(fhout);
375 if (fherr != 2)
376 close(fherr);
378 #endif
380 if (cmd->pid < 0) {
381 if (need_in)
382 close_pair(fdin);
383 else if (cmd->in)
384 close(cmd->in);
385 if (need_out)
386 close_pair(fdout);
387 else if (cmd->out)
388 close(cmd->out);
389 if (need_err)
390 close_pair(fderr);
391 else if (cmd->err)
392 close(cmd->err);
393 errno = failed_errno;
394 return -1;
397 if (need_in)
398 close(fdin[0]);
399 else if (cmd->in)
400 close(cmd->in);
402 if (need_out)
403 close(fdout[1]);
404 else if (cmd->out)
405 close(cmd->out);
407 if (need_err)
408 close(fderr[1]);
409 else if (cmd->err)
410 close(cmd->err);
412 return 0;
415 int finish_command(struct child_process *cmd)
417 return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
420 int run_command(struct child_process *cmd)
422 int code = start_command(cmd);
423 if (code)
424 return code;
425 return finish_command(cmd);
428 static void prepare_run_command_v_opt(struct child_process *cmd,
429 const char **argv,
430 int opt)
432 memset(cmd, 0, sizeof(*cmd));
433 cmd->argv = argv;
434 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
435 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
436 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
437 cmd->silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
438 cmd->use_shell = opt & RUN_USING_SHELL ? 1 : 0;
441 int run_command_v_opt(const char **argv, int opt)
443 struct child_process cmd;
444 prepare_run_command_v_opt(&cmd, argv, opt);
445 return run_command(&cmd);
448 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
450 struct child_process cmd;
451 prepare_run_command_v_opt(&cmd, argv, opt);
452 cmd.dir = dir;
453 cmd.env = env;
454 return run_command(&cmd);
457 #ifndef NO_PTHREADS
458 static pthread_t main_thread;
459 static int main_thread_set;
460 static pthread_key_t async_key;
462 static void *run_thread(void *data)
464 struct async *async = data;
465 intptr_t ret;
467 pthread_setspecific(async_key, async);
468 ret = async->proc(async->proc_in, async->proc_out, async->data);
469 return (void *)ret;
472 static NORETURN void die_async(const char *err, va_list params)
474 vreportf("fatal: ", err, params);
476 if (!pthread_equal(main_thread, pthread_self())) {
477 struct async *async = pthread_getspecific(async_key);
478 if (async->proc_in >= 0)
479 close(async->proc_in);
480 if (async->proc_out >= 0)
481 close(async->proc_out);
482 pthread_exit((void *)128);
485 exit(128);
487 #endif
489 int start_async(struct async *async)
491 int need_in, need_out;
492 int fdin[2], fdout[2];
493 int proc_in, proc_out;
495 need_in = async->in < 0;
496 if (need_in) {
497 if (pipe(fdin) < 0) {
498 if (async->out > 0)
499 close(async->out);
500 return error("cannot create pipe: %s", strerror(errno));
502 async->in = fdin[1];
505 need_out = async->out < 0;
506 if (need_out) {
507 if (pipe(fdout) < 0) {
508 if (need_in)
509 close_pair(fdin);
510 else if (async->in)
511 close(async->in);
512 return error("cannot create pipe: %s", strerror(errno));
514 async->out = fdout[0];
517 if (need_in)
518 proc_in = fdin[0];
519 else if (async->in)
520 proc_in = async->in;
521 else
522 proc_in = -1;
524 if (need_out)
525 proc_out = fdout[1];
526 else if (async->out)
527 proc_out = async->out;
528 else
529 proc_out = -1;
531 #ifdef NO_PTHREADS
532 /* Flush stdio before fork() to avoid cloning buffers */
533 fflush(NULL);
535 async->pid = fork();
536 if (async->pid < 0) {
537 error("fork (async) failed: %s", strerror(errno));
538 goto error;
540 if (!async->pid) {
541 if (need_in)
542 close(fdin[1]);
543 if (need_out)
544 close(fdout[0]);
545 exit(!!async->proc(proc_in, proc_out, async->data));
548 if (need_in)
549 close(fdin[0]);
550 else if (async->in)
551 close(async->in);
553 if (need_out)
554 close(fdout[1]);
555 else if (async->out)
556 close(async->out);
557 #else
558 if (!main_thread_set) {
560 * We assume that the first time that start_async is called
561 * it is from the main thread.
563 main_thread_set = 1;
564 main_thread = pthread_self();
565 pthread_key_create(&async_key, NULL);
566 set_die_routine(die_async);
569 if (proc_in >= 0)
570 set_cloexec(proc_in);
571 if (proc_out >= 0)
572 set_cloexec(proc_out);
573 async->proc_in = proc_in;
574 async->proc_out = proc_out;
576 int err = pthread_create(&async->tid, NULL, run_thread, async);
577 if (err) {
578 error("cannot create thread: %s", strerror(err));
579 goto error;
582 #endif
583 return 0;
585 error:
586 if (need_in)
587 close_pair(fdin);
588 else if (async->in)
589 close(async->in);
591 if (need_out)
592 close_pair(fdout);
593 else if (async->out)
594 close(async->out);
595 return -1;
598 int finish_async(struct async *async)
600 #ifdef NO_PTHREADS
601 return wait_or_whine(async->pid, "child process", 0);
602 #else
603 void *ret = (void *)(intptr_t)(-1);
605 if (pthread_join(async->tid, &ret))
606 error("pthread_join failed");
607 return (int)(intptr_t)ret;
608 #endif
611 int run_hook(const char *index_file, const char *name, ...)
613 struct child_process hook;
614 const char **argv = NULL, *env[2];
615 char index[PATH_MAX];
616 va_list args;
617 int ret;
618 size_t i = 0, alloc = 0;
620 if (access(git_path("hooks/%s", name), X_OK) < 0)
621 return 0;
623 va_start(args, name);
624 ALLOC_GROW(argv, i + 1, alloc);
625 argv[i++] = git_path("hooks/%s", name);
626 while (argv[i-1]) {
627 ALLOC_GROW(argv, i + 1, alloc);
628 argv[i++] = va_arg(args, const char *);
630 va_end(args);
632 memset(&hook, 0, sizeof(hook));
633 hook.argv = argv;
634 hook.no_stdin = 1;
635 hook.stdout_to_stderr = 1;
636 if (index_file) {
637 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
638 env[0] = index;
639 env[1] = NULL;
640 hook.env = env;
643 ret = run_command(&hook);
644 free(argv);
645 return ret;