popen-safer: prevent popen from clobbering std descriptors
[gnulib.git] / lib / popen-safer.c
1 /* Invoke popen, but avoid some glitches.
2
3    Copyright (C) 2009 Free Software Foundation, Inc.
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 /* Written by Eric Blake.  */
19
20 #include <config.h>
21
22 #include "stdio-safer.h"
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27
28 #include "cloexec.h"
29
30 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
31 # define O_CLOEXEC O_NOINHERIT
32 #elif !defined O_CLOEXEC
33 # define O_CLOEXEC 0
34 #endif
35
36 /* Like open (name, flags | O_CLOEXEC), although not necessarily
37    atomic.  FLAGS must not include O_CREAT.  */
38
39 static int
40 open_noinherit (char const *name, int flags)
41 {
42   int fd = open (name, flags | O_CLOEXEC);
43   if (0 <= fd && !O_CLOEXEC && set_cloexec_flag (fd, true) != 0)
44     {
45       int saved_errno = errno;
46       close (fd);
47       fd = -1;
48       errno = saved_errno;
49     }
50   return fd;
51 }
52
53 /* Like popen, but do not return stdin, stdout, or stderr.  */
54
55 FILE *
56 popen_safer (char const *cmd, char const *mode)
57 {
58   /* Unfortunately, we cannot use the fopen_safer approach of using
59      fdopen (dup_safer (fileno (popen (cmd, mode)))), because stdio
60      libraries maintain hidden state tying the original fd to the pid
61      to wait on when using pclose (this hidden state is also used to
62      avoid fd leaks in subsequent popen calls).  So, we instead
63      guarantee that all standard streams are open prior to the popen
64      call (even though this puts more pressure on open fds), so that
65      the original fd created by popen is safe.  */
66   FILE *fp;
67   int fd = open_noinherit ("/dev/null", O_RDONLY);
68   if (0 <= fd && fd <= STDERR_FILENO)
69     {
70       /* Maximum recursion depth is 3.  */
71       int saved_errno;
72       fp = popen_safer (cmd, mode);
73       saved_errno = errno;
74       close (fd);
75       errno = saved_errno;
76     }
77   else
78     {
79       /* Either all fd's are tied up, or fd is safe and the real popen
80          will reuse it.  */
81       close (fd);
82       fp = popen (cmd, mode);
83     }
84   return fp;
85 }