2 * Copyright (c) 2004-2005, 2007
3 * Todd C. Miller <Todd.Miller@courtesan.com>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include <sys/types.h>
21 #include <sys/param.h>
31 #endif /* STDC_HEADERS */
35 # define NAMLEN(dirent) strlen((dirent)->d_name)
37 # define dirent direct
38 # define NAMLEN(dirent) (dirent)->d_namlen
39 # ifdef HAVE_SYS_NDIR_H
40 # include <sys/ndir.h>
42 # ifdef HAVE_SYS_DIR_H
53 __unused static const char rcsid[] = "$Sudo: closefrom.c,v 1.14 2008/11/09 14:13:12 millert Exp $";
56 #ifndef HAVE_FCNTL_CLOSEM
58 # define closefrom_fallback closefrom
63 * Close all file descriptors greater than or equal to lowfd.
64 * This is the expensive (ballback) method.
67 closefrom_fallback(lowfd)
73 * Fall back on sysconf() or getdtablesize(). We avoid checking
74 * resource limits since it is possible to open a file descriptor
75 * and then drop the rlimit such that it is below the open fd.
78 maxfd = sysconf(_SC_OPEN_MAX);
80 maxfd = getdtablesize();
81 #endif /* HAVE_SYSCONF */
85 for (fd = lowfd; fd < maxfd; fd++)
86 (void) close((int) fd);
90 * Close all file descriptors greater than or equal to lowfd.
91 * We try the fast way first, falling back on the slow method.
93 #ifdef HAVE_FCNTL_CLOSEM
98 if (fcntl(lowfd, F_CLOSEM, 0) == -1)
99 closefrom_fallback(lowfd);
112 /* Use /proc/self/fd directory if it exists. */
113 if ((dirp = opendir("/proc/self/fd")) != NULL) {
114 while ((dent = readdir(dirp)) != NULL) {
115 fd = strtol(dent->d_name, &endp, 10);
116 if (dent->d_name != endp && *endp == '\0' &&
117 fd >= 0 && fd < INT_MAX && fd >= lowfd && fd != dirfd(dirp))
118 (void) close((int) fd);
120 (void) closedir(dirp);
122 closefrom_fallback(lowfd);
124 #endif /* HAVE_DIRFD */
125 #endif /* HAVE_FCNTL_CLOSEM */