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