Move more flags to lib/fcntl.in.h.
[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 #ifndef O_CLOEXEC
31 # define O_CLOEXEC 0
32 #endif
33
34 /* Like open (name, flags | O_CLOEXEC), although not necessarily
35    atomic.  FLAGS must not include O_CREAT.  */
36
37 static int
38 open_noinherit (char const *name, int flags)
39 {
40   int fd = open (name, flags | O_CLOEXEC);
41   if (0 <= fd && !O_CLOEXEC && set_cloexec_flag (fd, true) != 0)
42     {
43       int saved_errno = errno;
44       close (fd);
45       fd = -1;
46       errno = saved_errno;
47     }
48   return fd;
49 }
50
51 /* Like popen, but do not return stdin, stdout, or stderr.  */
52
53 FILE *
54 popen_safer (char const *cmd, char const *mode)
55 {
56   /* Unfortunately, we cannot use the fopen_safer approach of using
57      fdopen (dup_safer (fileno (popen (cmd, mode)))), because stdio
58      libraries maintain hidden state tying the original fd to the pid
59      to wait on when using pclose (this hidden state is also used to
60      avoid fd leaks in subsequent popen calls).  So, we instead
61      guarantee that all standard streams are open prior to the popen
62      call (even though this puts more pressure on open fds), so that
63      the original fd created by popen is safe.  */
64   FILE *fp;
65   int fd = open_noinherit ("/dev/null", O_RDONLY);
66   if (0 <= fd && fd <= STDERR_FILENO)
67     {
68       /* Maximum recursion depth is 3.  */
69       int saved_errno;
70       fp = popen_safer (cmd, mode);
71       saved_errno = errno;
72       close (fd);
73       errno = saved_errno;
74     }
75   else
76     {
77       /* Either all fd's are tied up, or fd is safe and the real popen
78          will reuse it.  */
79       close (fd);
80       fp = popen (cmd, mode);
81     }
82   return fp;
83 }