]> git.cworth.org Git - tar/blob - lib/stdopen.c
upstream: Fix extraction of device nodes.
[tar] / lib / stdopen.c
1 /* stdopen.c - ensure that the three standard file descriptors are in use
2
3    Copyright (C) 2005, 2007 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, or (at your option)
8    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, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* Written by Paul Eggert and Jim Meyering.  */
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include "stdopen.h"
26
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <errno.h>
32
33 /* Try to ensure that all of the standard file numbers (0, 1, 2)
34    are in use.  Without this, each application would have to guard
35    every call to open, dup, fopen, etc. with tests to ensure they
36    don't use one of the special file numbers when opening a file.
37    Return false if at least one of the file descriptors is initially
38    closed and an attempt to reopen it fails.  Otherwise, return true.  */
39 bool
40 stdopen (void)
41 {
42   int fd;
43   bool ok = true;
44
45   for (fd = 0; fd <= 2; fd++)
46     {
47       if (fcntl (fd, F_GETFD) < 0)
48         {
49           if (errno != EBADF)
50             ok = false;
51           else
52             {
53               static const int contrary_mode[]
54                 = { O_WRONLY, O_RDONLY, O_RDONLY };
55               int mode = contrary_mode[fd];
56               int new_fd;
57               /* Open /dev/null with the contrary mode so that the typical
58                  read (stdin) or write (stdout, stderr) operation will fail.
59                  With descriptor 0, we can do even better on systems that
60                  have /dev/full, by opening that write-only instead of
61                  /dev/null.  The only drawback is that a write-provoked
62                  failure comes with a misleading errno value, ENOSPC.  */
63               if (mode == O_RDONLY
64                   || (new_fd = open ("/dev/full", mode) != fd))
65                 new_fd = open ("/dev/null", mode);
66               if (new_fd != fd)
67                 {
68                   if (0 <= new_fd)
69                     close (new_fd);
70                   ok = false;
71                 }
72             }
73         }
74     }
75
76   return ok;
77 }