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