sysctl.c revision 24428
1250963Sachim/*
2250963Sachim * Copyright (c) 1993
3250963Sachim *	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 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/*static char sccsid[] = "From: @(#)sysctl.c	8.1 (Berkeley) 6/6/93"; */
42static const char rcsid[] =
43	"$Id: sysctl.c,v 1.12 1997/02/22 16:13:58 peter Exp $";
44#endif /* not lint */
45
46#include <sys/types.h>
47#include <sys/stat.h>
48#include <sys/sysctl.h>
49#include <sys/resource.h>
50
51#include <errno.h>
52#include <stdio.h>
53#include <stdlib.h>
54#include <string.h>
55#include <ctype.h>
56#include <err.h>
57
58static int	Aflag, aflag, nflag, wflag, Xflag, bflag;
59
60static int	oidfmt(int *, int, char *, u_int *);
61static void	parse(char *);
62static int	show_var(int *, int);
63static int	sysctl_all (int *oid, int len);
64static int	name2oid(char *, int *);
65
66static void
67usage(void)
68{
69
70	(void)fprintf(stderr, "usage:\n%s",
71	    "\tsysctl [-bnX] variable ...\n"
72	    "\tsysctl [-bnX] -w variable=value ...\n"
73	    "\tsysctl [-bnX] -a\n"
74	    "\tsysctl [-bnX] -A\n"
75		);
76	exit(1);
77}
78
79int
80main(int argc, char **argv)
81{
82	extern char *optarg;
83	extern int optind;
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			fprintf(stderr, "Must specify -w to set variables\n");
132			exit(2);
133		}
134		*strchr(buf, '=') = '\0';
135		*cp++ = '\0';
136		while (isspace(*cp))
137			cp++;
138		newval = cp;
139		newsize = strlen(cp);
140	} else {
141		if (wflag)
142			usage();
143	}
144	len = name2oid(bufp, mib);
145
146	if (len < 0)
147		errx(1, "Unknown oid '%s'", bufp);
148
149	if (oidfmt(mib, len, 0, &kind))
150		err(1, "Couldn't find format of oid '%s'", bufp);
151
152	if (!wflag) {
153		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
154			sysctl_all(mib, len);
155		} else {
156			i = show_var(mib, len);
157			if (!i && !bflag)
158				putchar('\n');
159		}
160	} else {
161		if ((kind & CTLTYPE) == CTLTYPE_NODE)
162			errx(1, "oid '%s' isn't a leaf node", bufp);
163
164		if (!(kind&CTLFLAG_WR))
165			errx(1, "oid '%s' is read only", bufp);
166
167		switch (kind & CTLTYPE) {
168			case CTLTYPE_INT:
169				intval = atoi(newval);
170				newval = &intval;
171				newsize = sizeof intval;
172				break;
173				break;
174			case CTLTYPE_STRING:
175				break;
176			case CTLTYPE_QUAD:
177				break;
178				sscanf(newval, "%qd", &quadval);
179				newval = &quadval;
180				newsize = sizeof quadval;
181				break;
182			default:
183				errx(1, "oid '%s' is type %d,"
184					" cannot set that", bufp);
185		}
186
187		i = show_var(mib, len);
188		if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
189			if (!i && !bflag)
190				putchar('\n');
191			switch (errno) {
192			case EOPNOTSUPP:
193				errx(1, "%s: value is not available\n",
194					string);
195			case ENOTDIR:
196				errx(1, "%s: specification is incomplete\n",
197					string);
198			case ENOMEM:
199				errx(1, "%s: type is unknown to this program\n",
200					string);
201			default:
202				perror(string);
203				return;
204			}
205		}
206		if (!bflag)
207			printf(" -> ");
208		i = nflag;
209		nflag = 1;
210		j = show_var(mib, len);
211		if (!j && !bflag)
212			putchar('\n');
213		nflag = i;
214	}
215}
216
217/* These functions will dump out various interesting structures. */
218
219static int
220S_clockinfo(int l2, void *p)
221{
222	struct clockinfo *ci = (struct clockinfo*)p;
223	if (l2 != sizeof *ci)
224		err(-1, "S_clockinfo %d != %d", l2, sizeof *ci);
225	printf("{ hz = %d, tick = %d, profhz = %d, stathz = %d }",
226		ci->hz, ci->tick, ci->profhz, ci->stathz);
227	return (0);
228}
229
230static int
231S_loadavg(int l2, void *p)
232{
233	struct loadavg *tv = (struct loadavg*)p;
234
235	if (l2 != sizeof *tv)
236		err(-1, "S_loadavg %d != %d", l2, sizeof *tv);
237
238	printf("{ %.2f %.2f %.2f }",
239		(double)tv->ldavg[0]/(double)tv->fscale,
240		(double)tv->ldavg[1]/(double)tv->fscale,
241		(double)tv->ldavg[2]/(double)tv->fscale);
242	return (0);
243}
244
245static int
246S_timeval(int l2, void *p)
247{
248	struct timeval *tv = (struct timeval*)p;
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	p1 = strdup(ctime(&tv->tv_sec));
256	for (p2=p1; *p2 ; p2++)
257		if (*p2 == '\n')
258			*p2 = '\0';
259	fputs(p1, stdout);
260	return (0);
261}
262
263static int
264T_dev_t(int l2, void *p)
265{
266	dev_t *d = (dev_t *)p;
267	if (l2 != sizeof *d)
268		err(-1, "T_dev_T %d != %d", l2, sizeof *d);
269	printf("{ major = %d, minor = %d }",
270		major(*d), minor(*d));
271	return (0);
272}
273
274/*
275 * These functions uses a presently undocumented interface to the kernel
276 * to walk the tree and get the type so it can print the value.
277 * This interface is under work and consideration, and should probably
278 * be killed with a big axe by the first person who can find the time.
279 * (be aware though, that the proper interface isn't as obvious as it
280 * may seem, there are various conflicting requirements.
281 */
282
283static int
284name2oid(char *name, int *oidp)
285{
286	int oid[2];
287	int i, j;
288
289	oid[0] = 0;
290	oid[1] = 3;
291
292	j = CTL_MAXNAME * sizeof (int);
293	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
294	if (i < 0)
295		return i;
296	j /= sizeof (int);
297	return (j);
298}
299
300static int
301oidfmt(int *oid, int len, char *fmt, u_int *kind)
302{
303	int qoid[CTL_MAXNAME+2];
304	u_char buf[BUFSIZ];
305	int i, j;
306
307	qoid[0] = 0;
308	qoid[1] = 4;
309	memcpy(qoid + 2, oid, len * sizeof(int));
310
311	j = sizeof buf;
312	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
313	if (i)
314		err(-1, "sysctl fmt %d %d %d", i, j, errno);
315
316	if (kind)
317		*kind = *(u_int *)buf;
318
319	if (fmt)
320		strcpy(fmt, (char *)(buf + sizeof(u_int)));
321	return 0;
322}
323
324/*
325 * This formats and outputs the value of one variable
326 *
327 * Returns zero if anything was actually output.
328 * Returns one if didn't know what to do with this.
329 * Return minus one if we had errors.
330 */
331
332static int
333show_var(int *oid, int nlen)
334{
335	u_char buf[BUFSIZ], *val, *p;
336	char name[BUFSIZ], *fmt;
337	int qoid[CTL_MAXNAME+2];
338	int i, j, len;
339	u_int kind;
340	int (*func)(int, void *) = 0;
341
342	/* find an estimate of how much we need for this var */
343	j = 0;
344	i = sysctl(oid, nlen, 0, &j, 0, 0);
345	j += j; /* we want to be sure :-) */
346
347	val = alloca(j);
348	len = j;
349	i = sysctl(oid, nlen, val, &len, 0, 0);
350	if (i || !len)
351		return (1);
352
353	if (bflag) {
354		fwrite(val, 1, len, stdout);
355		return (0);
356	}
357
358	qoid[0] = 0;
359	qoid[1] = 4;
360	memcpy(qoid + 2, oid, nlen * sizeof(int));
361
362	j = sizeof buf;
363	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
364	if (i || !j)
365		err(-1, "sysctl fmt %d %d %d", i, j, errno);
366
367	kind = *(u_int *)buf;
368
369	fmt = (char *)(buf + sizeof(u_int));
370
371	qoid[1] = 1;
372	j = sizeof name;
373	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
374	if (i || !j)
375		err(-1, "sysctl name %d %d %d", i, j, errno);
376
377	p = val;
378	switch (*fmt) {
379	case 'A':
380		if (!nflag)
381			printf("%s: ", name);
382		printf("%s", p);
383		return (0);
384
385	case 'I':
386		if (!nflag)
387			printf("%s: ", name);
388		printf("%d", *(int *)p);
389		return (0);
390
391	case 'T':
392	case 'S':
393		i = 0;
394		if (!strcmp(fmt, "S,clockinfo"))	func = S_clockinfo;
395		else if (!strcmp(fmt, "S,timeval"))	func = S_timeval;
396		else if (!strcmp(fmt, "S,loadavg"))	func = S_loadavg;
397		else if (!strcmp(fmt, "T,dev_t"))	func = T_dev_t;
398		if (func) {
399			if (!nflag)
400				printf("%s: ", name);
401			return ((*func)(len, p));
402		}
403		/* FALL THROUGH */
404	default:
405		if (!Aflag)
406			return (1);
407		if (!nflag)
408			printf("%s: ", name);
409		printf("Format:%s Length:%d Dump:0x", fmt, len);
410		while (len--) {
411			printf("%02x", *p++);
412			if (Xflag || p < val+16)
413				continue;
414			printf("...");
415			break;
416		}
417		return (0);
418	}
419	return (1);
420}
421
422static int
423sysctl_all (int *oid, int len)
424{
425	int name1[22], name2[22];
426	int i, j, l1, l2;
427
428	name1[0] = 0;
429	name1[1] = 2;
430	l1 = 2;
431	if (len) {
432		memcpy(name1+2, oid, len*sizeof (int));
433		l1 += len;
434	} else {
435		name1[2] = 1;
436		l1++;
437	}
438	while (1) {
439		l2 = sizeof name2;
440		j = sysctl(name1, l1, name2, &l2, 0, 0);
441		if (j < 0)
442			if (errno == ENOENT)
443				return 0;
444			else
445				err(-1, "sysctl(getnext) %d %d", j, l2);
446
447		l2 /= sizeof (int);
448
449		if (l2 < len)
450			return 0;
451
452		for (i = 0; i < len; i++)
453			if (name2[i] != oid[i])
454				return 0;
455
456		i = show_var(name2, l2);
457		if (!i && !bflag)
458			putchar('\n');
459
460		memcpy(name1+2, name2, l2*sizeof (int));
461		l1 = 2 + l2;
462	}
463}
464