Use spaces for indentation, not tabs.
[gnulib.git] / lib / pipe.c
1 /* Creation of subprocesses, communicating via pipes.
2    Copyright (C) 2001-2004, 2006-2009 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 _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
39
40 /* Native Woe32 API.  */
41 # include <process.h>
42 # include "w32spawn.h"
43
44 #else
45
46 /* Unix API.  */
47 # include <spawn.h>
48
49 #endif
50
51 /* The results of open() in this file are not used with fchdir,
52    therefore save some unnecessary work in fchdir.c.  */
53 #undef open
54 #undef close
55
56
57 #ifdef EINTR
58
59 /* EINTR handling for close().
60    These functions can return -1/EINTR even though we don't have any
61    signal handlers set up, namely when we get interrupted via SIGSTOP.  */
62
63 static inline int
64 nonintr_close (int fd)
65 {
66   int retval;
67
68   do
69     retval = close (fd);
70   while (retval < 0 && errno == EINTR);
71
72   return retval;
73 }
74 #define close nonintr_close
75
76 static inline int
77 nonintr_open (const char *pathname, int oflag, mode_t mode)
78 {
79   int retval;
80
81   do
82     retval = open (pathname, oflag, mode);
83   while (retval < 0 && errno == EINTR);
84
85   return retval;
86 }
87 #undef open /* avoid warning on VMS */
88 #define open nonintr_open
89
90 #endif
91
92
93 /* Open a pipe connected to a child process.
94  *
95  *           write       system                read
96  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child       if pipe_stdin
97  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child       if pipe_stdout
98  *           read        system                write
99  *
100  * At least one of pipe_stdin, pipe_stdout must be true.
101  * pipe_stdin and prog_stdin together determine the child's standard input.
102  * pipe_stdout and prog_stdout together determine the child's standard output.
103  * If pipe_stdin is true, prog_stdin is ignored.
104  * If pipe_stdout is true, prog_stdout is ignored.
105  */
106 static pid_t
107 create_pipe (const char *progname,
108              const char *prog_path, char **prog_argv,
109              bool pipe_stdin, bool pipe_stdout,
110              const char *prog_stdin, const char *prog_stdout,
111              bool null_stderr,
112              bool slave_process, bool exit_on_error,
113              int fd[2])
114 {
115 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
116
117   /* Native Woe32 API.
118      This uses _pipe(), dup2(), and spawnv().  It could also be implemented
119      using the low-level functions CreatePipe(), DuplicateHandle(),
120      CreateProcess() and _open_osfhandle(); see the GNU make and GNU clisp
121      and cvs source code.  */
122   int ifd[2];
123   int ofd[2];
124   int orig_stdin;
125   int orig_stdout;
126   int orig_stderr;
127   int child;
128   int nulloutfd;
129   int stdinfd;
130   int stdoutfd;
131
132   /* FIXME: Need to free memory allocated by prepare_spawn.  */
133   prog_argv = prepare_spawn (prog_argv);
134
135   if (pipe_stdout)
136     if (pipe2_safer (ifd, O_BINARY | O_CLOEXEC) < 0)
137       error (EXIT_FAILURE, errno, _("cannot create pipe"));
138   if (pipe_stdin)
139     if (pipe2_safer (ofd, O_BINARY | O_CLOEXEC) < 0)
140       error (EXIT_FAILURE, errno, _("cannot create pipe"));
141 /* Data flow diagram:
142  *
143  *           write        system         read
144  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
145  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
146  *           read         system         write
147  *
148  */
149
150   /* Save standard file handles of parent process.  */
151   if (pipe_stdin || prog_stdin != NULL)
152     orig_stdin = dup_safer_noinherit (STDIN_FILENO);
153   if (pipe_stdout || prog_stdout != NULL)
154     orig_stdout = dup_safer_noinherit (STDOUT_FILENO);
155   if (null_stderr)
156     orig_stderr = dup_safer_noinherit (STDERR_FILENO);
157   child = -1;
158
159   /* Create standard file handles of child process.  */
160   nulloutfd = -1;
161   stdinfd = -1;
162   stdoutfd = -1;
163   if ((!pipe_stdin || dup2 (ofd[0], STDIN_FILENO) >= 0)
164       && (!pipe_stdout || dup2 (ifd[1], STDOUT_FILENO) >= 0)
165       && (!null_stderr
166           || ((nulloutfd = open ("NUL", O_RDWR, 0)) >= 0
167               && (nulloutfd == STDERR_FILENO
168                   || (dup2 (nulloutfd, STDERR_FILENO) >= 0
169                       && close (nulloutfd) >= 0))))
170       && (pipe_stdin
171           || prog_stdin == NULL
172           || ((stdinfd = open (prog_stdin, O_RDONLY, 0)) >= 0
173               && (stdinfd == STDIN_FILENO
174                   || (dup2 (stdinfd, STDIN_FILENO) >= 0
175                       && close (stdinfd) >= 0))))
176       && (pipe_stdout
177           || prog_stdout == NULL
178           || ((stdoutfd = open (prog_stdout, O_WRONLY, 0)) >= 0
179               && (stdoutfd == STDOUT_FILENO
180                   || (dup2 (stdoutfd, STDOUT_FILENO) >= 0
181                       && close (stdoutfd) >= 0)))))
182     /* The child process doesn't inherit ifd[0], ifd[1], ofd[0], ofd[1],
183        but it inherits all open()ed or dup2()ed file handles (which is what
184        we want in the case of STD*_FILENO).  */
185     /* Use spawnvpe and pass the environment explicitly.  This is needed if
186        the program has modified the environment using putenv() or [un]setenv().
187        On Windows, programs have two environments, one in the "environment
188        block" of the process and managed through SetEnvironmentVariable(), and
189        one inside the process, in the location retrieved by the 'environ'
190        macro.  When using spawnvp() without 'e', the child process inherits a
191        copy of the environment block - ignoring the effects of putenv() and
192        [un]setenv().  */
193     {
194       child = spawnvpe (P_NOWAIT, prog_path, (const char **) prog_argv,
195                         (const char **) environ);
196       if (child < 0 && errno == ENOEXEC)
197         {
198           /* prog is not an native executable.  Try to execute it as a
199              shell script.  Note that prepare_spawn() has already prepended
200              a hidden element "sh.exe" to prog_argv.  */
201           --prog_argv;
202           child = spawnvpe (P_NOWAIT, prog_argv[0], (const char **) prog_argv,
203                             (const char **) environ);
204         }
205     }
206   if (stdinfd >= 0)
207     close (stdinfd);
208   if (stdoutfd >= 0)
209     close (stdoutfd);
210   if (nulloutfd >= 0)
211     close (nulloutfd);
212
213   /* Restore standard file handles of parent process.  */
214   if (null_stderr)
215     undup_safer_noinherit (orig_stderr, STDERR_FILENO);
216   if (pipe_stdout || prog_stdout != NULL)
217     undup_safer_noinherit (orig_stdout, STDOUT_FILENO);
218   if (pipe_stdin || prog_stdin != NULL)
219     undup_safer_noinherit (orig_stdin, STDIN_FILENO);
220
221   if (pipe_stdin)
222     close (ofd[0]);
223   if (pipe_stdout)
224     close (ifd[1]);
225   if (child == -1)
226     {
227       if (exit_on_error || !null_stderr)
228         error (exit_on_error ? EXIT_FAILURE : 0, errno,
229                _("%s subprocess failed"), progname);
230       if (pipe_stdout)
231         close (ifd[0]);
232       if (pipe_stdin)
233         close (ofd[1]);
234       return -1;
235     }
236
237   if (pipe_stdout)
238     fd[0] = ifd[0];
239   if (pipe_stdin)
240     fd[1] = ofd[1];
241   return child;
242
243 #else
244
245   /* Unix API.  */
246   int ifd[2];
247   int ofd[2];
248   sigset_t blocked_signals;
249   posix_spawn_file_actions_t actions;
250   bool actions_allocated;
251   posix_spawnattr_t attrs;
252   bool attrs_allocated;
253   int err;
254   pid_t child;
255
256   if (pipe_stdout)
257     if (pipe_safer (ifd) < 0)
258       error (EXIT_FAILURE, errno, _("cannot create pipe"));
259   if (pipe_stdin)
260     if (pipe_safer (ofd) < 0)
261       error (EXIT_FAILURE, errno, _("cannot create pipe"));
262 /* Data flow diagram:
263  *
264  *           write        system         read
265  *    parent  ->   ofd[1]   ->   ofd[0]   ->   child       if pipe_stdin
266  *    parent  <-   ifd[0]   <-   ifd[1]   <-   child       if pipe_stdout
267  *           read         system         write
268  *
269  */
270
271   if (slave_process)
272     {
273       sigprocmask (SIG_SETMASK, NULL, &blocked_signals);
274       block_fatal_signals ();
275     }
276   actions_allocated = false;
277   attrs_allocated = false;
278   if ((err = posix_spawn_file_actions_init (&actions)) != 0
279       || (actions_allocated = true,
280           (pipe_stdin
281            && (err = posix_spawn_file_actions_adddup2 (&actions,
282                                                        ofd[0], STDIN_FILENO))
283               != 0)
284           || (pipe_stdout
285               && (err = posix_spawn_file_actions_adddup2 (&actions,
286                                                           ifd[1], STDOUT_FILENO))
287                  != 0)
288           || (pipe_stdin
289               && (err = posix_spawn_file_actions_addclose (&actions, ofd[0]))
290                  != 0)
291           || (pipe_stdout
292               && (err = posix_spawn_file_actions_addclose (&actions, ifd[1]))
293                  != 0)
294           || (pipe_stdin
295               && (err = posix_spawn_file_actions_addclose (&actions, ofd[1]))
296                  != 0)
297           || (pipe_stdout
298               && (err = posix_spawn_file_actions_addclose (&actions, ifd[0]))
299                  != 0)
300           || (null_stderr
301               && (err = posix_spawn_file_actions_addopen (&actions,
302                                                           STDERR_FILENO,
303                                                           "/dev/null", O_RDWR,
304                                                           0))
305                  != 0)
306           || (!pipe_stdin
307               && prog_stdin != NULL
308               && (err = posix_spawn_file_actions_addopen (&actions,
309                                                           STDIN_FILENO,
310                                                           prog_stdin, O_RDONLY,
311                                                           0))
312                  != 0)
313           || (!pipe_stdout
314               && prog_stdout != NULL
315               && (err = posix_spawn_file_actions_addopen (&actions,
316                                                           STDOUT_FILENO,
317                                                           prog_stdout, O_WRONLY,
318                                                           0))
319                  != 0)
320           || (slave_process
321               && ((err = posix_spawnattr_init (&attrs)) != 0
322                   || (attrs_allocated = true,
323                       (err = posix_spawnattr_setsigmask (&attrs,
324                                                          &blocked_signals))
325                       != 0
326                       || (err = posix_spawnattr_setflags (&attrs,
327                                                         POSIX_SPAWN_SETSIGMASK))
328                          != 0)))
329           || (err = posix_spawnp (&child, prog_path, &actions,
330                                   attrs_allocated ? &attrs : NULL, prog_argv,
331                                   environ))
332              != 0))
333     {
334       if (actions_allocated)
335         posix_spawn_file_actions_destroy (&actions);
336       if (attrs_allocated)
337         posix_spawnattr_destroy (&attrs);
338       if (slave_process)
339         unblock_fatal_signals ();
340       if (exit_on_error || !null_stderr)
341         error (exit_on_error ? EXIT_FAILURE : 0, err,
342                _("%s subprocess failed"), progname);
343       if (pipe_stdout)
344         {
345           close (ifd[0]);
346           close (ifd[1]);
347         }
348       if (pipe_stdin)
349         {
350           close (ofd[0]);
351           close (ofd[1]);
352         }
353       return -1;
354     }
355   posix_spawn_file_actions_destroy (&actions);
356   if (attrs_allocated)
357     posix_spawnattr_destroy (&attrs);
358   if (slave_process)
359     {
360       register_slave_subprocess (child);
361       unblock_fatal_signals ();
362     }
363   if (pipe_stdin)
364     close (ofd[0]);
365   if (pipe_stdout)
366     close (ifd[1]);
367
368   if (pipe_stdout)
369     fd[0] = ifd[0];
370   if (pipe_stdin)
371     fd[1] = ofd[1];
372   return child;
373
374 #endif
375 }
376
377 /* Open a bidirectional pipe.
378  *
379  *           write       system                read
380  *    parent  ->   fd[1]   ->   STDIN_FILENO    ->   child
381  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
382  *           read        system                write
383  *
384  */
385 pid_t
386 create_pipe_bidi (const char *progname,
387                   const char *prog_path, char **prog_argv,
388                   bool null_stderr,
389                   bool slave_process, bool exit_on_error,
390                   int fd[2])
391 {
392   pid_t result = create_pipe (progname, prog_path, prog_argv,
393                               true, true, NULL, NULL,
394                               null_stderr, slave_process, exit_on_error,
395                               fd);
396   return result;
397 }
398
399 /* Open a pipe for input from a child process.
400  * The child's stdin comes from a file.
401  *
402  *           read        system                write
403  *    parent  <-   fd[0]   <-   STDOUT_FILENO   <-   child
404  *
405  */
406 pid_t
407 create_pipe_in (const char *progname,
408                 const char *prog_path, char **prog_argv,
409                 const char *prog_stdin, bool null_stderr,
410                 bool slave_process, bool exit_on_error,
411                 int fd[1])
412 {
413   int iofd[2];
414   pid_t result = create_pipe (progname, prog_path, prog_argv,
415                               false, true, prog_stdin, NULL,
416                               null_stderr, slave_process, exit_on_error,
417                               iofd);
418   if (result != -1)
419     fd[0] = iofd[0];
420   return result;
421 }
422
423 /* Open a pipe for output to a child process.
424  * The child's stdout goes to a file.
425  *
426  *           write       system                read
427  *    parent  ->   fd[0]   ->   STDIN_FILENO    ->   child
428  *
429  */
430 pid_t
431 create_pipe_out (const char *progname,
432                  const char *prog_path, char **prog_argv,
433                  const char *prog_stdout, bool null_stderr,
434                  bool slave_process, bool exit_on_error,
435                  int fd[1])
436 {
437   int iofd[2];
438   pid_t result = create_pipe (progname, prog_path, prog_argv,
439                               true, false, NULL, prog_stdout,
440                               null_stderr, slave_process, exit_on_error,
441                               iofd);
442   if (result != -1)
443     fd[0] = iofd[1];
444   return result;
445 }