sysctl.c revision 31214
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	"$Id: sysctl.c,v 1.15 1997/10/20 12:53:54 charnier 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
61static int	Aflag, aflag, nflag, wflag, Xflag, bflag;
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",
74		"usage: sysctl [-bnX] variable ...",
75		"       sysctl [-bnX] -w variable=value ...",
76		"       sysctl [-bnX] -a",
77		"       sysctl [-bnX] -A");
78	exit(1);
79}
80
81int
82main(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 */
116static void
117parse(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
218static int
219S_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
229static int
230S_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
244static int
245S_timeval(int l2, void *p)
246{
247	struct timeval *tv = (struct timeval*)p;
248	char *p1, *p2;
249
250	if (l2 != sizeof *tv)
251		err(1, "S_timeval %d != %d", l2, sizeof *tv);
252	printf("{ sec = %ld, usec = %ld } ",
253		tv->tv_sec, tv->tv_usec);
254	p1 = strdup(ctime(&tv->tv_sec));
255	for (p2=p1; *p2 ; p2++)
256		if (*p2 == '\n')
257			*p2 = '\0';
258	fputs(p1, stdout);
259	return (0);
260}
261
262static int
263T_dev_t(int l2, void *p)
264{
265	dev_t *d = (dev_t *)p;
266	if (l2 != sizeof *d)
267		err(1, "T_dev_T %d != %d", l2, sizeof *d);
268	printf("{ major = %d, minor = %d }",
269		major(*d), minor(*d));
270	return (0);
271}
272
273/*
274 * These functions uses a presently undocumented interface to the kernel
275 * to walk the tree and get the type so it can print the value.
276 * This interface is under work and consideration, and should probably
277 * be killed with a big axe by the first person who can find the time.
278 * (be aware though, that the proper interface isn't as obvious as it
279 * may seem, there are various conflicting requirements.
280 */
281
282static int
283name2oid(char *name, int *oidp)
284{
285	int oid[2];
286	int i, j;
287
288	oid[0] = 0;
289	oid[1] = 3;
290
291	j = CTL_MAXNAME * sizeof (int);
292	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
293	if (i < 0)
294		return i;
295	j /= sizeof (int);
296	return (j);
297}
298
299static int
300oidfmt(int *oid, int len, char *fmt, u_int *kind)
301{
302	int qoid[CTL_MAXNAME+2];
303	u_char buf[BUFSIZ];
304	int i, j;
305
306	qoid[0] = 0;
307	qoid[1] = 4;
308	memcpy(qoid + 2, oid, len * sizeof(int));
309
310	j = sizeof buf;
311	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
312	if (i)
313		err(1, "sysctl fmt %d %d %d", i, j, errno);
314
315	if (kind)
316		*kind = *(u_int *)buf;
317
318	if (fmt)
319		strcpy(fmt, (char *)(buf + sizeof(u_int)));
320	return 0;
321}
322
323/*
324 * This formats and outputs the value of one variable
325 *
326 * Returns zero if anything was actually output.
327 * Returns one if didn't know what to do with this.
328 * Return minus one if we had errors.
329 */
330
331static int
332show_var(int *oid, int nlen)
333{
334	u_char buf[BUFSIZ], *val, *p;
335	char name[BUFSIZ], *fmt;
336	int qoid[CTL_MAXNAME+2];
337	int i, j, len;
338	u_int kind;
339	int (*func)(int, void *) = 0;
340
341	/* find an estimate of how much we need for this var */
342	j = 0;
343	i = sysctl(oid, nlen, 0, &j, 0, 0);
344	j += j; /* we want to be sure :-) */
345
346	val = alloca(j);
347	len = j;
348	i = sysctl(oid, nlen, val, &len, 0, 0);
349	if (i || !len)
350		return (1);
351
352	if (bflag) {
353		fwrite(val, 1, len, stdout);
354		return (0);
355	}
356
357	qoid[0] = 0;
358	qoid[1] = 4;
359	memcpy(qoid + 2, oid, nlen * sizeof(int));
360
361	j = sizeof buf;
362	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
363	if (i || !j)
364		err(1, "sysctl fmt %d %d %d", i, j, errno);
365
366	kind = *(u_int *)buf;
367
368	fmt = (char *)(buf + sizeof(u_int));
369
370	qoid[1] = 1;
371	j = sizeof name;
372	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
373	if (i || !j)
374		err(1, "sysctl name %d %d %d", i, j, errno);
375
376	p = val;
377	switch (*fmt) {
378	case 'A':
379		if (!nflag)
380			printf("%s: ", name);
381		printf("%s", p);
382		return (0);
383
384	case 'I':
385		if (!nflag)
386			printf("%s: ", name);
387		printf("%d", *(int *)p);
388		return (0);
389
390	case 'T':
391	case 'S':
392		i = 0;
393		if (!strcmp(fmt, "S,clockinfo"))	func = S_clockinfo;
394		else if (!strcmp(fmt, "S,timeval"))	func = S_timeval;
395		else if (!strcmp(fmt, "S,loadavg"))	func = S_loadavg;
396		else if (!strcmp(fmt, "T,dev_t"))	func = T_dev_t;
397		if (func) {
398			if (!nflag)
399				printf("%s: ", name);
400			return ((*func)(len, p));
401		}
402		/* FALL THROUGH */
403	default:
404		if (!Aflag)
405			return (1);
406		if (!nflag)
407			printf("%s: ", name);
408		printf("Format:%s Length:%d Dump:0x", fmt, len);
409		while (len--) {
410			printf("%02x", *p++);
411			if (Xflag || p < val+16)
412				continue;
413			printf("...");
414			break;
415		}
416		return (0);
417	}
418	return (1);
419}
420
421static int
422sysctl_all (int *oid, int len)
423{
424	int name1[22], name2[22];
425	int i, j, l1, l2;
426
427	name1[0] = 0;
428	name1[1] = 2;
429	l1 = 2;
430	if (len) {
431		memcpy(name1+2, oid, len*sizeof (int));
432		l1 += len;
433	} else {
434		name1[2] = 1;
435		l1++;
436	}
437	while (1) {
438		l2 = sizeof name2;
439		j = sysctl(name1, l1, name2, &l2, 0, 0);
440		if (j < 0)
441			if (errno == ENOENT)
442				return 0;
443			else
444				err(1, "sysctl(getnext) %d %d", j, l2);
445
446		l2 /= sizeof (int);
447
448		if (l2 < len)
449			return 0;
450
451		for (i = 0; i < len; i++)
452			if (name2[i] != oid[i])
453				return 0;
454
455		i = show_var(name2, l2);
456		if (!i && !bflag)
457			putchar('\n');
458
459		memcpy(name1+2, name2, l2*sizeof (int));
460		l1 = 2 + l2;
461	}
462}
463