xref: /freebsd/sbin/sysctl/sysctl.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
1 /*
2  * Copyright (c) 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)from: sysctl.c	8.1 (Berkeley) 6/6/93";
43 #endif
44 static const char rcsid[] =
45 	"$Id: sysctl.c,v 1.17 1998/06/29 17:54:29 bde Exp $";
46 #endif /* not lint */
47 
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <sys/sysctl.h>
51 #include <sys/resource.h>
52 
53 #include <ctype.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 
61 static int	Aflag, aflag, nflag, wflag, Xflag, bflag;
62 
63 static int	oidfmt(int *, int, char *, u_int *);
64 static void	parse(char *);
65 static int	show_var(int *, int);
66 static int	sysctl_all (int *oid, int len);
67 static int	name2oid(char *, int *);
68 
69 static void
70 usage(void)
71 {
72 
73 	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
74 		"usage: sysctl [-bnX] variable ...",
75 		"       sysctl [-bnX] -w variable=value ...",
76 		"       sysctl [-bnX] -a",
77 		"       sysctl [-bnX] -A");
78 	exit(1);
79 }
80 
81 int
82 main(int argc, char **argv)
83 {
84 	int ch;
85 	setbuf(stdout,0);
86 	setbuf(stderr,0);
87 
88 	while ((ch = getopt(argc, argv, "AabnwX")) != -1) {
89 		switch (ch) {
90 		case 'A': Aflag = 1; break;
91 		case 'a': aflag = 1; break;
92 		case 'b': bflag = 1; break;
93 		case 'n': nflag = 1; break;
94 		case 'w': wflag = 1; break;
95 		case 'X': Xflag = Aflag = 1; break;
96 		default: usage();
97 		}
98 	}
99 	argc -= optind;
100 	argv += optind;
101 
102 	if (Aflag || aflag)
103 		exit (sysctl_all(0, 0));
104 	if (argc == 0)
105 		usage();
106 	while (argc-- > 0)
107 		parse(*argv++);
108 	exit(0);
109 }
110 
111 /*
112  * Parse a name into a MIB entry.
113  * Lookup and print out the MIB entry if it exists.
114  * Set a new value if requested.
115  */
116 static void
117 parse(char *string)
118 {
119 	int len, i, j;
120 	void *newval = 0;
121 	int intval, newsize = 0;
122 	quad_t quadval;
123 	int mib[CTL_MAXNAME];
124 	char *cp, *bufp, buf[BUFSIZ];
125 	u_int kind;
126 
127 	bufp = buf;
128 	snprintf(buf, BUFSIZ, "%s", string);
129 	if ((cp = strchr(string, '=')) != NULL) {
130 		if (!wflag)
131 			errx(2, "must specify -w to set variables");
132 		*strchr(buf, '=') = '\0';
133 		*cp++ = '\0';
134 		while (isspace(*cp))
135 			cp++;
136 		newval = cp;
137 		newsize = strlen(cp);
138 	} else {
139 		if (wflag)
140 			usage();
141 	}
142 	len = name2oid(bufp, mib);
143 
144 	if (len < 0)
145 		errx(1, "unknown oid '%s'", bufp);
146 
147 	if (oidfmt(mib, len, 0, &kind))
148 		err(1, "couldn't find format of oid '%s'", bufp);
149 
150 	if (!wflag) {
151 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
152 			sysctl_all(mib, len);
153 		} else {
154 			i = show_var(mib, len);
155 			if (!i && !bflag)
156 				putchar('\n');
157 		}
158 	} else {
159 		if ((kind & CTLTYPE) == CTLTYPE_NODE)
160 			errx(1, "oid '%s' isn't a leaf node", bufp);
161 
162 		if (!(kind&CTLFLAG_WR))
163 			errx(1, "oid '%s' is read only", bufp);
164 
165 		switch (kind & CTLTYPE) {
166 			case CTLTYPE_INT:
167 				intval = atoi(newval);
168 				newval = &intval;
169 				newsize = sizeof intval;
170 				break;
171 				break;
172 			case CTLTYPE_STRING:
173 				break;
174 			case CTLTYPE_QUAD:
175 				break;
176 				sscanf(newval, "%qd", &quadval);
177 				newval = &quadval;
178 				newsize = sizeof quadval;
179 				break;
180 			default:
181 				errx(1, "oid '%s' is type %d,"
182 					" cannot set that", bufp,
183 					kind & CTLTYPE);
184 		}
185 
186 		i = show_var(mib, len);
187 		if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
188 			if (!i && !bflag)
189 				putchar('\n');
190 			switch (errno) {
191 			case EOPNOTSUPP:
192 				errx(1, "%s: value is not available",
193 					string);
194 			case ENOTDIR:
195 				errx(1, "%s: specification is incomplete",
196 					string);
197 			case ENOMEM:
198 				errx(1, "%s: type is unknown to this program",
199 					string);
200 			default:
201 				warn("%s", string);
202 				return;
203 			}
204 		}
205 		if (!bflag)
206 			printf(" -> ");
207 		i = nflag;
208 		nflag = 1;
209 		j = show_var(mib, len);
210 		if (!j && !bflag)
211 			putchar('\n');
212 		nflag = i;
213 	}
214 }
215 
216 /* These functions will dump out various interesting structures. */
217 
218 static int
219 S_clockinfo(int l2, void *p)
220 {
221 	struct clockinfo *ci = (struct clockinfo*)p;
222 	if (l2 != sizeof *ci)
223 		err(1, "S_clockinfo %d != %d", l2, sizeof *ci);
224 	printf("{ hz = %d, tick = %d, tickadj = %d, profhz = %d, stathz = %d }",
225 		ci->hz, ci->tick, ci->tickadj, ci->profhz, ci->stathz);
226 	return (0);
227 }
228 
229 static int
230 S_loadavg(int l2, void *p)
231 {
232 	struct loadavg *tv = (struct loadavg*)p;
233 
234 	if (l2 != sizeof *tv)
235 		err(1, "S_loadavg %d != %d", l2, sizeof *tv);
236 
237 	printf("{ %.2f %.2f %.2f }",
238 		(double)tv->ldavg[0]/(double)tv->fscale,
239 		(double)tv->ldavg[1]/(double)tv->fscale,
240 		(double)tv->ldavg[2]/(double)tv->fscale);
241 	return (0);
242 }
243 
244 static int
245 S_timeval(int l2, void *p)
246 {
247 	struct timeval *tv = (struct timeval*)p;
248 	time_t tv_sec;
249 	char *p1, *p2;
250 
251 	if (l2 != sizeof *tv)
252 		err(1, "S_timeval %d != %d", l2, sizeof *tv);
253 	printf("{ sec = %ld, usec = %ld } ",
254 		tv->tv_sec, tv->tv_usec);
255 	tv_sec = tv->tv_sec;
256 	p1 = strdup(ctime(&tv_sec));
257 	for (p2=p1; *p2 ; p2++)
258 		if (*p2 == '\n')
259 			*p2 = '\0';
260 	fputs(p1, stdout);
261 	return (0);
262 }
263 
264 static int
265 T_dev_t(int l2, void *p)
266 {
267 	dev_t *d = (dev_t *)p;
268 	if (l2 != sizeof *d)
269 		err(1, "T_dev_T %d != %d", l2, sizeof *d);
270 	printf("{ major = %d, minor = %d }",
271 		major(*d), minor(*d));
272 	return (0);
273 }
274 
275 /*
276  * These functions uses a presently undocumented interface to the kernel
277  * to walk the tree and get the type so it can print the value.
278  * This interface is under work and consideration, and should probably
279  * be killed with a big axe by the first person who can find the time.
280  * (be aware though, that the proper interface isn't as obvious as it
281  * may seem, there are various conflicting requirements.
282  */
283 
284 static int
285 name2oid(char *name, int *oidp)
286 {
287 	int oid[2];
288 	int i;
289 	size_t j;
290 
291 	oid[0] = 0;
292 	oid[1] = 3;
293 
294 	j = CTL_MAXNAME * sizeof (int);
295 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
296 	if (i < 0)
297 		return i;
298 	j /= sizeof (int);
299 	return (j);
300 }
301 
302 static int
303 oidfmt(int *oid, int len, char *fmt, u_int *kind)
304 {
305 	int qoid[CTL_MAXNAME+2];
306 	u_char buf[BUFSIZ];
307 	int i;
308 	size_t j;
309 
310 	qoid[0] = 0;
311 	qoid[1] = 4;
312 	memcpy(qoid + 2, oid, len * sizeof(int));
313 
314 	j = sizeof buf;
315 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
316 	if (i)
317 		err(1, "sysctl fmt %d %d %d", i, j, errno);
318 
319 	if (kind)
320 		*kind = *(u_int *)buf;
321 
322 	if (fmt)
323 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
324 	return 0;
325 }
326 
327 /*
328  * This formats and outputs the value of one variable
329  *
330  * Returns zero if anything was actually output.
331  * Returns one if didn't know what to do with this.
332  * Return minus one if we had errors.
333  */
334 
335 static int
336 show_var(int *oid, int nlen)
337 {
338 	u_char buf[BUFSIZ], *val, *p;
339 	char name[BUFSIZ], *fmt;
340 	int qoid[CTL_MAXNAME+2];
341 	int i;
342 	size_t j, len;
343 	u_int kind;
344 	int (*func)(int, void *) = 0;
345 
346 	/* find an estimate of how much we need for this var */
347 	j = 0;
348 	i = sysctl(oid, nlen, 0, &j, 0, 0);
349 	j += j; /* we want to be sure :-) */
350 
351 	val = alloca(j);
352 	len = j;
353 	i = sysctl(oid, nlen, val, &len, 0, 0);
354 	if (i || !len)
355 		return (1);
356 
357 	if (bflag) {
358 		fwrite(val, 1, len, stdout);
359 		return (0);
360 	}
361 
362 	qoid[0] = 0;
363 	qoid[1] = 4;
364 	memcpy(qoid + 2, oid, nlen * sizeof(int));
365 
366 	j = sizeof buf;
367 	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
368 	if (i || !j)
369 		err(1, "sysctl fmt %d %d %d", i, j, errno);
370 
371 	kind = *(u_int *)buf;
372 
373 	fmt = (char *)(buf + sizeof(u_int));
374 
375 	qoid[1] = 1;
376 	j = sizeof name;
377 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
378 	if (i || !j)
379 		err(1, "sysctl name %d %d %d", i, j, errno);
380 
381 	p = val;
382 	switch (*fmt) {
383 	case 'A':
384 		if (!nflag)
385 			printf("%s: ", name);
386 		printf("%s", p);
387 		return (0);
388 
389 	case 'I':
390 		if (!nflag)
391 			printf("%s: ", name);
392 		printf("%d", *(int *)p);
393 		return (0);
394 
395 	case 'L':
396 		if (!nflag)
397 			printf("%s: ", name);
398 		printf("%ld", *(long *)p);
399 		return (0);
400 
401 	case 'P':
402 		if (!nflag)
403 			printf("%s: ", name);
404 		printf("%p", *(void **)p);
405 		return (0);
406 
407 	case 'T':
408 	case 'S':
409 		i = 0;
410 		if (!strcmp(fmt, "S,clockinfo"))	func = S_clockinfo;
411 		else if (!strcmp(fmt, "S,timeval"))	func = S_timeval;
412 		else if (!strcmp(fmt, "S,loadavg"))	func = S_loadavg;
413 		else if (!strcmp(fmt, "T,dev_t"))	func = T_dev_t;
414 		if (func) {
415 			if (!nflag)
416 				printf("%s: ", name);
417 			return ((*func)(len, p));
418 		}
419 		/* FALL THROUGH */
420 	default:
421 		if (!Aflag)
422 			return (1);
423 		if (!nflag)
424 			printf("%s: ", name);
425 		printf("Format:%s Length:%d Dump:0x", fmt, len);
426 		while (len--) {
427 			printf("%02x", *p++);
428 			if (Xflag || p < val+16)
429 				continue;
430 			printf("...");
431 			break;
432 		}
433 		return (0);
434 	}
435 	return (1);
436 }
437 
438 static int
439 sysctl_all (int *oid, int len)
440 {
441 	int name1[22], name2[22];
442 	int i, j;
443 	size_t l1, l2;
444 
445 	name1[0] = 0;
446 	name1[1] = 2;
447 	l1 = 2;
448 	if (len) {
449 		memcpy(name1+2, oid, len*sizeof (int));
450 		l1 += len;
451 	} else {
452 		name1[2] = 1;
453 		l1++;
454 	}
455 	while (1) {
456 		l2 = sizeof name2;
457 		j = sysctl(name1, l1, name2, &l2, 0, 0);
458 		if (j < 0)
459 			if (errno == ENOENT)
460 				return 0;
461 			else
462 				err(1, "sysctl(getnext) %d %d", j, l2);
463 
464 		l2 /= sizeof (int);
465 
466 		if (l2 < len)
467 			return 0;
468 
469 		for (i = 0; i < len; i++)
470 			if (name2[i] != oid[i])
471 				return 0;
472 
473 		i = show_var(name2, l2);
474 		if (!i && !bflag)
475 			putchar('\n');
476 
477 		memcpy(name1+2, name2, l2*sizeof (int));
478 		l1 = 2 + l2;
479 	}
480 }
481