Propagate effects of putenv/setenv/unsetenv to child processes.
[gnulib.git] / lib / pipe.c
1 /* Creation of subprocesses, communicating via pipes.
2    Copyright (C) 2001-2004, 2006-2008 Free Software Foundation, Inc.
3    Written by Bruno Haible <haible@clisp.cons.org>, 2001.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18
19 #include <config.h>
20
21 /* Specification.  */
22 #include "pipe.h"
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <unistd.h>
29
30 #include "error.h"
31 #include "fatal-signal.h"
32 #include "unistd-safer.h"
33 #include "wait-process.h"
34 #include "gettext.h"
35
36 #define _(str) gettext (str)
37
38 #if defined _MSC_VER || defined __MINGW32__
39
40 /* Native Woe32 API.  */
41 # include <process.h>
42 # include "w32spawn.h"
43
44 #else
45
46 /* Unix API.  */
47 # if HAVE_POSIX_SPAWN
48 #  include <spawn.h>
49 # else
50 #  if HAVE_VFORK_H
51 #   include <vfork.h>
52 #  endif
53 # endif
54
55 #endif
56
57 #ifndef STDIN_FILENO
58 # define STDIN_FILENO 0
59 #endif
60 #ifndef STDOUT_FILENO
61 # define STDOUT_FILENO 1
62 #endif
63 #ifndef STDERR_FILENO
64 # define STDERR_FILENO 2
65 #endif
66
67 /* The results of open() in this file are not used with fchdir,
68    therefore save some unnecessary work in fchdir.c.  */
69 #undef open
70 #undef close
71
72
73 #ifdef EINTR
74
75 /* EINTR handling for close().
76    These functions can return -1/EINTR even though we don't have any
77    signal handlers set up, namely when we get interrupted via SIGSTOP.  */
78
79 static inline int
80 nonintr_close (int fd)
81 {
82   int retval;
83
84   do
85     retval = close (fd);
86   while (retval < 0 && errno == EINTR);
87
88   return retval;
89 }
90 #define close nonintr_close
91
92 static inline int
93 nonintr_open (const char *pathname, int oflag, mode_t mode)
94 {
95   int retval;
96
97   do
98     retval = open (pathname, oflag, mode);
99   while (retval < 0 && errno == EINTR);
100
101   return retval;
102 }
103 #undef open /* avoid warning on VMS */
104 #define open nonintr_open
105
106 #endif
107
108
109 /* Open a pipe connected to a child process.
110  *
111  *           write       system                read
112  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child       if pipe_stdin
113  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child       if pipe_stdout
114  *           read        system                write
115  *
116  * At least one of pipe_stdin, pipe_stdout must be true.
117  * pipe_stdin and prog_stdin together determine the child's standard input.
118  * pipe_stdout and prog_stdout together determine the child's standard output.
119  * If pipe_stdin is true, prog_stdin is ignored.
120  * If pipe_stdout is true, prog_stdout is ignored.
121  */
122 static pid_t
123 create_pipe (const char *progname,
124              const char *prog_path, char **prog_argv,
125              bool pipe_stdin, bool pipe_stdout,
126              const char *prog_stdin, const char *prog_stdout,
127              bool null_stderr,
128              bool slave_process, bool exit_on_error,
129              int fd[2])
130 {
131 #if defined _MSC_VER || defined __MINGW32__
132
133   /* Native Woe32 API.
134      This uses _pipe(), dup2(), and spawnv().  It could also be implemented
135      using the low-level functions CreatePipe(), DuplicateHandle(),
136      CreateProcess() and _open_osfhandle(); see the GNU make and GNU clisp
137      and cvs source code.  */
138   int ifd[2];
139   int ofd[2];
140   int orig_stdin;
141   int orig_stdout;
142   int orig_stderr;
143   int child;
144   int nulloutfd;
145   int stdinfd;
146   int stdoutfd;
147
148   /* FIXME: Need to free memory allocated by prepare_spawn.  */
149   prog_argv = prepare_spawn (prog_argv);
150
151   if (pipe_stdout)
152     if (_pipe (ifd, 4096, O_BINARY | O_NOINHERIT) < 0
153         || (ifd[0] = fd_safer (ifd[0])) < 0)
154       error (EXIT_FAILURE, errno, _("cannot create pipe"));
155   if (pipe_stdin)
156     if (_pipe (ofd, 4096, O_BINARY | O_NOINHERIT) < 0
157         || (ofd[1] = fd_safer (ofd[1])) < 0)
158       error (EXIT_FAILURE, errno, _("cannot create pipe"));
159 /* Data flow diagram:
160  *
161  *           write        system         read
162  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
163  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
164  *           read         system         write
165  *
166  */
167
168   /* Save standard file handles of parent process.  */
169   if (pipe_stdin || prog_stdin != NULL)
170     orig_stdin = dup_noinherit (STDIN_FILENO);
171   if (pipe_stdout || prog_stdout != NULL)
172     orig_stdout = dup_noinherit (STDOUT_FILENO);
173   if (null_stderr)
174     orig_stderr = dup_noinherit (STDERR_FILENO);
175   child = -1;
176
177   /* Create standard file handles of child process.  */
178   nulloutfd = -1;
179   stdinfd = -1;
180   stdoutfd = -1;
181   if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
182       && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
183       && (!null_stderr
184           || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
185               && (nulloutfd == STDERR_FILENO
186                   || (dup2 (nulloutfd, STDERR_FILENO) >= 0
187                       && close (nulloutfd) >= 0))))
188       && (pipe_stdin
189           || prog_stdin == NULL
190           || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
191               && (stdinfd == STDIN_FILENO
192                   || (dup2 (stdinfd, STDIN_FILENO) >= 0
193                       && close (stdinfd) >= 0))))
194       && (pipe_stdout
195           || prog_stdout == NULL
196           || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
197               && (stdoutfd == STDOUT_FILENO
198                   || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
199                       && close (stdoutfd) >= 0)))))
200     /* The child process doesn't inherit ifd[0], ifd[1], ofd[0], ofd[1],
201        but it inherits all open()ed or dup2()ed file handles (which is what
202        we want in the case of STD*_FILENO) and also orig_stdin,
203        orig_stdout, orig_stderr (which is not explicitly wanted but
204        harmless).  */
205     /* Use spawnvpe and pass the environment explicitly.  This is needed if
206        the program has modified the environment using putenv() or [un]setenv().
207        On Windows, programs have two environments, one in the "environment
208        block" of the process and managed through SetEnvironmentVariable(), and
209        one inside the process, in the location retrieved by the 'environ'
210        macro.  When using spawnvp() without 'e', the child process inherits a
211        copy of the environment block - ignoring the effects of putenv() and
212        [un]setenv().  */
213     {
214       child = spawnvpe (P_NOWAIT, prog_path, prog_argv, environ);
215       if (child < 0 && errno == ENOEXEC)
216         {
217           /* prog is not an native executable.  Try to execute it as a
218              shell script.  Note that prepare_spawn() has already prepended
219              a hidden element "sh.exe" to prog_argv.  */
220           --prog_argv;
221           child = spawnvpe (P_NOWAIT, prog_argv[0], prog_argv, environ);
222         }
223     }
224   if (stdinfd >= 0)
225     close (stdinfd);
226   if (stdoutfd >= 0)
227     close (stdoutfd);
228   if (nulloutfd >= 0)
229     close (nulloutfd);
230
231   /* Restore standard file handles of parent process.  */
232   if (null_stderr)
233     dup2 (orig_stderr, STDERR_FILENO), close (orig_stderr);
234   if (pipe_stdout || prog_stdout != NULL)
235     dup2 (orig_stdout, STDOUT_FILENO), close (orig_stdout);
236   if (pipe_stdin || prog_stdin != NULL)
237     dup2 (orig_stdin, STDIN_FILENO), close (orig_stdin);
238
239   if (pipe_stdin)
240     close (ofd[0]);
241   if (pipe_stdout)
242     close (ifd[1]);
243   if (child == -1)
244     {
245       if (exit_on_error || !null_stderr)
246         error (exit_on_error ? EXIT_FAILURE : 0, errno,
247                _("%s subprocess failed"), progname);
248       if (pipe_stdout)
249         close (ifd[0]);
250       if (pipe_stdin)
251         close (ofd[1]);
252       return -1;
253     }
254
255   if (pipe_stdout)
256     fd[0] = ifd[0];
257   if (pipe_stdin)
258     fd[1] = ofd[1];
259   return child;
260
261 #else
262
263   /* Unix API.  */
264   int ifd[2];
265   int ofd[2];
266 # if HAVE_POSIX_SPAWN
267   sigset_t blocked_signals;
268   posix_spawn_file_actions_t actions;
269   bool actions_allocated;
270   posix_spawnattr_t attrs;
271   bool attrs_allocated;
272   int err;
273   pid_t child;
274 # else
275   int child;
276 # endif
277
278   if (pipe_stdout)
279     if (pipe (ifd) < 0
280         || (ifd[0] = fd_safer (ifd[0])) < 0)
281       error (EXIT_FAILURE, errno, _("cannot create pipe"));
282   if (pipe_stdin)
283     if (pipe (ofd) < 0
284         || (ofd[1] = fd_safer (ofd[1])) < 0)
285       error (EXIT_FAILURE, errno, _("cannot create pipe"));
286 /* Data flow diagram:
287  *
288  *           write        system         read
289  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
290  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
291  *           read         system         write
292  *
293  */
294
295 # if HAVE_POSIX_SPAWN
296   if (slave_process)
297     {
298       sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
299       block_fatal_signals ();
300     }
301   actions_allocated = false;
302   attrs_allocated = false;
303   if ((err = posix_spawn_file_actions_init (&actions)) != 0
304       || (actions_allocated = true,
305           (pipe_stdin
306            && (err = posix_spawn_file_actions_adddup2 (&actions,
307                                                        ofd[0], STDIN_FILENO))
308               != 0)
309           || (pipe_stdout
310               && (err = posix_spawn_file_actions_adddup2 (&actions,
311                                                           ifd[1], STDOUT_FILENO))
312                  != 0)
313           || (pipe_stdin
314               && (err = posix_spawn_file_actions_addclose (&actions, ofd[0]))
315                  != 0)
316           || (pipe_stdout
317               && (err = posix_spawn_file_actions_addclose (&actions, ifd[1]))
318                  != 0)
319           || (pipe_stdin
320               && (err = posix_spawn_file_actions_addclose (&actions, ofd[1]))
321                  != 0)
322           || (pipe_stdout
323               && (err = posix_spawn_file_actions_addclose (&actions, ifd[0]))
324                  != 0)
325           || (null_stderr
326               && (err = posix_spawn_file_actions_addopen (&actions,
327                                                           STDERR_FILENO,
328                                                           "/dev/null", O_RDWR,
329                                                           0))
330                  != 0)
331           || (!pipe_stdin
332               && prog_stdin != NULL
333               && (err = posix_spawn_file_actions_addopen (&actions,
334                                                           STDIN_FILENO,
335                                                           prog_stdin, O_RDONLY,
336                                                           0))
337                  != 0)
338           || (!pipe_stdout
339               && prog_stdout != NULL
340               && (err = posix_spawn_file_actions_addopen (&actions,
341                                                           STDOUT_FILENO,
342                                                           prog_stdout, O_WRONLY,
343                                                           0))
344                  != 0)
345           || (slave_process
346               && ((err = posix_spawnattr_init (&attrs)) != 0
347                   || (attrs_allocated = true,
348                       (err = posix_spawnattr_setsigmask (&attrs,
349                                                          &blocked_signals))
350                       != 0
351                       || (err = posix_spawnattr_setflags (&attrs,
352                                                         POSIX_SPAWN_SETSIGMASK))
353                          != 0)))
354           || (err = posix_spawnp (&child, prog_path, &actions,
355                                   attrs_allocated ? &attrs : NULL, prog_argv,
356                                   environ))
357              != 0))
358     {
359       if (actions_allocated)
360         posix_spawn_file_actions_destroy (&actions);
361       if (attrs_allocated)
362         posix_spawnattr_destroy (&attrs);
363       if (slave_process)
364         unblock_fatal_signals ();
365       if (exit_on_error || !null_stderr)
366         error (exit_on_error ? EXIT_FAILURE : 0, err,
367                _("%s subprocess failed"), progname);
368       if (pipe_stdout)
369         {
370           close (ifd[0]);
371           close (ifd[1]);
372         }
373       if (pipe_stdin)
374         {
375           close (ofd[0]);
376           close (ofd[1]);
377         }
378       return -1;
379     }
380   posix_spawn_file_actions_destroy (&actions);
381   if (attrs_allocated)
382     posix_spawnattr_destroy (&attrs);
383 # else
384   if (slave_process)
385     block_fatal_signals ();
386   /* Use vfork() instead of fork() for efficiency.  */
387   if ((child = vfork ()) == 0)
388     {
389       /* Child process code.  */
390       int nulloutfd;
391       int stdinfd;
392       int stdoutfd;
393
394       if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
395           && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
396           && (!pipe_stdin || close (ofd[0]) >= 0)
397           && (!pipe_stdout || close (ifd[1]) >= 0)
398           && (!pipe_stdin || close (ofd[1]) >= 0)
399           && (!pipe_stdout || close (ifd[0]) >= 0)
400           && (!null_stderr
401               || ((nulloutfd = open ("/dev/null", O_RDWR, 0)) >= 0
402                   && (nulloutfd == STDERR_FILENO
403                       || (dup2 (nulloutfd, STDERR_FILENO) >= 0
404                           && close (nulloutfd) >= 0))))
405           && (pipe_stdin
406               || prog_stdin == NULL
407               || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
408                   && (stdinfd == STDIN_FILENO
409                       || (dup2 (stdinfd, STDIN_FILENO) >= 0
410                           && close (stdinfd) >= 0))))
411           && (pipe_stdout
412               || prog_stdout == NULL
413               || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
414                   && (stdoutfd == STDOUT_FILENO
415                       || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
416                           && close (stdoutfd) >= 0))))
417           && (!slave_process || (unblock_fatal_signals (), true)))
418         execvp (prog_path, prog_argv);
419       _exit (127);
420     }
421   if (child == -1)
422     {
423       if (slave_process)
424         unblock_fatal_signals ();
425       if (exit_on_error || !null_stderr)
426         error (exit_on_error ? EXIT_FAILURE : 0, errno,
427                _("%s subprocess failed"), progname);
428       if (pipe_stdout)
429         {
430           close (ifd[0]);
431           close (ifd[1]);
432         }
433       if (pipe_stdin)
434         {
435           close (ofd[0]);
436           close (ofd[1]);
437         }
438       return -1;
439     }
440 # endif
441   if (slave_process)
442     {
443       register_slave_subprocess (child);
444       unblock_fatal_signals ();
445     }
446   if (pipe_stdin)
447     close (ofd[0]);
448   if (pipe_stdout)
449     close (ifd[1]);
450
451   if (pipe_stdout)
452     fd[0] = ifd[0];
453   if (pipe_stdin)
454     fd[1] = ofd[1];
455   return child;
456
457 #endif
458 }
459
460 /* Open a bidirectional pipe.
461  *
462  *           write       system                read
463  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child
464  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
465  *           read        system                write
466  *
467  */
468 pid_t
469 create_pipe_bidi (const char *progname,
470                   const char *prog_path, char **prog_argv,
471                   bool null_stderr,
472                   bool slave_process, bool exit_on_error,
473                   int fd[2])
474 {
475   pid_t result = create_pipe (progname, prog_path, prog_argv,
476                               true, true, NULL, NULL,
477                               null_stderr, slave_process, exit_on_error,
478                               fd);
479   return result;
480 }
481
482 /* Open a pipe for input from a child process.
483  * The child's stdin comes from a file.
484  *
485  *           read        system                write
486  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
487  *
488  */
489 pid_t
490 create_pipe_in (const char *progname,
491                 const char *prog_path, char **prog_argv,
492                 const char *prog_stdin, bool null_stderr,
493                 bool slave_process, bool exit_on_error,
494                 int fd[1])
495 {
496   int iofd[2];
497   pid_t result = create_pipe (progname, prog_path, prog_argv,
498                               false, true, prog_stdin, NULL,
499                               null_stderr, slave_process, exit_on_error,
500                               iofd);
501   if (result != -1)
502     fd[0] = iofd[0];
503   return result;
504 }
505
506 /* Open a pipe for output to a child process.
507  * The child's stdout goes to a file.
508  *
509  *           write       system                read
510  *    parent  ->   fd[0]   ->   STDIN_FILENO    ->   child
511  *
512  */
513 pid_t
514 create_pipe_out (const char *progname,
515                  const char *prog_path, char **prog_argv,
516                  const char *prog_stdout, bool null_stderr,
517                  bool slave_process, bool exit_on_error,
518                  int fd[1])
519 {
520   int iofd[2];
521   pid_t result = create_pipe (progname, prog_path, prog_argv,
522                               true, false, NULL, prog_stdout,
523                               null_stderr, slave_process, exit_on_error,
524                               iofd);
525   if (result != -1)
526     fd[0] = iofd[1];
527   return result;
528 }