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 else if (errno == ENOTDIR && !strchr(file, '/'))
81 errno = ENOENT;
82 return -1;
83}
84
85static const char **prepare_shell_cmd(const char **argv)
86{
87 int argc, nargc = 0;
88 const char **nargv;
89
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));
94
95 if (argc < 1)
96 die("BUG: shell command is empty");
97
98 if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
99 nargv[nargc++] = "sh";
100 nargv[nargc++] = "-c";
101
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);
108 }
109 }
110
111 for (argc = 0; argv[argc]; argc++)
112 nargv[nargc++] = argv[argc];
113 nargv[nargc] = NULL;
114
115 return nargv;
116}
117
118#ifndef WIN32
119static int execv_shell_cmd(const char **argv)
120{
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;
126}
127#endif
128
129#ifndef WIN32
130static int child_err = 2;
131static int child_notifier = -1;
132
133static void notify_parent(void)
134{
135 /*
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.
139 */
140 xwrite(child_notifier, "", 1);
141}
142
143static NORETURN void die_child(const char *err, va_list params)
144{
145 vwritef(child_err, "fatal: ", err, params);
146 exit(128);
147}
148
149static void error_child(const char *err, va_list params)
150{
151 vwritef(child_err, "error: ", err, params);
152}
153#endif
154
155static inline void set_cloexec(int fd)
156{
157 int flags = fcntl(fd, F_GETFD);
158 if (flags >= 0)
159 fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
160}
161
162static int wait_or_whine(pid_t pid, const char *argv0, int silent_exec_failure)
163{
164 int status, code = -1;
165 pid_t waiting;
166 int failed_errno = 0;
167
168 while ((waiting = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
169 ; /* nothing */
170
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);
179 /*
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.
183 */
184 code -= 128;
185 } else if (WIFEXITED(status)) {
186 code = WEXITSTATUS(status);
187 /*
188 * Convert special exit code when execvp failed.
189 */
190 if (code == 127) {
191 code = -1;
192 failed_errno = ENOENT;
193 }
194 } else {
195 error("waitpid is confused (%s)", argv0);
196 }
197 errno = failed_errno;
198 return code;
199}
200
201int start_command(struct child_process *cmd)
202{
203 int need_in, need_out, need_err;
204 int fdin[2], fdout[2], fderr[2];
205 int failed_errno = failed_errno;
206
207 /*
208 * In case of errors we must keep the promise to close FDs
209 * that have been passed in via ->in and ->out.
210 */
211
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;
219 }
220 cmd->in = fdin[1];
221 }
222
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;
234 }
235 cmd->out = fdout[0];
236 }
237
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);
250fail_pipe:
251 error("cannot create pipe for %s: %s",
252 cmd->argv[0], strerror(failed_errno));
253 errno = failed_errno;
254 return -1;
255 }
256 cmd->err = fderr[0];
257 }
258
259 trace_argv_printf(cmd->argv, "trace: run_command:");
260 fflush(NULL);
261
262#ifndef WIN32
263{
264 int notify_pipe[2];
265 if (pipe(notify_pipe))
266 notify_pipe[0] = notify_pipe[1] = -1;
267
268 cmd->pid = fork();
269 if (!cmd->pid) {
270 /*
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.
274 */
275 if (cmd->no_stderr || need_err) {
276 child_err = dup(2);
277 set_cloexec(child_err);
278 }
279 set_die_routine(die_child);
280 set_error_routine(error_child);
281
282 close(notify_pipe[0]);
283 set_cloexec(notify_pipe[1]);
284 child_notifier = notify_pipe[1];
285 atexit(notify_parent);
286
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);
295 }
296
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);
305 }
306
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);
317 }
318
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);
328 }
329 }
330 if (cmd->preexec_cb) {
331 /*
332 * We cannot predict what the pre-exec callback does.
333 * Forgo parent notification.
334 */
335 close(child_notifier);
336 child_notifier = -1;
337
338 cmd->preexec_cb();
339 }
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);
346 }
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]);
354 }
355 }
356 if (cmd->pid < 0)
357 error("cannot fork() for %s: %s", cmd->argv[0],
358 strerror(failed_errno = errno));
359
360 /*
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.
366 */
367 close(notify_pipe[1]);
368 if (read(notify_pipe[0], ¬ify_pipe[1], 1) == 1) {
369 /*
370 * At this point we know that fork() succeeded, but execvp()
371 * failed. Errors have been reported to our stderr.
372 */
373 wait_or_whine(cmd->pid, cmd->argv[0],
374 cmd->silent_exec_failure);
375 failed_errno = errno;
376 cmd->pid = -1;
377 }
378 close(notify_pipe[0]);
379}
380#else
381{
382 int fhin = 0, fhout = 1, fherr = 2;
383 const char **sargv = cmd->argv;
384 char **env = environ;
385
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);
392
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);
399
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);
408
409 if (cmd->env)
410 env = make_augmented_environ(cmd->env);
411
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);
416 }
417
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));
423
424 if (cmd->env)
425 free_environ(env);
426 if (cmd->git_cmd)
427 free(cmd->argv);
428
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);
436}
437#endif
438
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;
454 }
455
456 if (need_in)
457 close(fdin[0]);
458 else if (cmd->in)
459 close(cmd->in);
460
461 if (need_out)
462 close(fdout[1]);
463 else if (cmd->out)
464 close(cmd->out);
465
466 if (need_err)
467 close(fderr[1]);
468 else if (cmd->err)
469 close(cmd->err);
470
471 return 0;
472}
473
474int finish_command(struct child_process *cmd)
475{
476 return wait_or_whine(cmd->pid, cmd->argv[0], cmd->silent_exec_failure);
477}
478
479int run_command(struct child_process *cmd)
480{
481 int code = start_command(cmd);
482 if (code)
483 return code;
484 return finish_command(cmd);
485}
486
487static void prepare_run_command_v_opt(struct child_process *cmd,
488 const char **argv,
489 int opt)
490{
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;
498}
499
500int run_command_v_opt(const char **argv, int opt)
501{
502 struct child_process cmd;
503 prepare_run_command_v_opt(&cmd, argv, opt);
504 return run_command(&cmd);
505}
506
507int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env)
508{
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);
514}
515
516#ifndef NO_PTHREADS
517static pthread_t main_thread;
518static int main_thread_set;
519static pthread_key_t async_key;
520
521static void *run_thread(void *data)
522{
523 struct async *async = data;
524 intptr_t ret;
525
526 pthread_setspecific(async_key, async);
527 ret = async->proc(async->proc_in, async->proc_out, async->data);
528 return (void *)ret;
529}
530
531static NORETURN void die_async(const char *err, va_list params)
532{
533 vreportf("fatal: ", err, params);
534
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);
542 }
543
544 exit(128);
545}
546#endif
547
548int start_async(struct async *async)
549{
550 int need_in, need_out;
551 int fdin[2], fdout[2];
552 int proc_in, proc_out;
553
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));
560 }
561 async->in = fdin[1];
562 }
563
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));
572 }
573 async->out = fdout[0];
574 }
575
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;
582
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;
589
590#ifdef NO_PTHREADS
591 /* Flush stdio before fork() to avoid cloning buffers */
592 fflush(NULL);
593
594 async->pid = fork();
595 if (async->pid < 0) {
596 error("fork (async) failed: %s", strerror(errno));
597 goto error;
598 }
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));
605 }
606
607 if (need_in)
608 close(fdin[0]);
609 else if (async->in)
610 close(async->in);
611
612 if (need_out)
613 close(fdout[1]);
614 else if (async->out)
615 close(async->out);
616#else
617 if (!main_thread_set) {
618 /*
619 * We assume that the first time that start_async is called
620 * it is from the main thread.
621 */
622 main_thread_set = 1;
623 main_thread = pthread_self();
624 pthread_key_create(&async_key, NULL);
625 set_die_routine(die_async);
626 }
627
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;
634 {
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;
639 }
640 }
641#endif
642 return 0;
643
644error:
645 if (need_in)
646 close_pair(fdin);
647 else if (async->in)
648 close(async->in);
649
650 if (need_out)
651 close_pair(fdout);
652 else if (async->out)
653 close(async->out);
654 return -1;
655}
656
657int finish_async(struct async *async)
658{
659#ifdef NO_PTHREADS
660 return wait_or_whine(async->pid, "child process", 0);
661#else
662 void *ret = (void *)(intptr_t)(-1);
663
664 if (pthread_join(async->tid, &ret))
665 error("pthread_join failed");
666 return (int)(intptr_t)ret;
667#endif
668}
669
670int run_hook(const char *index_file, const char *name, ...)
671{
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;
678
679 if (access(git_path("hooks/%s", name), X_OK) < 0)
680 return 0;
681
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);
687
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;
697 }
698
699 ret = run_command(&hook);
700 argv_array_clear(&argv);
701 return ret;
702}