xref: /freebsd/sbin/sysctl/sysctl.c (revision 5129159789cc9d7bc514e4546b88e3427695002d)
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   "$FreeBSD$";
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, bflag, nflag, wflag, Xflag;
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%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 
82 int
83 main(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  */
119 static void
120 parse(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 
221 static int
222 S_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 
232 static int
233 S_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 
247 static int
248 S_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 
267 static int
268 T_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 	printf("{ major = %d, minor = %d }",
274 		major(*d), minor(*d));
275 	return (0);
276 }
277 
278 /*
279  * These functions uses a presently undocumented interface to the kernel
280  * to walk the tree and get the type so it can print the value.
281  * This interface is under work and consideration, and should probably
282  * be killed with a big axe by the first person who can find the time.
283  * (be aware though, that the proper interface isn't as obvious as it
284  * may seem, there are various conflicting requirements.
285  */
286 
287 static int
288 name2oid(char *name, int *oidp)
289 {
290 	int oid[2];
291 	int i;
292 	size_t j;
293 
294 	oid[0] = 0;
295 	oid[1] = 3;
296 
297 	j = CTL_MAXNAME * sizeof (int);
298 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
299 	if (i < 0)
300 		return i;
301 	j /= sizeof (int);
302 	return (j);
303 }
304 
305 static int
306 oidfmt(int *oid, int len, char *fmt, u_int *kind)
307 {
308 	int qoid[CTL_MAXNAME+2];
309 	u_char buf[BUFSIZ];
310 	int i;
311 	size_t j;
312 
313 	qoid[0] = 0;
314 	qoid[1] = 4;
315 	memcpy(qoid + 2, oid, len * sizeof(int));
316 
317 	j = sizeof buf;
318 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
319 	if (i)
320 		err(1, "sysctl fmt %d %d %d", i, j, errno);
321 
322 	if (kind)
323 		*kind = *(u_int *)buf;
324 
325 	if (fmt)
326 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
327 	return 0;
328 }
329 
330 /*
331  * This formats and outputs the value of one variable
332  *
333  * Returns zero if anything was actually output.
334  * Returns one if didn't know what to do with this.
335  * Return minus one if we had errors.
336  */
337 
338 static int
339 show_var(int *oid, int nlen)
340 {
341 	u_char buf[BUFSIZ], *val, *p;
342 	char name[BUFSIZ], descr[BUFSIZ], *fmt;
343 	int qoid[CTL_MAXNAME+2];
344 	int i;
345 	size_t j, len;
346 	u_int kind;
347 	int (*func)(int, void *) = 0;
348 
349 	qoid[0] = 0;
350 	memcpy(qoid + 2, oid, nlen * sizeof(int));
351 
352 	qoid[1] = 1;
353 	j = sizeof name;
354 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
355 	if (i || !j)
356 		err(1, "sysctl name %d %d %d", i, j, errno);
357 
358 	/* find an estimate of how much we need for this var */
359 	j = 0;
360 	i = sysctl(oid, nlen, 0, &j, 0, 0);
361 	j += j; /* we want to be sure :-) */
362 
363 	val = alloca(j);
364 	len = j;
365 	i = sysctl(oid, nlen, val, &len, 0, 0);
366 	if (i || !len)
367 		return (1);
368 
369 	if (bflag) {
370 		fwrite(val, 1, len, stdout);
371 		return (0);
372 	}
373 
374 	qoid[1] = 4;
375 	j = sizeof buf;
376 	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
377 	if (i || !j)
378 		err(1, "sysctl fmt %d %d %d", i, j, errno);
379 
380 	kind = *(u_int *)buf;
381 
382 	fmt = (char *)(buf + sizeof(u_int));
383 
384 	p = val;
385 	switch (*fmt) {
386 	case 'A':
387 		if (!nflag)
388 			printf("%s: ", name);
389 		printf("%s", p);
390 		return (0);
391 
392 	case 'I':
393 		if (!nflag)
394 			printf("%s: ", name);
395 		val = "";
396 		while (len >= sizeof(int)) {
397 			printf("%s%d", val, *(int *)p);
398 			val = " ";
399 			len -= sizeof (int);
400 			p += sizeof (int);
401 		}
402 		return (0);
403 
404 	case 'L':
405 		if (!nflag)
406 			printf("%s: ", name);
407 		printf("%ld", *(long *)p);
408 		return (0);
409 
410 	case 'P':
411 		if (!nflag)
412 			printf("%s: ", name);
413 		printf("%p", *(void **)p);
414 		return (0);
415 
416 	case 'T':
417 	case 'S':
418 		i = 0;
419 		if (!strcmp(fmt, "S,clockinfo"))	func = S_clockinfo;
420 		else if (!strcmp(fmt, "S,timeval"))	func = S_timeval;
421 		else if (!strcmp(fmt, "S,loadavg"))	func = S_loadavg;
422 		else if (!strcmp(fmt, "T,dev_t"))	func = T_dev_t;
423 		if (func) {
424 			if (!nflag)
425 				printf("%s: ", name);
426 			return ((*func)(len, p));
427 		}
428 		/* FALL THROUGH */
429 	default:
430 		if (!Aflag)
431 			return (1);
432 		if (!nflag)
433 			printf("%s: ", name);
434 		printf("Format:%s Length:%d Dump:0x", fmt, len);
435 		while (len--) {
436 			printf("%02x", *p++);
437 			if (Xflag || p < val+16)
438 				continue;
439 			printf("...");
440 			break;
441 		}
442 		return (0);
443 	}
444 	return (1);
445 }
446 
447 static int
448 sysctl_all (int *oid, int len)
449 {
450 	int name1[22], name2[22];
451 	int i, j;
452 	size_t l1, l2;
453 
454 	name1[0] = 0;
455 	name1[1] = 2;
456 	l1 = 2;
457 	if (len) {
458 		memcpy(name1+2, oid, len*sizeof (int));
459 		l1 += len;
460 	} else {
461 		name1[2] = 1;
462 		l1++;
463 	}
464 	while (1) {
465 		l2 = sizeof name2;
466 		j = sysctl(name1, l1, name2, &l2, 0, 0);
467 		if (j < 0) {
468 			if (errno == ENOENT)
469 				return 0;
470 			else
471 				err(1, "sysctl(getnext) %d %d", j, l2);
472 		}
473 
474 		l2 /= sizeof (int);
475 
476 		if (l2 < len)
477 			return 0;
478 
479 		for (i = 0; i < len; i++)
480 			if (name2[i] != oid[i])
481 				return 0;
482 
483 		i = show_var(name2, l2);
484 		if (!i && !bflag)
485 			putchar('\n');
486 
487 		memcpy(name1+2, name2, l2*sizeof (int));
488 		l1 = 2 + l2;
489 	}
490 }
491