summaryrefslogtreecommitdiffstats
path: root/src/lib/restrict-process-size.c
blob: 018147376122449b1db171a1456ccd2a613c8997 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* Copyright (c) 2002-2018 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "restrict-process-size.h"

#include <unistd.h>

void restrict_process_size(rlim_t bytes)
{
	struct rlimit rlim;

	rlim.rlim_max = rlim.rlim_cur = bytes;
	if (setrlimit(RLIMIT_DATA, &rlim) < 0) {
		i_fatal("setrlimit(RLIMIT_DATA, %llu): %m",
			(unsigned long long)bytes);
	}

#ifdef HAVE_RLIMIT_AS
	if (setrlimit(RLIMIT_AS, &rlim) < 0) {
		i_fatal("setrlimit(RLIMIT_AS, %llu): %m",
			(unsigned long long)bytes);
	}
#endif
}

void restrict_process_count(rlim_t count ATTR_UNUSED)
{
#ifdef HAVE_RLIMIT_NPROC
	struct rlimit rlim;

	rlim.rlim_max = rlim.rlim_cur = count;
	if (setrlimit(RLIMIT_NPROC, &rlim) < 0) {
		i_error("setrlimit(RLIMIT_NPROC, %llu): %m",
			(unsigned long long)count);
	}
#endif
}

void restrict_fd_limit(rlim_t count)
{
#ifdef HAVE_SETRLIMIT
	struct rlimit rlim;

	rlim.rlim_cur = rlim.rlim_max = count;
	if (setrlimit(RLIMIT_NOFILE, &rlim) < 0) {
		i_error("setrlimit(RLIMIT_NOFILE, %llu): %m",
			(unsigned long long)count);
	}
#endif
}

int restrict_get_process_size(rlim_t *limit_r)
{
	struct rlimit rlim;

#ifdef HAVE_RLIMIT_AS
	if (getrlimit(RLIMIT_AS, &rlim) < 0) {
		i_error("getrlimit(RLIMIT_AS): %m");
		return -1;
	}
#else
	if (getrlimit(RLIMIT_DATA, &rlim) < 0) {
		i_error("getrlimit(RLIMIT_DATA): %m");
		return -1;
	}
#endif
	*limit_r = rlim.rlim_cur;
	return 0;
}

int restrict_get_core_limit(rlim_t *limit_r)
{
#ifdef HAVE_RLIMIT_CORE
	struct rlimit rlim;

	if (getrlimit(RLIMIT_CORE, &rlim) < 0) {
		i_error("getrlimit(RLIMIT_CORE) failed: %m");
		return -1;
	}
	*limit_r = rlim.rlim_cur;
	return 0;
#else
	return -1;
#endif
}

int restrict_get_process_limit(rlim_t *limit_r)
{
#ifdef HAVE_RLIMIT_NPROC
	struct rlimit rlim;

	if (getrlimit(RLIMIT_NPROC, &rlim) < 0) {
		i_error("getrlimit(RLIMIT_NPROC) failed: %m");
		return -1;
	}
	*limit_r = rlim.rlim_cur;
	return 0;
#else
	return -1;
#endif
}

int restrict_get_fd_limit(rlim_t *limit_r)
{
	struct rlimit rlim;

	if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
		i_error("getrlimit(RLIMIT_NOFILE) failed: %m");
		return -1;
	}
	*limit_r = rlim.rlim_cur;
	return 0;
}