1 /* vi: set sw=4 ts=4: */
2 /*
3 * Sysctl 1.01 - A utility to read and manipulate the sysctl parameters
4 *
5 * Copyright 1999 George Staikos
6 *
7 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8 *
9 * Changelog:
10 * v1.01 - added -p <preload> to preload values from a file
11 * v1.01.1 - busybox applet aware by <solar@gentoo.org>
12 */
13 //config:config BB_SYSCTL
14 //config: bool "sysctl (7.4 kb)"
15 //config: default y
16 //config: help
17 //config: Configure kernel parameters at runtime.
18
19 //applet:IF_BB_SYSCTL(APPLET_NOEXEC(sysctl, sysctl, BB_DIR_SBIN, BB_SUID_DROP, sysctl))
20
21 //kbuild:lib-$(CONFIG_BB_SYSCTL) += sysctl.o
22
23 //usage:#define sysctl_trivial_usage
24 //usage: "[-enq] { -a | -p [FILE]... | [-w] [KEY[=VALUE]]... }"
25 //usage:#define sysctl_full_usage "\n\n"
26 //usage: "Show/set kernel parameters\n"
27 //usage: "\n -e Don't warn about unknown keys"
28 //usage: "\n -n Don't show key names"
29 //usage: "\n -q Quiet"
30 //usage: "\n -a Show all values"
31 /* Same as -a, no need to show it */
32 /* //usage: "\n -A Show all values in table form" */
33 //usage: "\n -p Set values from FILEs (default /etc/sysctl.conf)"
34 //usage: "\n -w Set values"
35 //usage:
36 //usage:#define sysctl_example_usage
37 //usage: "sysctl [-n] [-e] variable...\n"
38 //usage: "sysctl [-n] [-e] [-q] -w variable=value...\n"
39 //usage: "sysctl [-n] [-e] -a\n"
40 //usage: "sysctl [-n] [-e] [-q] -p file (default /etc/sysctl.conf)\n"
41 //usage: "sysctl [-n] [-e] -A\n"
42
43 #include "libbb.h"
44
45 enum {
46 FLAG_SHOW_KEYS = 1 << 0,
47 FLAG_SHOW_KEY_ERRORS = 1 << 1,
48 FLAG_TABLE_FORMAT = 1 << 2, /* not implemented */
49 FLAG_SHOW_ALL = 1 << 3,
50 FLAG_PRELOAD_FILE = 1 << 4,
51 /* NB: procps 3.2.8 does not require -w for KEY=VAL to work, it only rejects non-KEY=VAL form */
52 FLAG_WRITE = 1 << 5,
53 FLAG_QUIET = 1 << 6,
54 };
55 #define OPTION_STR "neAapwq"
56
sysctl_dots_to_slashes(char * name)57 static void sysctl_dots_to_slashes(char *name)
58 {
59 char *cptr, *last_good, *end, *slash;
60 char end_ch;
61
62 end = strchrnul(name, '=');
63
64 slash = strchrnul(name, '/');
65 if (slash < end
66 && strchrnul(name, '.') < slash
67 ) {
68 /* There are both dots and slashes, and 1st dot is
69 * before 1st slash.
70 * (IOW: not raw, unmangled a/b/c.d format)
71 *
72 * procps supports this syntax for names with dots:
73 * net.ipv4.conf.eth0/100.mc_forwarding
74 * (dots and slashes are simply swapped)
75 */
76 while (end != name) {
77 end--;
78 if (*end == '.') *end = '/';
79 else if (*end == '/') *end = '.';
80 }
81 return;
82 }
83 /* else: use our old behavior: */
84
85 /* Convert minimum number of '.' to '/' so that
86 * we end up with existing file's name.
87 *
88 * Example from bug 3894:
89 * net.ipv4.conf.eth0.100.mc_forwarding ->
90 * net/ipv4/conf/eth0.100/mc_forwarding
91 * NB: net/ipv4/conf/eth0/mc_forwarding *also exists*,
92 * therefore we must start from the end, and if
93 * we replaced even one . -> /, start over again,
94 * but never replace dots before the position
95 * where last replacement occurred.
96 *
97 * Another bug we later had is that
98 * net.ipv4.conf.eth0.100
99 * (without .mc_forwarding) was mishandled.
100 *
101 * To set up testing: modprobe 8021q; vconfig add eth0 100
102 */
103 end_ch = *end;
104 *end = '.'; /* trick the loop into trying full name too */
105
106 last_good = name - 1;
107 again:
108 cptr = end;
109 while (cptr > last_good) {
110 if (*cptr == '.') {
111 *cptr = '\0';
112 //bb_error_msg("trying:'%s'", name);
113 if (access(name, F_OK) == 0) {
114 *cptr = '/';
115 //bb_error_msg("replaced:'%s'", name);
116 last_good = cptr;
117 goto again;
118 }
119 *cptr = '.';
120 }
121 cptr--;
122 }
123 *end = end_ch;
124 }
125
sysctl_act_on_setting(char * setting)126 static int sysctl_act_on_setting(char *setting)
127 {
128 int fd, retval = EXIT_SUCCESS;
129 char *cptr, *outname;
130 char *value = value; /* for compiler */
131 bool writing = (option_mask32 & FLAG_WRITE);
132
133 outname = xstrdup(setting);
134
135 cptr = outname;
136 while (*cptr) {
137 if (*cptr == '/')
138 *cptr = '.';
139 else if (*cptr == '.')
140 *cptr = '/';
141 cptr++;
142 }
143
144 cptr = strchr(setting, '=');
145 if (cptr)
146 writing = 1;
147 if (writing) {
148 if (!cptr) {
149 bb_error_msg("error: '%s' must be of the form name=value",
150 outname);
151 retval = EXIT_FAILURE;
152 goto end;
153 }
154 value = cptr + 1; /* point to the value in name=value */
155 if (setting == cptr /* "name" can't be empty */
156 /* || !*value - WRONG: "sysctl net.ipv4.ip_local_reserved_ports=" is a valid syntax (clears the value) */
157 ) {
158 bb_error_msg("error: malformed setting '%s'", outname);
159 retval = EXIT_FAILURE;
160 goto end;
161 }
162 *cptr = '\0';
163 outname[cptr - setting] = '\0';
164 /* procps 3.2.7 actually uses these flags */
165 fd = open(setting, O_WRONLY|O_CREAT|O_TRUNC, 0666);
166 } else {
167 fd = open(setting, O_RDONLY);
168 }
169
170 if (fd < 0) {
171 switch (errno) {
172 case ENOENT:
173 if (option_mask32 & FLAG_SHOW_KEY_ERRORS)
174 bb_error_msg("error: '%s' is an unknown key", outname);
175 break;
176 case EACCES:
177 /* Happens for write-only settings, e.g. net.ipv6.route.flush */
178 if (!writing)
179 goto end;
180 /* fall through */
181 default:
182 bb_perror_msg("error %sing key '%s'",
183 writing ?
184 "sett" : "read",
185 outname);
186 break;
187 }
188 retval = EXIT_FAILURE;
189 goto end;
190 }
191
192 if (writing) {
193 //TODO: procps 3.2.7 writes "value\n", note trailing "\n"
194 xwrite_str(fd, value);
195 close(fd);
196 if (!(option_mask32 & FLAG_QUIET)) {
197 if (option_mask32 & FLAG_SHOW_KEYS)
198 printf("%s = ", outname);
199 puts(value);
200 }
201 } else {
202 char c;
203
204 value = cptr = xmalloc_read(fd, NULL);
205 close(fd);
206 if (value == NULL) {
207 bb_perror_msg("error reading key '%s'", outname);
208 retval = EXIT_FAILURE;
209 goto end;
210 }
211
212 /* dev.cdrom.info and sunrpc.transports, for example,
213 * are multi-line. Try "sysctl sunrpc.transports"
214 */
215 while ((c = *cptr) != '\0') {
216 if (option_mask32 & FLAG_SHOW_KEYS)
217 printf("%s = ", outname);
218 while (1) {
219 fputc(c, stdout);
220 cptr++;
221 if (c == '\n')
222 break;
223 c = *cptr;
224 if (c == '\0')
225 break;
226 }
227 }
228 free(value);
229 }
230 end:
231 free(outname);
232 return retval;
233 }
234
sysctl_act_recursive(const char * path)235 static int sysctl_act_recursive(const char *path)
236 {
237 struct stat buf;
238 int retval = 0;
239
240 if (!(option_mask32 & FLAG_WRITE)
241 && !strchr(path, '=') /* do not try to resurse on "var=val" */
242 && stat(path, &buf) == 0
243 && S_ISDIR(buf.st_mode)
244 ) {
245 struct dirent *entry;
246 DIR *dirp;
247
248 dirp = opendir(path);
249 if (dirp == NULL)
250 return -1;
251 while ((entry = readdir(dirp)) != NULL) {
252 char *next = concat_subpath_file(path, entry->d_name);
253 if (next == NULL)
254 continue; /* d_name is "." or ".." */
255 /* if path was ".", drop "./" prefix: */
256 retval |= sysctl_act_recursive((next[0] == '.' && next[1] == '/') ?
257 next + 2 : next);
258 free(next);
259 }
260 closedir(dirp);
261 } else {
262 char *name = xstrdup(path);
263 retval |= sysctl_act_on_setting(name);
264 free(name);
265 }
266
267 return retval;
268 }
269
270 /* Set sysctl's from a conf file. Format example:
271 * # Controls IP packet forwarding
272 * net.ipv4.ip_forward = 0
273 */
sysctl_handle_preload_file(const char * filename)274 static int sysctl_handle_preload_file(const char *filename)
275 {
276 char *token[2];
277 parser_t *parser;
278 int parse_flags;
279
280 parser = config_open(filename);
281 /* Must do it _after_ config_open(): */
282 xchdir("/proc/sys");
283
284 parse_flags = 0;
285 parse_flags &= ~PARSE_COLLAPSE; // NO (var==val is not var=val) - treat consecutive delimiters as one
286 parse_flags &= ~PARSE_TRIM; // NO - trim leading and trailing delimiters
287 parse_flags |= PARSE_GREEDY; // YES - last token takes entire remainder of the line
288 parse_flags &= ~PARSE_MIN_DIE; // NO - die if < min tokens found
289 parse_flags &= ~PARSE_EOL_COMMENTS; // NO (only first char) - comments are recognized even if not first char
290 parse_flags |= PARSE_ALT_COMMENTS;// YES - two comment chars: ';' and '#'
291 /* <space><tab><space>#comment is also comment, not strictly 1st char only */
292 parse_flags |= PARSE_WS_COMMENTS; // YES - comments are recognized even if there is whitespace before
293 while (config_read(parser, token, 2, 2, ";#=", parse_flags)) {
294 char *tp;
295
296 trim(token[1]);
297 tp = trim(token[0]);
298 sysctl_dots_to_slashes(token[0]);
299 /* ^^^converted in-place. tp still points to NUL */
300 /* now, add "=TOKEN1" */
301 *tp++ = '=';
302 overlapping_strcpy(tp, token[1]);
303
304 sysctl_act_on_setting(token[0]);
305 }
306 if (ENABLE_FEATURE_CLEAN_UP)
307 config_close(parser);
308 return 0;
309 }
310
311 int sysctl_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
sysctl_main(int argc UNUSED_PARAM,char ** argv)312 int sysctl_main(int argc UNUSED_PARAM, char **argv)
313 {
314 int retval;
315 int opt;
316
317 opt = getopt32(argv, "+" OPTION_STR); /* '+' - stop on first non-option */
318 argv += optind;
319 opt ^= (FLAG_SHOW_KEYS | FLAG_SHOW_KEY_ERRORS);
320 option_mask32 = opt;
321
322 if (opt & FLAG_PRELOAD_FILE) {
323 int cur_dir_fd;
324 option_mask32 |= FLAG_WRITE;
325 if (!*argv)
326 *--argv = (char*)"/etc/sysctl.conf";
327 cur_dir_fd = xopen(".", O_RDONLY | O_DIRECTORY);
328 do {
329 /* xchdir("/proc/sys") is inside */
330 sysctl_handle_preload_file(*argv);
331 xfchdir(cur_dir_fd); /* files can be relative, must restore cwd */
332 } while (*++argv);
333 return 0; /* procps-ng 3.3.10 does not flag parse errors */
334 }
335 xchdir("/proc/sys");
336 if (opt & (FLAG_TABLE_FORMAT | FLAG_SHOW_ALL)) {
337 return sysctl_act_recursive(".");
338 }
339
340 //TODO: if(!argv[0]) bb_show_usage() ?
341
342 retval = 0;
343 while (*argv) {
344 sysctl_dots_to_slashes(*argv);
345 retval |= sysctl_act_recursive(*argv);
346 argv++;
347 }
348
349 return retval;
350 }
351