sysctl.c revision 67476
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
35static 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
42static char sccsid[] = "@(#)from: sysctl.c	8.1 (Berkeley) 6/6/93";
43#endif
44static const char rcsid[] =
45  "$FreeBSD: head/sbin/sysctl/sysctl.c 67476 2000-10-23 21:04:18Z gallatin $";
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
61static int	Aflag, aflag, bflag, nflag, wflag, Xflag;
62
63static int	oidfmt(int *, int, char *, u_int *);
64static void	parse(char *);
65static int	show_var(int *, int);
66static int	sysctl_all (int *oid, int len);
67static int	name2oid(char *, int *);
68
69static void
70usage(void)
71{
72
73	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
74		"usage: sysctl [-bn] variable ...",
75		"       sysctl [-bn] -w variable=value ...",
76		"       sysctl [-bn] -a",
77		"       sysctl [-bn] -A",
78		"       sysctl [-bn] -X");
79	exit(1);
80}
81
82int
83main(int argc, char **argv)
84{
85	int ch;
86	setbuf(stdout,0);
87	setbuf(stderr,0);
88
89	while ((ch = getopt(argc, argv, "AabnwX")) != -1) {
90		switch (ch) {
91		case 'A': Aflag = 1; break;
92		case 'a': aflag = 1; break;
93		case 'b': bflag = 1; break;
94		case 'n': nflag = 1; break;
95		case 'w': wflag = 1; break;
96		case 'X': Xflag = Aflag = 1; break;
97		default: usage();
98		}
99	}
100	argc -= optind;
101	argv += optind;
102
103	if (wflag && (Aflag || aflag))
104		usage();
105	if (Aflag || aflag)
106		exit (sysctl_all(0, 0));
107	if (argc == 0)
108		usage();
109	while (argc-- > 0)
110		parse(*argv++);
111	exit(0);
112}
113
114/*
115 * Parse a name into a MIB entry.
116 * Lookup and print out the MIB entry if it exists.
117 * Set a new value if requested.
118 */
119static void
120parse(char *string)
121{
122	int len, i, j;
123	void *newval = 0;
124	int intval, newsize = 0;
125	quad_t quadval;
126	int mib[CTL_MAXNAME];
127	char *cp, *bufp, buf[BUFSIZ];
128	u_int kind;
129
130	bufp = buf;
131	snprintf(buf, BUFSIZ, "%s", string);
132	if ((cp = strchr(string, '=')) != NULL) {
133		if (!wflag)
134			errx(2, "must specify -w to set variables");
135		*strchr(buf, '=') = '\0';
136		*cp++ = '\0';
137		while (isspace(*cp))
138			cp++;
139		newval = cp;
140		newsize = strlen(cp);
141	} else {
142		if (wflag)
143			usage();
144	}
145	len = name2oid(bufp, mib);
146
147	if (len < 0)
148		errx(1, "unknown oid '%s'", bufp);
149
150	if (oidfmt(mib, len, 0, &kind))
151		err(1, "couldn't find format of oid '%s'", bufp);
152
153	if (!wflag) {
154		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
155			sysctl_all(mib, len);
156		} else {
157			i = show_var(mib, len);
158			if (!i && !bflag)
159				putchar('\n');
160		}
161	} else {
162		if ((kind & CTLTYPE) == CTLTYPE_NODE)
163			errx(1, "oid '%s' isn't a leaf node", bufp);
164
165		if (!(kind&CTLFLAG_WR))
166			errx(1, "oid '%s' is read only", bufp);
167
168		switch (kind & CTLTYPE) {
169			case CTLTYPE_INT:
170				intval = (int) strtol(newval, NULL, 0);
171				newval = &intval;
172				newsize = sizeof intval;
173				break;
174				break;
175			case CTLTYPE_STRING:
176				break;
177			case CTLTYPE_QUAD:
178				break;
179				sscanf(newval, "%qd", &quadval);
180				newval = &quadval;
181				newsize = sizeof quadval;
182				break;
183			default:
184				errx(1, "oid '%s' is type %d,"
185					" cannot set that", bufp,
186					kind & CTLTYPE);
187		}
188
189		i = show_var(mib, len);
190		if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
191			if (!i && !bflag)
192				putchar('\n');
193			switch (errno) {
194			case EOPNOTSUPP:
195				errx(1, "%s: value is not available",
196					string);
197			case ENOTDIR:
198				errx(1, "%s: specification is incomplete",
199					string);
200			case ENOMEM:
201				errx(1, "%s: type is unknown to this program",
202					string);
203			default:
204				warn("%s", string);
205				return;
206			}
207		}
208		if (!bflag)
209			printf(" -> ");
210		i = nflag;
211		nflag = 1;
212		j = show_var(mib, len);
213		if (!j && !bflag)
214			putchar('\n');
215		nflag = i;
216	}
217}
218
219/* These functions will dump out various interesting structures. */
220
221static int
222S_clockinfo(int l2, void *p)
223{
224	struct clockinfo *ci = (struct clockinfo*)p;
225	if (l2 != sizeof *ci)
226		err(1, "S_clockinfo %d != %d", l2, sizeof *ci);
227	printf("{ hz = %d, tick = %d, tickadj = %d, profhz = %d, stathz = %d }",
228		ci->hz, ci->tick, ci->tickadj, ci->profhz, ci->stathz);
229	return (0);
230}
231
232static int
233S_loadavg(int l2, void *p)
234{
235	struct loadavg *tv = (struct loadavg*)p;
236
237	if (l2 != sizeof *tv)
238		err(1, "S_loadavg %d != %d", l2, sizeof *tv);
239
240	printf("{ %.2f %.2f %.2f }",
241		(double)tv->ldavg[0]/(double)tv->fscale,
242		(double)tv->ldavg[1]/(double)tv->fscale,
243		(double)tv->ldavg[2]/(double)tv->fscale);
244	return (0);
245}
246
247static int
248S_timeval(int l2, void *p)
249{
250	struct timeval *tv = (struct timeval*)p;
251	time_t tv_sec;
252	char *p1, *p2;
253
254	if (l2 != sizeof *tv)
255		err(1, "S_timeval %d != %d", l2, sizeof *tv);
256	printf("{ sec = %ld, usec = %ld } ",
257		tv->tv_sec, tv->tv_usec);
258	tv_sec = tv->tv_sec;
259	p1 = strdup(ctime(&tv_sec));
260	for (p2=p1; *p2 ; p2++)
261		if (*p2 == '\n')
262			*p2 = '\0';
263	fputs(p1, stdout);
264	return (0);
265}
266
267static int
268T_dev_t(int l2, void *p)
269{
270	dev_t *d = (dev_t *)p;
271	if (l2 != sizeof *d)
272		err(1, "T_dev_T %d != %d", l2, sizeof *d);
273	if ((int)(*d) != -1) {
274		if (minor(*d) > 255 || minor(*d) < 0)
275			printf("{ major = %d, minor = 0x%x }",
276				major(*d), minor(*d));
277		else
278			printf("{ major = %d, minor = %d }",
279				major(*d), minor(*d));
280	}
281	return (0);
282}
283
284/*
285 * These functions uses a presently undocumented interface to the kernel
286 * to walk the tree and get the type so it can print the value.
287 * This interface is under work and consideration, and should probably
288 * be killed with a big axe by the first person who can find the time.
289 * (be aware though, that the proper interface isn't as obvious as it
290 * may seem, there are various conflicting requirements.
291 */
292
293static int
294name2oid(char *name, int *oidp)
295{
296	int oid[2];
297	int i;
298	size_t j;
299
300	oid[0] = 0;
301	oid[1] = 3;
302
303	j = CTL_MAXNAME * sizeof (int);
304	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
305	if (i < 0)
306		return i;
307	j /= sizeof (int);
308	return (j);
309}
310
311static int
312oidfmt(int *oid, int len, char *fmt, u_int *kind)
313{
314	int qoid[CTL_MAXNAME+2];
315	u_char buf[BUFSIZ];
316	int i;
317	size_t j;
318
319	qoid[0] = 0;
320	qoid[1] = 4;
321	memcpy(qoid + 2, oid, len * sizeof(int));
322
323	j = sizeof buf;
324	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
325	if (i)
326		err(1, "sysctl fmt %d %d %d", i, j, errno);
327
328	if (kind)
329		*kind = *(u_int *)buf;
330
331	if (fmt)
332		strcpy(fmt, (char *)(buf + sizeof(u_int)));
333	return 0;
334}
335
336/*
337 * This formats and outputs the value of one variable
338 *
339 * Returns zero if anything was actually output.
340 * Returns one if didn't know what to do with this.
341 * Return minus one if we had errors.
342 */
343
344static int
345show_var(int *oid, int nlen)
346{
347	u_char buf[BUFSIZ], *val, *p;
348	char name[BUFSIZ], descr[BUFSIZ], *fmt;
349	int qoid[CTL_MAXNAME+2];
350	int i;
351	size_t j, len;
352	u_int kind;
353	int (*func)(int, void *) = 0;
354
355	qoid[0] = 0;
356	memcpy(qoid + 2, oid, nlen * sizeof(int));
357
358	qoid[1] = 1;
359	j = sizeof name;
360	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
361	if (i || !j)
362		err(1, "sysctl name %d %d %d", i, j, errno);
363
364	/* find an estimate of how much we need for this var */
365	j = 0;
366	i = sysctl(oid, nlen, 0, &j, 0, 0);
367	j += j; /* we want to be sure :-) */
368
369	val = alloca(j);
370	len = j;
371	i = sysctl(oid, nlen, val, &len, 0, 0);
372	if (i || !len)
373		return (1);
374
375	if (bflag) {
376		fwrite(val, 1, len, stdout);
377		return (0);
378	}
379
380	qoid[1] = 4;
381	j = sizeof buf;
382	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
383	if (i || !j)
384		err(1, "sysctl fmt %d %d %d", i, j, errno);
385
386	kind = *(u_int *)buf;
387
388	fmt = (char *)(buf + sizeof(u_int));
389
390	p = val;
391	switch (*fmt) {
392	case 'A':
393		if (!nflag)
394			printf("%s: ", name);
395		printf("%s", p);
396		return (0);
397
398	case 'I':
399		if (!nflag)
400			printf("%s: ", name);
401		fmt++;
402		val = "";
403		while (len >= sizeof(int)) {
404			if(*fmt == 'U')
405				printf("%s%u", val, *(unsigned int *)p);
406			else
407				printf("%s%d", val, *(int *)p);
408			val = " ";
409			len -= sizeof (int);
410			p += sizeof (int);
411		}
412		return (0);
413
414	case 'L':
415		if (!nflag)
416			printf("%s: ", name);
417		fmt++;
418		val = "";
419		while (len >= sizeof(long)) {
420			if(*fmt == 'U')
421				printf("%s%lu", val, *(unsigned long *)p);
422			else
423				printf("%s%ld", val, *(long *)p);
424			val = " ";
425			len -= sizeof (long);
426			p += sizeof (long);
427		}
428		return (0);
429
430	case 'P':
431		if (!nflag)
432			printf("%s: ", name);
433		printf("%p", *(void **)p);
434		return (0);
435
436	case 'T':
437	case 'S':
438		i = 0;
439		if (!strcmp(fmt, "S,clockinfo"))	func = S_clockinfo;
440		else if (!strcmp(fmt, "S,timeval"))	func = S_timeval;
441		else if (!strcmp(fmt, "S,loadavg"))	func = S_loadavg;
442		else if (!strcmp(fmt, "T,dev_t"))	func = T_dev_t;
443		if (func) {
444			if (!nflag)
445				printf("%s: ", name);
446			return ((*func)(len, p));
447		}
448		/* FALL THROUGH */
449	default:
450		if (!Aflag)
451			return (1);
452		if (!nflag)
453			printf("%s: ", name);
454		printf("Format:%s Length:%d Dump:0x", fmt, len);
455		while (len--) {
456			printf("%02x", *p++);
457			if (Xflag || p < val+16)
458				continue;
459			printf("...");
460			break;
461		}
462		return (0);
463	}
464	return (1);
465}
466
467static int
468sysctl_all (int *oid, int len)
469{
470	int name1[22], name2[22];
471	int i, j;
472	size_t l1, l2;
473
474	name1[0] = 0;
475	name1[1] = 2;
476	l1 = 2;
477	if (len) {
478		memcpy(name1+2, oid, len*sizeof (int));
479		l1 += len;
480	} else {
481		name1[2] = 1;
482		l1++;
483	}
484	while (1) {
485		l2 = sizeof name2;
486		j = sysctl(name1, l1, name2, &l2, 0, 0);
487		if (j < 0) {
488			if (errno == ENOENT)
489				return 0;
490			else
491				err(1, "sysctl(getnext) %d %d", j, l2);
492		}
493
494		l2 /= sizeof (int);
495
496		if (l2 < len)
497			return 0;
498
499		for (i = 0; i < len; i++)
500			if (name2[i] != oid[i])
501				return 0;
502
503		i = show_var(name2, l2);
504		if (!i && !bflag)
505			putchar('\n');
506
507		memcpy(name1+2, name2, l2*sizeof (int));
508		l1 = 2 + l2;
509	}
510}
511