xapian-core  1.4.29
closefrom.cc
Go to the documentation of this file.
1 
4 /* Copyright (C) 2010,2011,2012,2016,2018,2019 Olly Betts
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include <config.h>
22 
23 // We don't currently need closefrom() on __WIN32__.
24 #if !defined HAVE_CLOSEFROM && !defined __WIN32__
25 
26 #include "closefrom.h"
27 
28 #include <cerrno>
29 #include "safefcntl.h"
30 #include "safeunistd.h"
31 
32 #ifdef HAVE_SYS_RESOURCE_H
33 # include <sys/types.h>
34 # include <sys/resource.h>
35 #endif
36 
37 #if defined __linux__
38 # include "alignment_cast.h"
39 # include "safedirent.h"
40 # include "parseint.h"
41 #elif defined __APPLE__
42 # include <sys/attr.h>
43 # include <cstring>
44 # include "parseint.h"
45 #endif
46 
47 static int
49 #ifdef F_MAXFD
50  // May only be supported by NetBSD, modern versions of which implement
51  // closefrom(). Leave this in so that if other platforms have it or add
52  // it they will benefit.
53  int maxfd = fcntl(0, F_MAXFD);
54  if (maxfd >= 0) return maxfd;
55 #endif
56 #ifdef HAVE_GETRLIMIT
57  struct rlimit rl;
58  if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
59  rl.rlim_max != RLIM_INFINITY) {
60  return static_cast<int>(rl.rlim_max) - 1;
61  }
62 #endif
63  return static_cast<int>(sysconf(_SC_OPEN_MAX)) - 1;
64 }
65 
66 // These platforms are known to provide closefrom():
67 // FreeBSD >= 8.0, NetBSD >= 3.0, OpenBSD >= 3.5, Solaris >= 9,
68 // Linux >= 5.9 with glibc >= 2.34
69 //
70 // These platforms are known to support fcntl() with F_CLOSEM:
71 // AIX, NetBSD >= 2.0
72 //
73 // These platforms have getdirentries() and a "magic" directory with an entry
74 // for each FD open in the current process:
75 // Linux (at least with glibc)
76 //
77 // These platforms have getdirentriesattr() and a "magic" directory with an
78 // entry for each FD open in the current process:
79 // macOS
80 //
81 // Other platforms just use a loop up to a limit obtained from
82 // fcntl(0, F_MAXFD), getrlimit(RLIMIT_NOFILE, ...), or sysconf(_SC_OPEN_MAX)
83 // - known examples:
84 // Android (bionic libc doesn't provide getdirentries())
85 
86 void
88 {
89  int maxfd = -1;
90 #ifdef F_CLOSEM
91  if (fcntl(fd, F_CLOSEM, 0) >= 0)
92  return;
93 #elif defined HAVE_GETDIRENTRIES && defined __linux__
94  const char* path = "/proc/self/fd";
95  int dir = open(path, O_RDONLY|O_DIRECTORY);
96  if (dir >= 0) {
97  off_t base = 0;
98  while (true) {
99  char buf[1024];
100  errno = 0;
101  // We use getdirentries() instead of opendir()/readdir() here
102  // because the latter can call malloc(), which isn't safe to do
103  // between fork() and exec() in a multi-threaded program.
104  ssize_t c = getdirentries(dir, buf, sizeof(buf), &base);
105  if (c == 0) {
106  close(dir);
107  return;
108  }
109  if (c < 0) {
110  // Fallback if getdirentries() fails.
111  break;
112  }
113  struct dirent* d;
114  for (ssize_t pos = 0; pos < c; pos += d->d_reclen) {
115  d = alignment_cast<struct dirent*>(buf + pos);
116  const char* leaf = d->d_name;
117  int n;
118  if (!parse_signed(leaf, n)) {
119  // Skip '.' and '..'.
120  continue;
121  }
122  if (n < fd) {
123  // FD below threshold.
124  continue;
125  }
126  if (n == dir) {
127  // Don't close the fd open on the directory.
128  continue;
129  }
130 
131  // Running under valgrind causes some entries above the
132  // reported RLIMIT_NOFILE value to appear in
133  // /proc/self/fd - see:
134  // https://bugs.kde.org/show_bug.cgi?id=191758
135  //
136  // If we try to close these, valgrind issues a warning about
137  // trying to close an invalid file descriptor. These entries
138  // start at 1024, so we check that value first so we can
139  // usually avoid having to read the fd limit when we're not
140  // running under valgrind.
141  if (n >= 1024) {
142  if (maxfd < 0)
143  maxfd = get_maxfd();
144  if (n > maxfd)
145  continue;
146  }
147 
148  // Retry on EINTR.
149  while (close(n) < 0 && errno == EINTR) { }
150  }
151  }
152  close(dir);
153  }
154 #elif defined __APPLE__ // macOS
155  const char* path = "/dev/fd";
156 #ifdef __LP64__
157  typedef unsigned int gdea_type;
158 #else
159  typedef unsigned long gdea_type;
160 #endif
161  int dir = open(path, O_RDONLY|O_DIRECTORY);
162  if (dir >= 0) {
163  gdea_type base = 0;
164  struct attrlist alist;
165  std::memset(&alist, 0, sizeof(alist));
166  alist.bitmapcount = ATTR_BIT_MAP_COUNT;
167  alist.commonattr = ATTR_CMN_NAME;
168  while (true) {
169  char buf[1024];
170  errno = 0;
171  // We use getdirentriesattr() instead of opendir()/readdir() here
172  // because the latter can call malloc(), which isn't safe to do
173  // between fork() and exec() in a multi-threaded program. We only
174  // want filename, but can't use getdirentries() because it's not
175  // available with 64-bit inode_t, which seems to be tied to LFS.
176  gdea_type count = sizeof(buf);
177  gdea_type new_state;
178  int r = getdirentriesattr(dir, &alist, buf, sizeof(buf),
179  &count, &base, &new_state, 0);
180  (void)new_state;
181  if (r < 0) {
182  // Fallback if getdirentriesattr() fails.
183  break;
184  }
185  char* p = buf;
186  while (count-- > 0) {
187  const char* leaf = p + sizeof(u_int32_t);
188  p += *static_cast<u_int32_t*>(static_cast<void*>(p));
189 
190  int n;
191  if (!parse_signed(leaf, n)) {
192  // Skip '.' and '..'.
193  continue;
194  }
195  if (n < fd) {
196  // FD below threshold.
197  continue;
198  }
199  if (n == dir) {
200  // Don't close the fd open on the directory.
201  continue;
202  }
203 
204  // Retry on EINTR.
205  while (close(n) < 0 && errno == EINTR) { }
206  }
207  if (r == 1) {
208  // We've had the last entry.
209  close(dir);
210  return;
211  }
212  }
213  close(dir);
214  }
215 #elif 0
216  // Some platforms have /proc/<pid>/fd but not /proc/self - if any such
217  // platforms don't have either closefrom() or F_CLOSEM but do have
218  // getdirentries() then this code can be used. AIX is an example of
219  // a platform of the former, but apparently has F_CLOSEM.
220  char path[6 + sizeof(pid_t) * 3 + 4];
221 # ifdef SNPRINTF
222  snprintf(path, sizeof(path), "/proc/%ld/fd", long(getpid()));
223  path[sizeof(path) - 1] = '\0';
224 # else
225  sprintf(path, "/proc/%ld/fd", long(getpid()));
226 # endif
227 #endif
228  if (maxfd < 0)
229  maxfd = get_maxfd();
230  while (fd <= maxfd) {
231  // Retry on EINTR; just ignore other errors (we'll get EBADF if fd
232  // isn't open so that's OK).
233  while (close(fd) < 0 && errno == EINTR) { }
234  ++fd;
235  }
236 }
237 
238 #endif
int close(FD &fd)
Definition: fd.h:63
Parse signed and unsigned type from string and check for trailing characters.
void closefrom(int fd)
Definition: closefrom.cc:87
Cast a pointer we know is suitably aligned.
Implementation of closefrom() function.
WritableDatabase open()
Construct a WritableDatabase object for a new, empty InMemory database.
Definition: dbfactory.h:104
include <dirent.h>, with alternative implementation for windows.
std::enable_if< std::is_const< typename std::remove_pointer< U >::type >::value, T >::type alignment_cast(U ptr)
Cast a pointer we know is suitably aligned.
char * d_name
Definition: msvc_dirent.h:36
static int get_maxfd()
Definition: closefrom.cc:48
bool parse_signed(const char *p, T &res)
Definition: parseint.h:43
<unistd.h>, but with compat.
include <fcntl.h>, but working around broken platforms.