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