fix another nonportable grep usage in scripts
[oweals/busybox.git] / procps / sysctl.c
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
14 //usage:#define sysctl_trivial_usage
15 //usage:       "[OPTIONS] [VALUE]..."
16 //usage:#define sysctl_full_usage "\n\n"
17 //usage:       "Configure kernel parameters at runtime\n"
18 //usage:     "\nOptions:"
19 //usage:     "\n        -n      Don't print key names"
20 //usage:     "\n        -e      Don't warn about unknown keys"
21 //usage:     "\n        -w      Change sysctl setting"
22 //usage:     "\n        -p FILE Load sysctl settings from FILE (default /etc/sysctl.conf)"
23 //usage:     "\n        -a      Display all values"
24 //usage:     "\n        -A      Display all values in table form"
25 //usage:
26 //usage:#define sysctl_example_usage
27 //usage:       "sysctl [-n] [-e] variable...\n"
28 //usage:       "sysctl [-n] [-e] -w variable=value...\n"
29 //usage:       "sysctl [-n] [-e] -a\n"
30 //usage:       "sysctl [-n] [-e] -p file        (default /etc/sysctl.conf)\n"
31 //usage:       "sysctl [-n] [-e] -A\n"
32
33 #include "libbb.h"
34
35 enum {
36         FLAG_SHOW_KEYS       = 1 << 0,
37         FLAG_SHOW_KEY_ERRORS = 1 << 1,
38         FLAG_TABLE_FORMAT    = 1 << 2, /* not implemented */
39         FLAG_SHOW_ALL        = 1 << 3,
40         FLAG_PRELOAD_FILE    = 1 << 4,
41         FLAG_WRITE           = 1 << 5,
42 };
43 #define OPTION_STR "neAapw"
44
45 static void sysctl_dots_to_slashes(char *name)
46 {
47         char *cptr, *last_good, *end;
48
49         /* Convert minimum number of '.' to '/' so that
50          * we end up with existing file's name.
51          *
52          * Example from bug 3894:
53          * net.ipv4.conf.eth0.100.mc_forwarding ->
54          * net/ipv4/conf/eth0.100/mc_forwarding
55          * NB: net/ipv4/conf/eth0/mc_forwarding *also exists*,
56          * therefore we must start from the end, and if
57          * we replaced even one . -> /, start over again,
58          * but never replace dots before the position
59          * where last replacement occurred.
60          *
61          * Another bug we later had is that
62          * net.ipv4.conf.eth0.100
63          * (without .mc_forwarding) was mishandled.
64          *
65          * To set up testing: modprobe 8021q; vconfig add eth0 100
66          */
67         end = name + strlen(name);
68         last_good = name - 1;
69         *end = '.'; /* trick the loop into trying full name too */
70
71  again:
72         cptr = end;
73         while (cptr > last_good) {
74                 if (*cptr == '.') {
75                         *cptr = '\0';
76                         //bb_error_msg("trying:'%s'", name);
77                         if (access(name, F_OK) == 0) {
78                                 *cptr = '/';
79                                 //bb_error_msg("replaced:'%s'", name);
80                                 last_good = cptr;
81                                 goto again;
82                         }
83                         *cptr = '.';
84                 }
85                 cptr--;
86         }
87         *end = '\0';
88 }
89
90 static int sysctl_act_on_setting(char *setting)
91 {
92         int fd, retval = EXIT_SUCCESS;
93         char *cptr, *outname;
94         char *value = value; /* for compiler */
95
96         outname = xstrdup(setting);
97
98         cptr = outname;
99         while (*cptr) {
100                 if (*cptr == '/')
101                         *cptr = '.';
102                 cptr++;
103         }
104
105         if (option_mask32 & FLAG_WRITE) {
106                 cptr = strchr(setting, '=');
107                 if (cptr == NULL) {
108                         bb_error_msg("error: '%s' must be of the form name=value",
109                                 outname);
110                         retval = EXIT_FAILURE;
111                         goto end;
112                 }
113                 value = cptr + 1;  /* point to the value in name=value */
114                 if (setting == cptr || !*value) {
115                         bb_error_msg("error: malformed setting '%s'", outname);
116                         retval = EXIT_FAILURE;
117                         goto end;
118                 }
119                 *cptr = '\0';
120                 outname[cptr - setting] = '\0';
121                 /* procps 3.2.7 actually uses these flags */
122                 fd = open(setting, O_WRONLY|O_CREAT|O_TRUNC, 0666);
123         } else {
124                 fd = open(setting, O_RDONLY);
125         }
126
127         if (fd < 0) {
128                 switch (errno) {
129                 case ENOENT:
130                         if (option_mask32 & FLAG_SHOW_KEY_ERRORS)
131                                 bb_error_msg("error: '%s' is an unknown key", outname);
132                         break;
133                 default:
134                         bb_perror_msg("error %sing key '%s'",
135                                         option_mask32 & FLAG_WRITE ?
136                                                 "sett" : "read",
137                                         outname);
138                         break;
139                 }
140                 retval = EXIT_FAILURE;
141                 goto end;
142         }
143
144         if (option_mask32 & FLAG_WRITE) {
145 //TODO: procps 3.2.7 writes "value\n", note trailing "\n"
146                 xwrite_str(fd, value);
147                 close(fd);
148                 if (option_mask32 & FLAG_SHOW_KEYS)
149                         printf("%s = ", outname);
150                 puts(value);
151         } else {
152                 char c;
153
154                 value = cptr = xmalloc_read(fd, NULL);
155                 close(fd);
156                 if (value == NULL) {
157                         bb_perror_msg("error reading key '%s'", outname);
158                         goto end;
159                 }
160
161                 /* dev.cdrom.info and sunrpc.transports, for example,
162                  * are multi-line. Try "sysctl sunrpc.transports"
163                  */
164                 while ((c = *cptr) != '\0') {
165                         if (option_mask32 & FLAG_SHOW_KEYS)
166                                 printf("%s = ", outname);
167                         while (1) {
168                                 fputc(c, stdout);
169                                 cptr++;
170                                 if (c == '\n')
171                                         break;
172                                 c = *cptr;
173                                 if (c == '\0')
174                                         break;
175                         }
176                 }
177                 free(value);
178         }
179  end:
180         free(outname);
181         return retval;
182 }
183
184 static int sysctl_act_recursive(const char *path)
185 {
186         DIR *dirp;
187         struct stat buf;
188         struct dirent *entry;
189         char *next;
190         int retval = 0;
191
192         stat(path, &buf);
193         if (S_ISDIR(buf.st_mode) && !(option_mask32 & FLAG_WRITE)) {
194                 dirp = opendir(path);
195                 if (dirp == NULL)
196                         return -1;
197                 while ((entry = readdir(dirp)) != NULL) {
198                         next = concat_subpath_file(path, entry->d_name);
199                         if (next == NULL)
200                                 continue; /* d_name is "." or ".." */
201                         /* if path was ".", drop "./" prefix: */
202                         retval |= sysctl_act_recursive((next[0] == '.' && next[1] == '/') ?
203                                             next + 2 : next);
204                         free(next);
205                 }
206                 closedir(dirp);
207         } else {
208                 char *name = xstrdup(path);
209                 retval |= sysctl_act_on_setting(name);
210                 free(name);
211         }
212
213         return retval;
214 }
215
216 /* Set sysctl's from a conf file. Format example:
217  * # Controls IP packet forwarding
218  * net.ipv4.ip_forward = 0
219  */
220 static int sysctl_handle_preload_file(const char *filename)
221 {
222         char *token[2];
223         parser_t *parser;
224
225         parser = config_open(filename);
226         /* Must do it _after_ config_open(): */
227         xchdir("/proc/sys");
228         /* xchroot(".") - if you are paranoid */
229
230 //TODO: ';' is comment char too
231 //TODO: comment may be only at line start. "var=1 #abc" - "1 #abc" is the value
232 // (but _whitespace_ from ends should be trimmed first (and we do it right))
233 //TODO: "var==1" is mishandled (must use "=1" as a value, but uses "1")
234 // can it be fixed by removing PARSE_COLLAPSE bit?
235         while (config_read(parser, token, 2, 2, "# \t=", PARSE_NORMAL)) {
236                 char *tp;
237                 sysctl_dots_to_slashes(token[0]);
238                 tp = xasprintf("%s=%s", token[0], token[1]);
239                 sysctl_act_recursive(tp);
240                 free(tp);
241         }
242         if (ENABLE_FEATURE_CLEAN_UP)
243                 config_close(parser);
244         return 0;
245 }
246
247 int sysctl_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
248 int sysctl_main(int argc UNUSED_PARAM, char **argv)
249 {
250         int retval;
251         int opt;
252
253         opt = getopt32(argv, "+" OPTION_STR); /* '+' - stop on first non-option */
254         argv += optind;
255         opt ^= (FLAG_SHOW_KEYS | FLAG_SHOW_KEY_ERRORS);
256         option_mask32 = opt;
257
258         if (opt & FLAG_PRELOAD_FILE) {
259                 option_mask32 |= FLAG_WRITE;
260                 /* xchdir("/proc/sys") is inside */
261                 return sysctl_handle_preload_file(*argv ? *argv : "/etc/sysctl.conf");
262         }
263         xchdir("/proc/sys");
264         /* xchroot(".") - if you are paranoid */
265         if (opt & (FLAG_TABLE_FORMAT | FLAG_SHOW_ALL)) {
266                 return sysctl_act_recursive(".");
267         }
268
269         retval = 0;
270         while (*argv) {
271                 sysctl_dots_to_slashes(*argv);
272                 retval |= sysctl_act_recursive(*argv);
273                 argv++;
274         }
275
276         return retval;
277 }