sane_execvp(): ignore non-directory on $PATH
[alt-git.git] / run-command.c
blobf9b7db23857a31ee037b0f900d0a5f2397c3d538
1 #include "cache.h"
2 #include "run-command.h"
3 #include "exec_cmd.h"
4 #include "argv-array.h"
6 static inline void close_pair(int fd[2])
8 close(fd[0]);
9 close(fd[1]);
12 #ifndef WIN32
13 static inline void dup_devnull(int to)
15 int fd = open("/dev/null", O_RDWR);
16 dup2(fd, to);
17 close(fd);
19 #endif
21 static char *locate_in_PATH(const char *file)
23 const char *p = getenv("PATH");
24 struct strbuf buf = STRBUF_INIT;
26 if (!p || !*p)
27 return NULL;
29 while (1) {
30 const char *end = strchrnul(p, ':');
32 strbuf_reset(&buf);
34 /* POSIX specifies an empty entry as the current directory. */
35 if (end != p) {
36 strbuf_add(&buf, p, end - p);
37 strbuf_addch(&buf, '/');
39 strbuf_addstr(&buf, file);
41 if (!access(buf.buf, F_OK))
42 return strbuf_detach(&buf, NULL);
44 if (!*end)
45 break;
46 p = end + 1;
49 strbuf_release(&buf);
50 return NULL;
53 static int exists_in_PATH(const char *file)
55 char *r = locate_in_PATH(file);
56 free(r);
57 return r != NULL;
60 int sane_execvp(const char *file, char * const argv[])
62 if (!execvp(file, argv))
63 return 0; /* cannot happen ;-) */
66 * When a command can't be found because one of the directories
67 * listed in $PATH is unsearchable, execvp reports EACCES, but
68 * careful usability testing (read: analysis of occasional bug
69 * reports) reveals that "No such file or directory" is more
70 * intuitive.
72 * We avoid commands with "/", because execvp will not do $PATH
73 * lookups in that case.
75 * The reassignment of EACCES to errno looks like a no-op below,
76 * but we need to protect against exists_in_PATH overwriting errno.
78 if (errno == EACCES && !strchr(file, '/'))
79 errno = exists_in_PATH(file) ? EACCES : ENOENT;
80 else if (errno == ENOTDIR && !strchr(file, '/'))
81 errno = ENOENT;
82 return -1;
85 static const char **prepare_shell_cmd(const char **argv)
87 int argc, nargc = 0;
88 const char **nargv;
90 for (argc = 0; argv[argc]; argc++)
91 ; /* just counting */
92 /* +1 for NULL, +3 for "sh -c" plus extra $0 */
93 nargv = xmalloc(sizeof(*nargv) * (argc + 1 + 3));
95 if (argc < 1)
96 die("BUG: shell command is empty");
98 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
99 nargv[nargc++] = "sh";
100 nargv[nargc++] = "-c";
102 if (argc < 2)
103 nargv[nargc++] = argv[0];
104 else {
105 struct strbuf arg0 = STRBUF_INIT;
106 strbuf_addf(&arg0, "%s \"$@\"", argv[0]);
107 nargv[nargc++] = strbuf_detach(&arg0, NULL);
111 for (argc = 0; argv[argc]; argc++)
112 nargv[nargc++] = argv[argc];
113 nargv[nargc] = NULL;
115 return nargv;
118 #ifndef WIN32
119 static int execv_shell_cmd(const char **argv)
121 const char **nargv = prepare_shell_cmd(argv);
122 trace_argv_printf(nargv, "trace: exec:");
123 sane_execvp(nargv[0], (char **)nargv);
124 free(nargv);
125 return -1;
127 #endif
129 #ifndef WIN32
130 static int child_err = 2;
131 static int child_notifier = -1;
133 static void notify_parent(void)
136 * execvp failed. If possible, we'd like to let start_command
137 * know, so failures like ENOENT can be handled right away; but
138 * otherwise, finish_command will still report the error.
140 xwrite(child_notifier, "", 1);
143 static NORETURN void die_child(const char *err, va_list params)
145 vwritef(child_err, "fatal: ", err, params);
146 exit(128);
149 static void error_child(const char *err, va_list params)
151 vwritef(child_err, "error: ", err, params);
153 #endif
155 static inline void set_cloexec(int fd)
157 int flags = fcntl(fd, F_GETFD);
158 if (flags >= 0)
159 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
162 static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
164 int status, code = -1;
165 pid_t waiting;
166 int failed_errno = 0;
168 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
169 ; /* nothing */
171 if (waiting < 0) {
172 failed_errno = errno;
173 error("waitpid for %s failed: %s", argv0, strerror(errno));
174 } else if (waiting != pid) {
175 error("waitpid is confused (%s)", argv0);
176 } else if (WIFSIGNALED(status)) {
177 code = WTERMSIG(status);
178 error("%s died of signal %d", argv0, code);
180 * This return value is chosen so that code & 0xff
181 * mimics the exit code that a POSIX shell would report for
182 * a program that died from this signal.
184 code -= 128;
185 } else if (WIFEXITED(status)) {
186 code = WEXITSTATUS(status);
188 * Convert special exit code when execvp failed.
190 if (code == 127) {
191 code = -1;
192 failed_errno = ENOENT;
194 } else {
195 error("waitpid is confused (%s)", argv0);
197 errno = failed_errno;
198 return code;
201 int start_command(struct child_process *cmd)
203 int need_in, need_out, need_err;
204 int fdin[2], fdout[2], fderr[2];
205 int failed_errno = failed_errno;
208 * In case of errors we must keep the promise to close FDs
209 * that have been passed in via ->in and ->out.
212 need_in = !cmd->no_stdin && cmd->in < 0;
213 if (need_in) {
214 if (pipe(fdin) < 0) {
215 failed_errno = errno;
216 if (cmd->out > 0)
217 close(cmd->out);
218 goto fail_pipe;
220 cmd->in = fdin[1];
223 need_out = !cmd->no_stdout
224 && !cmd->stdout_to_stderr
225 && cmd->out < 0;
226 if (need_out) {
227 if (pipe(fdout) < 0) {
228 failed_errno = errno;
229 if (need_in)
230 close_pair(fdin);
231 else if (cmd->in)
232 close(cmd->in);
233 goto fail_pipe;
235 cmd->out = fdout[0];
238 need_err = !cmd->no_stderr && cmd->err < 0;
239 if (need_err) {
240 if (pipe(fderr) < 0) {
241 failed_errno = errno;
242 if (need_in)
243 close_pair(fdin);
244 else if (cmd->in)
245 close(cmd->in);
246 if (need_out)
247 close_pair(fdout);
248 else if (cmd->out)
249 close(cmd->out);
250 fail_pipe:
251 error("cannot create pipe for %s: %s",
252 cmd->argv[0], strerror(failed_errno));
253 errno = failed_errno;
254 return -1;
256 cmd->err = fderr[0];
259 trace_argv_printf(cmd->argv, "trace: run_command:");
260 fflush(NULL);
262 #ifndef WIN32
264 int notify_pipe[2];
265 if (pipe(notify_pipe))
266 notify_pipe[0] = notify_pipe[1] = -1;
268 cmd->pid = fork();
269 if (!cmd->pid) {
271 * Redirect the channel to write syscall error messages to
272 * before redirecting the process's stderr so that all die()
273 * in subsequent call paths use the parent's stderr.
275 if (cmd->no_stderr || need_err) {
276 child_err = dup(2);
277 set_cloexec(child_err);
279 set_die_routine(die_child);
280 set_error_routine(error_child);
282 close(notify_pipe[0]);
283 set_cloexec(notify_pipe[1]);
284 child_notifier = notify_pipe[1];
285 atexit(notify_parent);
287 if (cmd->no_stdin)
288 dup_devnull(0);
289 else if (need_in) {
290 dup2(fdin[0], 0);
291 close_pair(fdin);
292 } else if (cmd->in) {
293 dup2(cmd->in, 0);
294 close(cmd->in);
297 if (cmd->no_stderr)
298 dup_devnull(2);
299 else if (need_err) {
300 dup2(fderr[1], 2);
301 close_pair(fderr);
302 } else if (cmd->err > 1) {
303 dup2(cmd->err, 2);
304 close(cmd->err);
307 if (cmd->no_stdout)
308 dup_devnull(1);
309 else if (cmd->stdout_to_stderr)
310 dup2(2, 1);
311 else if (need_out) {
312 dup2(fdout[1], 1);
313 close_pair(fdout);
314 } else if (cmd->out > 1) {
315 dup2(cmd->out, 1);
316 close(cmd->out);
319 if (cmd->dir && chdir(cmd->dir))
320 die_errno("exec '%s': cd to '%s' failed", cmd->argv[0],
321 cmd->dir);
322 if (cmd->env) {
323 for (; *cmd->env; cmd->env++) {
324 if (strchr(*cmd->env, '='))
325 putenv((char *)*cmd->env);
326 else
327 unsetenv(*cmd->env);
330 if (cmd->preexec_cb) {
332 * We cannot predict what the pre-exec callback does.
333 * Forgo parent notification.
335 close(child_notifier);
336 child_notifier = -1;
338 cmd->preexec_cb();
340 if (cmd->git_cmd) {
341 execv_git_cmd(cmd->argv);
342 } else if (cmd->use_shell) {
343 execv_shell_cmd(cmd->argv);
344 } else {
345 sane_execvp(cmd->argv[0], (char *const*) cmd->argv);
347 if (errno == ENOENT) {
348 if (!cmd->silent_exec_failure)
349 error("cannot run %s: %s", cmd->argv[0],
350 strerror(ENOENT));
351 exit(127);
352 } else {
353 die_errno("cannot exec '%s'", cmd->argv[0]);
356 if (cmd->pid < 0)
357 error("cannot fork() for %s: %s", cmd->argv[0],
358 strerror(failed_errno = errno));
361 * Wait for child's execvp. If the execvp succeeds (or if fork()
362 * failed), EOF is seen immediately by the parent. Otherwise, the
363 * child process sends a single byte.
364 * Note that use of this infrastructure is completely advisory,
365 * therefore, we keep error checks minimal.
367 close(notify_pipe[1]);
368 if (read(notify_pipe[0], &notify_pipe[1], 1) == 1) {
370 * At this point we know that fork() succeeded, but execvp()
371 * failed. Errors have been reported to our stderr.
373 wait_or_whine(cmd->pid, cmd->argv[0],
374 cmd->silent_exec_failure);
375 failed_errno = errno;
376 cmd->pid = -1;
378 close(notify_pipe[0]);
380 #else
382 int fhin = 0, fhout = 1, fherr = 2;
383 const char **sargv = cmd->argv;
384 char **env = environ;
386 if (cmd->no_stdin)
387 fhin = open("/dev/null", O_RDWR);
388 else if (need_in)
389 fhin = dup(fdin[0]);
390 else if (cmd->in)
391 fhin = dup(cmd->in);
393 if (cmd->no_stderr)
394 fherr = open("/dev/null", O_RDWR);
395 else if (need_err)
396 fherr = dup(fderr[1]);
397 else if (cmd->err > 2)
398 fherr = dup(cmd->err);
400 if (cmd->no_stdout)
401 fhout = open("/dev/null", O_RDWR);
402 else if (cmd->stdout_to_stderr)
403 fhout = dup(fherr);
404 else if (need_out)
405 fhout = dup(fdout[1]);
406 else if (cmd->out > 1)
407 fhout = dup(cmd->out);
409 if (cmd->env)
410 env = make_augmented_environ(cmd->env);
412 if (cmd->git_cmd) {
413 cmd->argv = prepare_git_cmd(cmd->argv);
414 } else if (cmd->use_shell) {
415 cmd->argv = prepare_shell_cmd(cmd->argv);
418 cmd->pid = mingw_spawnvpe(cmd->argv[0], cmd->argv, env, cmd->dir,
419 fhin, fhout, fherr);
420 failed_errno = errno;
421 if (cmd->pid < 0 && (!cmd->silent_exec_failure || errno != ENOENT))
422 error("cannot spawn %s: %s", cmd->argv[0], strerror(errno));
424 if (cmd->env)
425 free_environ(env);
426 if (cmd->git_cmd)
427 free(cmd->argv);
429 cmd->argv = sargv;
430 if (fhin != 0)
431 close(fhin);
432 if (fhout != 1)
433 close(fhout);
434 if (fherr != 2)
435 close(fherr);
437 #endif
439 if (cmd->pid < 0) {
440 if (need_in)
441 close_pair(fdin);
442 else if (cmd->in)
443 close(cmd->in);
444 if (need_out)
445 close_pair(fdout);
446 else if (cmd->out)
447 close(cmd->out);
448 if (need_err)
449 close_pair(fderr);
450 else if (cmd->err)
451 close(cmd->err);
452 errno = failed_errno;
453 return -1;
456 if (need_in)
457 close(fdin[0]);
458 else if (cmd->in)
459 close(cmd->in);
461 if (need_out)
462 close(fdout[1]);
463 else if (cmd->out)
464 close(cmd->out);
466 if (need_err)
467 close(fderr[1]);
468 else if (cmd->err)
469 close(cmd->err);
471 return 0;
474 int finish_command(struct child_process *cmd)
476 return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
479 int run_command(struct child_process *cmd)
481 int code = start_command(cmd);
482 if (code)
483 return code;
484 return finish_command(cmd);
487 static void prepare_run_command_v_opt(struct child_process *cmd,
488 const char **argv,
489 int opt)
491 memset(cmd, 0, sizeof(*cmd));
492 cmd->argv = argv;
493 cmd->no_stdin = opt & RUN_COMMAND_NO_STDIN ? 1 : 0;
494 cmd->git_cmd = opt & RUN_GIT_CMD ? 1 : 0;
495 cmd->stdout_to_stderr = opt & RUN_COMMAND_STDOUT_TO_STDERR ? 1 : 0;
496 cmd->silent_exec_failure = opt & RUN_SILENT_EXEC_FAILURE ? 1 : 0;
497 cmd->use_shell = opt & RUN_USING_SHELL ? 1 : 0;
500 int run_command_v_opt(const char **argv, int opt)
502 struct child_process cmd;
503 prepare_run_command_v_opt(&cmd, argv, opt);
504 return run_command(&cmd);
507 int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
509 struct child_process cmd;
510 prepare_run_command_v_opt(&cmd, argv, opt);
511 cmd.dir = dir;
512 cmd.env = env;
513 return run_command(&cmd);
516 #ifndef NO_PTHREADS
517 static pthread_t main_thread;
518 static int main_thread_set;
519 static pthread_key_t async_key;
521 static void *run_thread(void *data)
523 struct async *async = data;
524 intptr_t ret;
526 pthread_setspecific(async_key, async);
527 ret = async->proc(async->proc_in, async->proc_out, async->data);
528 return (void *)ret;
531 static NORETURN void die_async(const char *err, va_list params)
533 vreportf("fatal: ", err, params);
535 if (!pthread_equal(main_thread, pthread_self())) {
536 struct async *async = pthread_getspecific(async_key);
537 if (async->proc_in >= 0)
538 close(async->proc_in);
539 if (async->proc_out >= 0)
540 close(async->proc_out);
541 pthread_exit((void *)128);
544 exit(128);
546 #endif
548 int start_async(struct async *async)
550 int need_in, need_out;
551 int fdin[2], fdout[2];
552 int proc_in, proc_out;
554 need_in = async->in < 0;
555 if (need_in) {
556 if (pipe(fdin) < 0) {
557 if (async->out > 0)
558 close(async->out);
559 return error("cannot create pipe: %s", strerror(errno));
561 async->in = fdin[1];
564 need_out = async->out < 0;
565 if (need_out) {
566 if (pipe(fdout) < 0) {
567 if (need_in)
568 close_pair(fdin);
569 else if (async->in)
570 close(async->in);
571 return error("cannot create pipe: %s", strerror(errno));
573 async->out = fdout[0];
576 if (need_in)
577 proc_in = fdin[0];
578 else if (async->in)
579 proc_in = async->in;
580 else
581 proc_in = -1;
583 if (need_out)
584 proc_out = fdout[1];
585 else if (async->out)
586 proc_out = async->out;
587 else
588 proc_out = -1;
590 #ifdef NO_PTHREADS
591 /* Flush stdio before fork() to avoid cloning buffers */
592 fflush(NULL);
594 async->pid = fork();
595 if (async->pid < 0) {
596 error("fork (async) failed: %s", strerror(errno));
597 goto error;
599 if (!async->pid) {
600 if (need_in)
601 close(fdin[1]);
602 if (need_out)
603 close(fdout[0]);
604 exit(!!async->proc(proc_in, proc_out, async->data));
607 if (need_in)
608 close(fdin[0]);
609 else if (async->in)
610 close(async->in);
612 if (need_out)
613 close(fdout[1]);
614 else if (async->out)
615 close(async->out);
616 #else
617 if (!main_thread_set) {
619 * We assume that the first time that start_async is called
620 * it is from the main thread.
622 main_thread_set = 1;
623 main_thread = pthread_self();
624 pthread_key_create(&async_key, NULL);
625 set_die_routine(die_async);
628 if (proc_in >= 0)
629 set_cloexec(proc_in);
630 if (proc_out >= 0)
631 set_cloexec(proc_out);
632 async->proc_in = proc_in;
633 async->proc_out = proc_out;
635 int err = pthread_create(&async->tid, NULL, run_thread, async);
636 if (err) {
637 error("cannot create thread: %s", strerror(err));
638 goto error;
641 #endif
642 return 0;
644 error:
645 if (need_in)
646 close_pair(fdin);
647 else if (async->in)
648 close(async->in);
650 if (need_out)
651 close_pair(fdout);
652 else if (async->out)
653 close(async->out);
654 return -1;
657 int finish_async(struct async *async)
659 #ifdef NO_PTHREADS
660 return wait_or_whine(async->pid, "child process", 0);
661 #else
662 void *ret = (void *)(intptr_t)(-1);
664 if (pthread_join(async->tid, &ret))
665 error("pthread_join failed");
666 return (int)(intptr_t)ret;
667 #endif
670 int run_hook(const char *index_file, const char *name, ...)
672 struct child_process hook;
673 struct argv_array argv = ARGV_ARRAY_INIT;
674 const char *p, *env[2];
675 char index[PATH_MAX];
676 va_list args;
677 int ret;
679 if (access(git_path("hooks/%s", name), X_OK) < 0)
680 return 0;
682 va_start(args, name);
683 argv_array_push(&argv, git_path("hooks/%s", name));
684 while ((p = va_arg(args, const char *)))
685 argv_array_push(&argv, p);
686 va_end(args);
688 memset(&hook, 0, sizeof(hook));
689 hook.argv = argv.argv;
690 hook.no_stdin = 1;
691 hook.stdout_to_stderr = 1;
692 if (index_file) {
693 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
694 env[0] = index;
695 env[1] = NULL;
696 hook.env = env;
699 ret = run_command(&hook);
700 argv_array_clear(&argv);
701 return ret;