xref: /freebsd/sbin/sysctl/sysctl.c (revision 11afcc8f9f96d657b8e6f7547c02c1957331fc96)
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.16 1997/11/18 03:37:45 jdp 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, j;
289 
290 	oid[0] = 0;
291 	oid[1] = 3;
292 
293 	j = CTL_MAXNAME * sizeof (int);
294 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
295 	if (i < 0)
296 		return i;
297 	j /= sizeof (int);
298 	return (j);
299 }
300 
301 static int
302 oidfmt(int *oid, int len, char *fmt, u_int *kind)
303 {
304 	int qoid[CTL_MAXNAME+2];
305 	u_char buf[BUFSIZ];
306 	int i, j;
307 
308 	qoid[0] = 0;
309 	qoid[1] = 4;
310 	memcpy(qoid + 2, oid, len * sizeof(int));
311 
312 	j = sizeof buf;
313 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
314 	if (i)
315 		err(1, "sysctl fmt %d %d %d", i, j, errno);
316 
317 	if (kind)
318 		*kind = *(u_int *)buf;
319 
320 	if (fmt)
321 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
322 	return 0;
323 }
324 
325 /*
326  * This formats and outputs the value of one variable
327  *
328  * Returns zero if anything was actually output.
329  * Returns one if didn't know what to do with this.
330  * Return minus one if we had errors.
331  */
332 
333 static int
334 show_var(int *oid, int nlen)
335 {
336 	u_char buf[BUFSIZ], *val, *p;
337 	char name[BUFSIZ], *fmt;
338 	int qoid[CTL_MAXNAME+2];
339 	int i, j, len;
340 	u_int kind;
341 	int (*func)(int, void *) = 0;
342 
343 	/* find an estimate of how much we need for this var */
344 	j = 0;
345 	i = sysctl(oid, nlen, 0, &j, 0, 0);
346 	j += j; /* we want to be sure :-) */
347 
348 	val = alloca(j);
349 	len = j;
350 	i = sysctl(oid, nlen, val, &len, 0, 0);
351 	if (i || !len)
352 		return (1);
353 
354 	if (bflag) {
355 		fwrite(val, 1, len, stdout);
356 		return (0);
357 	}
358 
359 	qoid[0] = 0;
360 	qoid[1] = 4;
361 	memcpy(qoid + 2, oid, nlen * sizeof(int));
362 
363 	j = sizeof buf;
364 	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
365 	if (i || !j)
366 		err(1, "sysctl fmt %d %d %d", i, j, errno);
367 
368 	kind = *(u_int *)buf;
369 
370 	fmt = (char *)(buf + sizeof(u_int));
371 
372 	qoid[1] = 1;
373 	j = sizeof name;
374 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
375 	if (i || !j)
376 		err(1, "sysctl name %d %d %d", i, j, errno);
377 
378 	p = val;
379 	switch (*fmt) {
380 	case 'A':
381 		if (!nflag)
382 			printf("%s: ", name);
383 		printf("%s", p);
384 		return (0);
385 
386 	case 'I':
387 		if (!nflag)
388 			printf("%s: ", name);
389 		printf("%d", *(int *)p);
390 		return (0);
391 
392 	case 'T':
393 	case 'S':
394 		i = 0;
395 		if (!strcmp(fmt, "S,clockinfo"))	func = S_clockinfo;
396 		else if (!strcmp(fmt, "S,timeval"))	func = S_timeval;
397 		else if (!strcmp(fmt, "S,loadavg"))	func = S_loadavg;
398 		else if (!strcmp(fmt, "T,dev_t"))	func = T_dev_t;
399 		if (func) {
400 			if (!nflag)
401 				printf("%s: ", name);
402 			return ((*func)(len, p));
403 		}
404 		/* FALL THROUGH */
405 	default:
406 		if (!Aflag)
407 			return (1);
408 		if (!nflag)
409 			printf("%s: ", name);
410 		printf("Format:%s Length:%d Dump:0x", fmt, len);
411 		while (len--) {
412 			printf("%02x", *p++);
413 			if (Xflag || p < val+16)
414 				continue;
415 			printf("...");
416 			break;
417 		}
418 		return (0);
419 	}
420 	return (1);
421 }
422 
423 static int
424 sysctl_all (int *oid, int len)
425 {
426 	int name1[22], name2[22];
427 	int i, j, l1, l2;
428 
429 	name1[0] = 0;
430 	name1[1] = 2;
431 	l1 = 2;
432 	if (len) {
433 		memcpy(name1+2, oid, len*sizeof (int));
434 		l1 += len;
435 	} else {
436 		name1[2] = 1;
437 		l1++;
438 	}
439 	while (1) {
440 		l2 = sizeof name2;
441 		j = sysctl(name1, l1, name2, &l2, 0, 0);
442 		if (j < 0)
443 			if (errno == ENOENT)
444 				return 0;
445 			else
446 				err(1, "sysctl(getnext) %d %d", j, l2);
447 
448 		l2 /= sizeof (int);
449 
450 		if (l2 < len)
451 			return 0;
452 
453 		for (i = 0; i < len; i++)
454 			if (name2[i] != oid[i])
455 				return 0;
456 
457 		i = show_var(name2, l2);
458 		if (!i && !bflag)
459 			putchar('\n');
460 
461 		memcpy(name1+2, name2, l2*sizeof (int));
462 		l1 = 2 + l2;
463 	}
464 }
465