- jmc@cvs.openbsd.org 2006/07/18 08:03:09
[openssh-git.git] / openbsd-compat / bsd-closefrom.c
blob7509d2835e7e47a7b62c3288e0c012ee82040d6b
1 /*
2 * Copyright (c) 2004 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.
17 #include "includes.h"
19 #ifndef HAVE_CLOSEFROM
21 #include <sys/types.h>
22 #include <sys/param.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <stddef.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 # define NAMLEN(dirent) strlen((dirent)->d_name)
31 #else
32 # define dirent direct
33 # define NAMLEN(dirent) (dirent)->d_namlen
34 # ifdef HAVE_SYS_NDIR_H
35 # include <sys/ndir.h>
36 # endif
37 # ifdef HAVE_SYS_DIR_H
38 # include <sys/dir.h>
39 # endif
40 # ifdef HAVE_NDIR_H
41 # include <ndir.h>
42 # endif
43 #endif
45 #ifndef OPEN_MAX
46 # define OPEN_MAX 256
47 #endif
49 #ifndef lint
50 static const char sudorcsid[] = "$Sudo: closefrom.c,v 1.6 2004/06/01 20:51:56 millert Exp $";
51 #endif /* lint */
54 * Close all file descriptors greater than or equal to lowfd.
56 void
57 closefrom(int lowfd)
59 long fd, maxfd;
60 #if defined(HAVE_DIRFD) && defined(HAVE_PROC_PID)
61 char fdpath[PATH_MAX], *endp;
62 struct dirent *dent;
63 DIR *dirp;
64 int len;
66 /* Check for a /proc/$$/fd directory. */
67 len = snprintf(fdpath, sizeof(fdpath), "/proc/%ld/fd", (long)getpid());
68 if (len >= 0 && (u_int)len <= sizeof(fdpath) && (dirp = opendir(fdpath))) {
69 while ((dent = readdir(dirp)) != NULL) {
70 fd = strtol(dent->d_name, &endp, 10);
71 if (dent->d_name != endp && *endp == '\0' &&
72 fd >= 0 && fd < INT_MAX && fd >= lowfd && fd != dirfd(dirp))
73 (void) close((int) fd);
75 (void) closedir(dirp);
76 } else
77 #endif
80 * Fall back on sysconf() or getdtablesize(). We avoid checking
81 * resource limits since it is possible to open a file descriptor
82 * and then drop the rlimit such that it is below the open fd.
84 #ifdef HAVE_SYSCONF
85 maxfd = sysconf(_SC_OPEN_MAX);
86 #else
87 maxfd = getdtablesize();
88 #endif /* HAVE_SYSCONF */
89 if (maxfd < 0)
90 maxfd = OPEN_MAX;
92 for (fd = lowfd; fd < maxfd; fd++)
93 (void) close((int) fd);
97 #endif /* HAVE_CLOSEFROM */