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