1/*	$NetBSD$	*/
2
3/*++
4/* NAME
5/*	open_limit 3
6/* SUMMARY
7/*	set/get open file limit
8/* SYNOPSIS
9/*	#include <iostuff.h>
10/*
11/*	int	open_limit(int limit)
12/* DESCRIPTION
13/*	The \fIopen_limit\fR() routine attempts to change the maximum
14/*	number of open files to the specified limit.  Specify a null
15/*	argument to effect no change. The result is the actual open file
16/*	limit for the current process. The number can be smaller or larger
17/*	than the requested limit.
18/* DIAGNOSTICS
19/*	open_limit() returns -1 in case of problems. The errno
20/*	variable gives hints about the nature of the problem.
21/* LICENSE
22/* .ad
23/* .fi
24/*	The Secure Mailer license must be distributed with this software.
25/* AUTHOR(S)
26/*	Wietse Venema
27/*	IBM T.J. Watson Research
28/*	P.O. Box 704
29/*	Yorktown Heights, NY 10598, USA
30/*--*/
31
32/* System libraries. */
33
34#include "sys_defs.h"
35#include <sys/time.h>
36#include <sys/resource.h>
37#include <errno.h>
38
39#ifdef USE_MAX_FILES_PER_PROC
40#include <sys/sysctl.h>
41#define MAX_FILES_PER_PROC      "kern.maxfilesperproc"
42#endif
43
44/* Application-specific. */
45
46#include "iostuff.h"
47
48 /*
49  * 44BSD compatibility.
50  */
51#ifndef RLIMIT_NOFILE
52#ifdef RLIMIT_OFILE
53#define RLIMIT_NOFILE RLIMIT_OFILE
54#endif
55#endif
56
57/* open_limit - set/query file descriptor limit */
58
59int     open_limit(int limit)
60{
61#ifdef RLIMIT_NOFILE
62    struct rlimit rl;
63#endif
64
65    if (limit < 0) {
66	errno = EINVAL;
67	return (-1);
68    }
69#ifdef RLIMIT_NOFILE
70    if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
71	return (-1);
72    if (limit > 0) {
73
74	/*
75	 * MacOSX incorrectly reports rlim_max as RLIM_INFINITY. The true
76	 * hard limit is finite and equals the kern.maxfilesperproc value.
77	 */
78#ifdef USE_MAX_FILES_PER_PROC
79	int     max_files_per_proc;
80	size_t  len = sizeof(max_files_per_proc);
81
82	if (sysctlbyname(MAX_FILES_PER_PROC, &max_files_per_proc, &len,
83			 (void *) 0, (size_t) 0) < 0)
84	    return (-1);
85	if (limit > max_files_per_proc)
86	    limit = max_files_per_proc;
87#endif
88	if (limit > rl.rlim_max)
89	    rl.rlim_cur = rl.rlim_max;
90	else
91	    rl.rlim_cur = limit;
92	if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
93	    return (-1);
94    }
95    return (rl.rlim_cur);
96#endif
97
98#ifndef RLIMIT_NOFILE
99    return (getdtablesize());
100#endif
101}
102
103