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