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