Annotation of src/usr.bin/ssh/minfd.c, Revision 1.1
1.1 ! deraadt 1: /*
! 2:
! 3: minfd.c
! 4:
! 5: Author: David Mazieres <dm@lcs.mit.edu>
! 6: Contributed to be part of ssh.
! 7:
! 8: Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
! 9: All rights reserved
! 10:
! 11: Created: Tue Aug 22 17:25:30 1995 ylo
! 12:
! 13: */
! 14:
! 15: #include "includes.h"
! 16: RCSID("$Id: minfd.c,v 1.2 1999/05/04 11:58:51 bg Exp $");
! 17:
! 18: #include <sys/resource.h> /* Needed by fdlim.h */
! 19: #include "fdlim.h"
! 20: #include "minfd.h"
! 21:
! 22: #ifdef _PATH_BSHELL
! 23: #define DEFAULT_SHELL _PATH_BSHELL
! 24: #else
! 25: #define DEFAULT_SHELL "/bin/sh"
! 26: #endif
! 27:
! 28: static int
! 29: _get_permanent_fd(const char *shellpath)
! 30: {
! 31: const char *shell;
! 32: struct passwd *pwd;
! 33: int fdmin;
! 34: int fdlim;
! 35: int fd;
! 36: int i;
! 37:
! 38: if (!shellpath)
! 39: {
! 40: if (!shellpath)
! 41: shellpath = getenv("SHELL");
! 42: if (!shellpath)
! 43: if ((pwd = getpwuid(getuid())))
! 44: shellpath = pwd->pw_shell;
! 45: if (!shellpath)
! 46: shellpath = DEFAULT_SHELL;
! 47: }
! 48: if ((shell = strrchr(shellpath, '/')))
! 49: shell++;
! 50: else
! 51: shell = shellpath;
! 52:
! 53: for (i = 0; strcmp(mafd[i].shell, shell); i++)
! 54: if (i == MAFD_MAX - 1)
! 55: return -1;
! 56:
! 57: fdmin = mafd[i].fd;
! 58: fdlim = fdlim_get(0);
! 59:
! 60: if (fdmin < fdlim)
! 61: {
! 62: /* First try to find a file descriptor as high as possible without
! 63: upping the limit */
! 64: fd = fdlim - 1;
! 65: while (fd >= fdmin)
! 66: {
! 67: if (fcntl(fd, F_GETFL, NULL) < 0)
! 68: return fd;
! 69: fd--;
! 70: }
! 71: }
! 72:
! 73: fd = fdlim;
! 74: for (;;)
! 75: {
! 76: if (fdlim_set(fd + 1) < 0)
! 77: return -1;
! 78: if (fcntl(fd, F_GETFL, NULL) < 0)
! 79: break;
! 80: fd++;
! 81: }
! 82: return fd;
! 83: }
! 84:
! 85: int
! 86: get_permanent_fd(const char *shellpath)
! 87: {
! 88: static int fd = -2;
! 89:
! 90: if (fd >= -1)
! 91: return fd;
! 92: fd = _get_permanent_fd(shellpath);
! 93: if (fd < 0)
! 94: fd = -1;
! 95: return fd;
! 96: }