1#include "cache.h"
2#include "run-command.h"
3#include "exec_cmd.h"
4#include "sigchain.h"
5#include "argv-array.h"
6
7#ifndef SHELL_PATH
8# define SHELL_PATH "/bin/sh"
9#endif
10
11struct child_to_clean {
12 pid_t pid;
13 struct child_to_clean *next;
14};
15static struct child_to_clean *children_to_clean;
16static int installed_child_cleanup_handler;
17
18static void cleanup_children(int sig)
19{
20 while (children_to_clean) {
21 struct child_to_clean *p = children_to_clean;
22 children_to_clean = p->next;
23 kill(p->pid, sig);
24 free(p);
25 }
26}
27
28static void cleanup_children_on_signal(int sig)
29{
30 cleanup_children(sig);
31 sigchain_pop(sig);
32 raise(sig);
33}
34
35static void cleanup_children_on_exit(void)
36{
37 cleanup_children(SIGTERM);
38}
39
40static void mark_child_for_cleanup(pid_t pid)
41{
42 struct child_to_clean *p = xmalloc(sizeof(*p));
43 p->pid = pid;
44 p->next = children_to_clean;
45 children_to_clean = p;
46
47 if (!installed_child_cleanup_handler) {
48 atexit(cleanup_children_on_exit);
49 sigchain_push_common(cleanup_children_on_signal);
50 installed_child_cleanup_handler = 1;
51 }
52}
53
54static void clear_child_for_cleanup(pid_t pid)
55{
56 struct child_to_clean **last, *p;
57
58 last = &children_to_clean;
59 for (p = children_to_clean; p; p = p->next) {
60 if (p->pid == pid) {
61 *last = p->next;
62 free(p);
63 return;
64 }
65 }
66}
67
68static inline void close_pair(int fd[2])
69{
70 close(fd[0]);
71 close(fd[1]);
72}
73
74#ifndef WIN32
75static inline void dup_devnull(int to)
76{
77 int fd = open("/dev/null", O_RDWR);
78 dup2(fd, to);
79 close(fd);
80}
81#endif
82
83static char *locate_in_PATH(const char *file)
84{
85 const char *p = getenv("PATH");
86 struct strbuf buf = STRBUF_INIT;
87
88 if (!p || !*p)
89 return NULL;
90
91 while (1) {
92 const char *end = strchrnul(p, ':');
93
94 strbuf_reset(&buf);
95
96 /* POSIX specifies an empty entry as the current directory. */
97 if (end != p) {
98 strbuf_add(&buf, p, end - p);
99 strbuf_addch(&buf, '/');
100 }
101 strbuf_addstr(&buf, file);
102
103 if (!access(buf.buf, F_OK))
104 return strbuf_detach(&buf, NULL);
105
106 if (!*end)
107 break;
108 p = end + 1;
109 }
110
111 strbuf_release(&buf);
112 return NULL;
113}
114
115static int exists_in_PATH(const char *file)
116{
117 char *r = locate_in_PATH(file);
118 free(r);
119 return r != NULL;
120}
121
122int sane_execvp(const char *file, char * const argv[])
123{
124 if (!execvp(file, argv))
125 return 0; /* cannot happen ;-) */
126
127 /*
128 * When a command can't be found because one of the directories
129 * listed in $PATH is unsearchable, execvp reports EACCES, but
130 * careful usability testing (read: analysis of occasional bug
131 * reports) reveals that "No such file or directory" is more
132 * intuitive.
133 *
134 * We avoid commands with "/", because execvp will not do $PATH
135 * lookups in that case.
136 *
137 * The reassignment of EACCES to errno looks like a no-op below,
138 * but we need to protect against exists_in_PATH overwriting errno.
139 */
140 if (errno == EACCES && !strchr(file, '/'))
141 errno = exists_in_PATH(file) ? EACCES : ENOENT;
142 else if (errno == ENOTDIR && !strchr(file, '/'))
143 errno = ENOENT;
144 return -1;
145}
146
147static const char **prepare_shell_cmd(const char **argv)
148{
149 int argc, nargc = 0;
150 const char **nargv;
151
152 for (argc = 0; argv[argc]; argc++)
153 ; /* just counting */
154 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
155 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
156
157 if (argc < 1)
158 die("BUG: shell command is empty");
159
160 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
161#ifndef WIN32
162 nargv[nargc++] = SHELL_PATH;
163#else
164 nargv[nargc++] = "sh";
165#endif
166 nargv[nargc++] = "-c";
167
168 if (argc < 2)
169 nargv[nargc++] = argv[0];
170 else {
171 struct strbuf arg0 = STRBUF_INIT;
172 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
173 nargv[nargc++] = strbuf_detach(&arg0, NULL);
174 }
175 }
176
177 for (argc = 0; argv[argc]; argc++)
178 nargv[nargc++] = argv[argc];
179 nargv[nargc] = NULL;
180
181 return nargv;
182}
183
184#ifndef WIN32
185static int execv_shell_cmd(const char **argv)
186{
187 const char **nargv = prepare_shell_cmd(argv);
188 trace_argv_printf(nargv, "trace: exec:");
189 sane_execvp(nargv[0], (char **)nargv);
190 free(nargv);
191 return -1;
192}
193#endif
194
195#ifndef WIN32
196static int child_err = 2;
197static int child_notifier = -1;
198
199static void notify_parent(void)
200{
201 /*
202 * execvp failed. If possible, we'd like to let start_command
203 * know, so failures like ENOENT can be handled right away; but
204 * otherwise, finish_command will still report the error.
205 */
206 xwrite(child_notifier, "", 1);
207}
208
209static NORETURN void die_child(const char *err, va_list params)
210{
211 vwritef(child_err, "fatal: ", err, params);
212 exit(128);
213}
214
215static void error_child(const char *err, va_list params)
216{
217 vwritef(child_err, "error: ", err, params);
218}
219#endif
220
221static inline void set_cloexec(int fd)
222{
223 int flags = fcntl(fd, F_GETFD);
224 if (flags >= 0)
225 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
226}
227
228static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
229{
230 int status, code = -1;
231 pid_t waiting;
232 int failed_errno = 0;
233
234 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
235 ; /* nothing */
236
237 if (waiting < 0) {
238 failed_errno = errno;
239 error("waitpid for %s failed: %s", argv0, strerror(errno));
240 } else if (waiting != pid) {
241 error("waitpid is confused (%s)", argv0);
242 } else if (WIFSIGNALED(status)) {
243 code = WTERMSIG(status);
244 error("%s died of signal %d", argv0, code);
245 /*
246 * This return value is chosen so that code & 0xff
247 * mimics the exit code that a POSIX shell would report for
248 * a program that died from this signal.
249 */
250 code -= 128;
251 } else if (WIFEXITED(status)) {
252 code = WEXITSTATUS(status);
253 /*
254 * Convert special exit code when execvp failed.
255 */
256 if (code == 127) {
257 code = -1;
258 failed_errno = ENOENT;
259 }
260 } else {
261 error("waitpid is confused (%s)", argv0);
262 }
263
264 clear_child_for_cleanup(pid);
265
266 errno = failed_errno;
267 return code;
268}
269
270int start_command(struct child_process *cmd)
271{
272 int need_in, need_out, need_err;
273 int fdin[2], fdout[2], fderr[2];
274 int failed_errno = failed_errno;
275
276 /*
277 * In case of errors we must keep the promise to close FDs
278 * that have been passed in via ->in and ->out.
279 */
280
281 need_in = !cmd->no_stdin && cmd->in < 0;
282 if (need_in) {
283 if (pipe(fdin) < 0) {
284 failed_errno = errno;
285 if (cmd->out > 0)
286 close(cmd->out);
287 goto fail_pipe;
288 }
289 cmd->in = fdin[1];
290 }
291
292 need_out = !cmd->no_stdout
293 && !cmd->stdout_to_stderr
294 && cmd->out < 0;
295 if (need_out) {
296 if (pipe(fdout) < 0) {
297 failed_errno = errno;
298 if (need_in)
299 close_pair(fdin);
300 else if (cmd->in)
301 close(cmd->in);
302 goto fail_pipe;
303 }
304 cmd->out = fdout[0];
305 }
306
307 need_err = !cmd->no_stderr && cmd->err < 0;
308 if (need_err) {
309 if (pipe(fderr) < 0) {
310 failed_errno = errno;
311 if (need_in)
312 close_pair(fdin);
313 else if (cmd->in)
314 close(cmd->in);
315 if (need_out)
316 close_pair(fdout);
317 else if (cmd->out)
318 close(cmd->out);
319fail_pipe:
320 error("cannot create pipe for %s: %s",
321 cmd->argv[0], strerror(failed_errno));
322 errno = failed_errno;
323 return -1;
324 }
325 cmd->err = fderr[0];
326 }
327
328 trace_argv_printf(cmd->argv, "trace: run_command:");
329 fflush(NULL);
330
331#ifndef WIN32
332{
333 int notify_pipe[2];
334 if (pipe(notify_pipe))
335 notify_pipe[0] = notify_pipe[1] = -1;
336
337 cmd->pid = fork();
338 if (!cmd->pid) {
339 /*
340 * Redirect the channel to write syscall error messages to
341 * before redirecting the process's stderr so that all die()
342 * in subsequent call paths use the parent's stderr.
343 */
344 if (cmd->no_stderr || need_err) {
345 child_err = dup(2);
346 set_cloexec(child_err);
347 }
348 set_die_routine(die_child);
349 set_error_routine(error_child);
350
351 close(notify_pipe[0]);
352 set_cloexec(notify_pipe[1]);
353 child_notifier = notify_pipe[1];
354 atexit(notify_parent);
355
356 if (cmd->no_stdin)
357 dup_devnull(0);
358 else if (need_in) {
359 dup2(fdin[0], 0);
360 close_pair(fdin);
361 } else if (cmd->in) {
362 dup2(cmd->in, 0);
363 close(cmd->in);
364 }
365
366 if (cmd->no_stderr)
367 dup_devnull(2);
368 else if (need_err) {
369 dup2(fderr[1], 2);
370 close_pair(fderr);
371 } else if (cmd->err > 1) {
372 dup2(cmd->err, 2);
373 close(cmd->err);
374 }
375
376 if (cmd->no_stdout)
377 dup_devnull(1);
378 else if (cmd->stdout_to_stderr)
379 dup2(2, 1);
380 else if (need_out) {
381 dup2(fdout[1], 1);
382 close_pair(fdout);
383 } else if (cmd->out > 1) {
384 dup2(cmd->out, 1);
385 close(cmd->out);
386 }
387
388 if (cmd->dir && chdir(cmd->dir))
389 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
390 cmd->dir);
391 if (cmd->env) {
392 for (; *cmd->env; cmd->env++) {
393 if (strchr(*cmd->env, '='))
394 putenv((char *)*cmd->env);
395 else
396 unsetenv(*cmd->env);
397 }
398 }
399 if (cmd->preexec_cb) {
400 /*
401 * We cannot predict what the pre-exec callback does.
402 * Forgo parent notification.
403 */
404 close(child_notifier);
405 child_notifier = -1;
406
407 cmd->preexec_cb();
408 }
409 if (cmd->git_cmd) {
410 execv_git_cmd(cmd->argv);
411 } else if (cmd->use_shell) {
412 execv_shell_cmd(cmd->argv);
413 } else {
414 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
415 }
416 if (errno == ENOENT) {
417 if (!cmd->silent_exec_failure)
418 error("cannot run %s: %s", cmd->argv[0],
419 strerror(ENOENT));
420 exit(127);
421 } else {
422 die_errno("cannot exec '%s'", cmd->argv[0]);
423 }
424 }
425 if (cmd->pid < 0)
426 error("cannot fork() for %s: %s", cmd->argv[0],
427 strerror(failed_errno = errno));
428 else if (cmd->clean_on_exit)
429 mark_child_for_cleanup(cmd->pid);
430
431 /*
432 * Wait for child's execvp. If the execvp succeeds (or if fork()
433 * failed), EOF is seen immediately by the parent. Otherwise, the
434 * child process sends a single byte.
435 * Note that use of this infrastructure is completely advisory,
436 * therefore, we keep error checks minimal.
437 */
438 close(notify_pipe[1]);
439 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
440 /*
441 * At this point we know that fork() succeeded, but execvp()
442 * failed. Errors have been reported to our stderr.
443 */
444 wait_or_whine(cmd->pid, cmd->argv[0],
445 cmd->silent_exec_failure);
446 failed_errno = errno;
447 cmd->pid = -1;
448 }
449 close(notify_pipe[0]);
450
451}
452#else
453{
454 int fhin = 0, fhout = 1, fherr = 2;
455 const char **sargv = cmd->argv;
456 char **env = environ;
457
458 if (cmd->no_stdin)
459 fhin = open("/dev/null", O_RDWR);
460 else if (need_in)
461 fhin = dup(fdin[0]);
462 else if (cmd->in)
463 fhin = dup(cmd->in);
464
465 if (cmd->no_stderr)
466 fherr = open("/dev/null", O_RDWR);
467 else if (need_err)
468 fherr = dup(fderr[1]);
469 else if (cmd->err > 2)
470 fherr = dup(cmd->err);
471
472 if (cmd->no_stdout)
473 fhout = open("/dev/null", O_RDWR);
474 else if (cmd->stdout_to_stderr)
475 fhout = dup(fherr);
476 else if (need_out)
477 fhout = dup(fdout[1]);
478 else if (cmd->out > 1)
479 fhout = dup(cmd->out);
480
481 if (cmd->env)
482 env = make_augmented_environ(cmd->env);
483
484 if (cmd->git_cmd) {
485 cmd->argv = prepare_git_cmd(cmd->argv);
486 } else if (cmd->use_shell) {
487 cmd->argv = prepare_shell_cmd(cmd->argv);
488 }
489
490 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
491 fhin, fhout, fherr);
492 failed_errno = errno;
493 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
494 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
495 if (cmd->clean_on_exit && cmd->pid >= 0)
496 mark_child_for_cleanup(cmd->pid);
497
498 if (cmd->env)
499 free_environ(env);
500 if (cmd->git_cmd)
501 free(cmd->argv);
502
503 cmd->argv = sargv;
504 if (fhin != 0)
505 close(fhin);
506 if (fhout != 1)
507 close(fhout);
508 if (fherr != 2)
509 close(fherr);
510}
511#endif
512
513 if (cmd->pid < 0) {
514 if (need_in)
515 close_pair(fdin);
516 else if (cmd->in)
517 close(cmd->in);
518 if (need_out)
519 close_pair(fdout);
520 else if (cmd->out)
521 close(cmd->out);
522 if (need_err)
523 close_pair(fderr);
524 else if (cmd->err)
525 close(cmd->err);
526 errno = failed_errno;
527 return -1;
528 }
529
530 if (need_in)
531 close(fdin[0]);
532 else if (cmd->in)
533 close(cmd->in);
534
535 if (need_out)
536 close(fdout[1]);
537 else if (cmd->out)
538 close(cmd->out);
539
540 if (need_err)
541 close(fderr[1]);
542 else if (cmd->err)
543 close(cmd->err);
544
545 return 0;
546}
547
548int finish_command(struct child_process *cmd)
549{
550 return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
551}
552
553int run_command(struct child_process *cmd)
554{
555 int code = start_command(cmd);
556 if (code)
557 return code;
558 return finish_command(cmd);
559}
560
561static void prepare_run_command_v_opt(struct child_process *cmd,
562 const char **argv,
563 int opt)
564{
565 memset(cmd, 0, sizeof(*cmd));
566 cmd->argv = argv;
567 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
568 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
569 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
570 cmd->silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
571 cmd->use_shell = opt & RUN_USING_SHELL ? 1 : 0;
572 cmd->clean_on_exit = opt & RUN_CLEAN_ON_EXIT ? 1 : 0;
573}
574
575int run_command_v_opt(const char **argv, int opt)
576{
577 struct child_process cmd;
578 prepare_run_command_v_opt(&cmd, argv, opt);
579 return run_command(&cmd);
580}
581
582int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
583{
584 struct child_process cmd;
585 prepare_run_command_v_opt(&cmd, argv, opt);
586 cmd.dir = dir;
587 cmd.env = env;
588 return run_command(&cmd);
589}
590
591#ifndef NO_PTHREADS
592static pthread_t main_thread;
593static int main_thread_set;
594static pthread_key_t async_key;
595
596static void *run_thread(void *data)
597{
598 struct async *async = data;
599 intptr_t ret;
600
601 pthread_setspecific(async_key, async);
602 ret = async->proc(async->proc_in, async->proc_out, async->data);
603 return (void *)ret;
604}
605
606static NORETURN void die_async(const char *err, va_list params)
607{
608 vreportf("fatal: ", err, params);
609
610 if (!pthread_equal(main_thread, pthread_self())) {
611 struct async *async = pthread_getspecific(async_key);
612 if (async->proc_in >= 0)
613 close(async->proc_in);
614 if (async->proc_out >= 0)
615 close(async->proc_out);
616 pthread_exit((void *)128);
617 }
618
619 exit(128);
620}
621#endif
622
623int start_async(struct async *async)
624{
625 int need_in, need_out;
626 int fdin[2], fdout[2];
627 int proc_in, proc_out;
628
629 need_in = async->in < 0;
630 if (need_in) {
631 if (pipe(fdin) < 0) {
632 if (async->out > 0)
633 close(async->out);
634 return error("cannot create pipe: %s", strerror(errno));
635 }
636 async->in = fdin[1];
637 }
638
639 need_out = async->out < 0;
640 if (need_out) {
641 if (pipe(fdout) < 0) {
642 if (need_in)
643 close_pair(fdin);
644 else if (async->in)
645 close(async->in);
646 return error("cannot create pipe: %s", strerror(errno));
647 }
648 async->out = fdout[0];
649 }
650
651 if (need_in)
652 proc_in = fdin[0];
653 else if (async->in)
654 proc_in = async->in;
655 else
656 proc_in = -1;
657
658 if (need_out)
659 proc_out = fdout[1];
660 else if (async->out)
661 proc_out = async->out;
662 else
663 proc_out = -1;
664
665#ifdef NO_PTHREADS
666 /* Flush stdio before fork() to avoid cloning buffers */
667 fflush(NULL);
668
669 async->pid = fork();
670 if (async->pid < 0) {
671 error("fork (async) failed: %s", strerror(errno));
672 goto error;
673 }
674 if (!async->pid) {
675 if (need_in)
676 close(fdin[1]);
677 if (need_out)
678 close(fdout[0]);
679 exit(!!async->proc(proc_in, proc_out, async->data));
680 }
681
682 mark_child_for_cleanup(async->pid);
683
684 if (need_in)
685 close(fdin[0]);
686 else if (async->in)
687 close(async->in);
688
689 if (need_out)
690 close(fdout[1]);
691 else if (async->out)
692 close(async->out);
693#else
694 if (!main_thread_set) {
695 /*
696 * We assume that the first time that start_async is called
697 * it is from the main thread.
698 */
699 main_thread_set = 1;
700 main_thread = pthread_self();
701 pthread_key_create(&async_key, NULL);
702 set_die_routine(die_async);
703 }
704
705 if (proc_in >= 0)
706 set_cloexec(proc_in);
707 if (proc_out >= 0)
708 set_cloexec(proc_out);
709 async->proc_in = proc_in;
710 async->proc_out = proc_out;
711 {
712 int err = pthread_create(&async->tid, NULL, run_thread, async);
713 if (err) {
714 error("cannot create thread: %s", strerror(err));
715 goto error;
716 }
717 }
718#endif
719 return 0;
720
721error:
722 if (need_in)
723 close_pair(fdin);
724 else if (async->in)
725 close(async->in);
726
727 if (need_out)
728 close_pair(fdout);
729 else if (async->out)
730 close(async->out);
731 return -1;
732}
733
734int finish_async(struct async *async)
735{
736#ifdef NO_PTHREADS
737 return wait_or_whine(async->pid, "child process", 0);
738#else
739 void *ret = (void *)(intptr_t)(-1);
740
741 if (pthread_join(async->tid, &ret))
742 error("pthread_join failed");
743 return (int)(intptr_t)ret;
744#endif
745}
746
747int run_hook(const char *index_file, const char *name, ...)
748{
749 struct child_process hook;
750 struct argv_array argv = ARGV_ARRAY_INIT;
751 const char *p, *env[2];
752 char index[PATH_MAX];
753 va_list args;
754 int ret;
755
756 if (access(git_path("hooks/%s", name), X_OK) < 0)
757 return 0;
758
759 va_start(args, name);
760 argv_array_push(&argv, git_path("hooks/%s", name));
761 while ((p = va_arg(args, const char *)))
762 argv_array_push(&argv, p);
763 va_end(args);
764
765 memset(&hook, 0, sizeof(hook));
766 hook.argv = argv.argv;
767 hook.no_stdin = 1;
768 hook.stdout_to_stderr = 1;
769 if (index_file) {
770 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
771 env[0] = index;
772 env[1] = NULL;
773 hook.env = env;
774 }
775
776 ret = run_command(&hook);
777 argv_array_clear(&argv);
778 return ret;
779}