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