xref: /freebsd/sbin/sysctl/sysctl.c (revision 6132212808e8dccedc9e5d85fea4390c2f38059a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)from: sysctl.c	8.1 (Berkeley) 6/6/93";
41 #endif
42 static const char rcsid[] =
43   "$FreeBSD$";
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 #include <sys/time.h>
48 #include <sys/resource.h>
49 #include <sys/stat.h>
50 #include <sys/sysctl.h>
51 #include <sys/vmmeter.h>
52 #include <dev/evdev/input.h>
53 
54 #ifdef __amd64__
55 #include <sys/efi.h>
56 #include <machine/metadata.h>
57 #endif
58 
59 #if defined(__amd64__) || defined(__i386__)
60 #include <machine/pc/bios.h>
61 #endif
62 
63 #include <assert.h>
64 #include <ctype.h>
65 #include <err.h>
66 #include <errno.h>
67 #include <inttypes.h>
68 #include <locale.h>
69 #include <stdbool.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <sysexits.h>
74 #include <unistd.h>
75 
76 static const char *conffile;
77 
78 static int	aflag, bflag, Bflag, dflag, eflag, hflag, iflag;
79 static int	Nflag, nflag, oflag, qflag, tflag, Tflag, Wflag, xflag;
80 
81 static int	oidfmt(int *, int, char *, u_int *);
82 static int	parsefile(const char *);
83 static int	parse(const char *, int);
84 static int	show_var(int *, int);
85 static int	sysctl_all(int *oid, int len);
86 static int	name2oid(const char *, int *);
87 
88 static int	strIKtoi(const char *, char **, const char *);
89 
90 static int ctl_sign[CTLTYPE+1] = {
91 	[CTLTYPE_INT] = 1,
92 	[CTLTYPE_LONG] = 1,
93 	[CTLTYPE_S8] = 1,
94 	[CTLTYPE_S16] = 1,
95 	[CTLTYPE_S32] = 1,
96 	[CTLTYPE_S64] = 1,
97 };
98 
99 static int ctl_size[CTLTYPE+1] = {
100 	[CTLTYPE_INT] = sizeof(int),
101 	[CTLTYPE_UINT] = sizeof(u_int),
102 	[CTLTYPE_LONG] = sizeof(long),
103 	[CTLTYPE_ULONG] = sizeof(u_long),
104 	[CTLTYPE_S8] = sizeof(int8_t),
105 	[CTLTYPE_S16] = sizeof(int16_t),
106 	[CTLTYPE_S32] = sizeof(int32_t),
107 	[CTLTYPE_S64] = sizeof(int64_t),
108 	[CTLTYPE_U8] = sizeof(uint8_t),
109 	[CTLTYPE_U16] = sizeof(uint16_t),
110 	[CTLTYPE_U32] = sizeof(uint32_t),
111 	[CTLTYPE_U64] = sizeof(uint64_t),
112 };
113 
114 static const char *ctl_typename[CTLTYPE+1] = {
115 	[CTLTYPE_INT] = "integer",
116 	[CTLTYPE_UINT] = "unsigned integer",
117 	[CTLTYPE_LONG] = "long integer",
118 	[CTLTYPE_ULONG] = "unsigned long",
119 	[CTLTYPE_U8] = "uint8_t",
120 	[CTLTYPE_U16] = "uint16_t",
121 	[CTLTYPE_U32] = "uint32_t",
122 	[CTLTYPE_U64] = "uint64_t",
123 	[CTLTYPE_S8] = "int8_t",
124 	[CTLTYPE_S16] = "int16_t",
125 	[CTLTYPE_S32] = "int32_t",
126 	[CTLTYPE_S64] = "int64_t",
127 	[CTLTYPE_NODE] = "node",
128 	[CTLTYPE_STRING] = "string",
129 	[CTLTYPE_OPAQUE] = "opaque",
130 };
131 
132 static void
133 usage(void)
134 {
135 
136 	(void)fprintf(stderr, "%s\n%s\n",
137 	    "usage: sysctl [-bdehiNnoqTtWx] [ -B <bufsize> ] [-f filename] name[=value] ...",
138 	    "       sysctl [-bdehNnoqTtWx] [ -B <bufsize> ] -a");
139 	exit(1);
140 }
141 
142 int
143 main(int argc, char **argv)
144 {
145 	int ch;
146 	int warncount = 0;
147 
148 	setlocale(LC_NUMERIC, "");
149 	setbuf(stdout,0);
150 	setbuf(stderr,0);
151 
152 	while ((ch = getopt(argc, argv, "AabB:def:hiNnoqtTwWxX")) != -1) {
153 		switch (ch) {
154 		case 'A':
155 			/* compatibility */
156 			aflag = oflag = 1;
157 			break;
158 		case 'a':
159 			aflag = 1;
160 			break;
161 		case 'b':
162 			bflag = 1;
163 			break;
164 		case 'B':
165 			Bflag = strtol(optarg, NULL, 0);
166 			break;
167 		case 'd':
168 			dflag = 1;
169 			break;
170 		case 'e':
171 			eflag = 1;
172 			break;
173 		case 'f':
174 			conffile = optarg;
175 			break;
176 		case 'h':
177 			hflag = 1;
178 			break;
179 		case 'i':
180 			iflag = 1;
181 			break;
182 		case 'N':
183 			Nflag = 1;
184 			break;
185 		case 'n':
186 			nflag = 1;
187 			break;
188 		case 'o':
189 			oflag = 1;
190 			break;
191 		case 'q':
192 			qflag = 1;
193 			break;
194 		case 't':
195 			tflag = 1;
196 			break;
197 		case 'T':
198 			Tflag = 1;
199 			break;
200 		case 'w':
201 			/* compatibility */
202 			/* ignored */
203 			break;
204 		case 'W':
205 			Wflag = 1;
206 			break;
207 		case 'X':
208 			/* compatibility */
209 			aflag = xflag = 1;
210 			break;
211 		case 'x':
212 			xflag = 1;
213 			break;
214 		default:
215 			usage();
216 		}
217 	}
218 	argc -= optind;
219 	argv += optind;
220 
221 	if (Nflag && nflag)
222 		usage();
223 	if (aflag && argc == 0)
224 		exit(sysctl_all(0, 0));
225 	if (argc == 0 && conffile == NULL)
226 		usage();
227 
228 	warncount = 0;
229 	if (conffile != NULL)
230 		warncount += parsefile(conffile);
231 
232 	while (argc-- > 0)
233 		warncount += parse(*argv++, 0);
234 
235 	return (warncount);
236 }
237 
238 /*
239  * Parse a single numeric value, append it to 'newbuf', and update
240  * 'newsize'.  Returns true if the value was parsed and false if the
241  * value was invalid.  Non-numeric types (strings) are handled
242  * directly in parse().
243  */
244 static bool
245 parse_numeric(const char *newvalstr, const char *fmt, u_int kind,
246     void **newbufp, size_t *newsizep)
247 {
248 	void *newbuf;
249 	const void *newval;
250 	int8_t i8val;
251 	uint8_t u8val;
252 	int16_t i16val;
253 	uint16_t u16val;
254 	int32_t i32val;
255 	uint32_t u32val;
256 	int intval;
257 	unsigned int uintval;
258 	long longval;
259 	unsigned long ulongval;
260 	int64_t i64val;
261 	uint64_t u64val;
262 	size_t valsize;
263 	char *endptr = NULL;
264 
265 	errno = 0;
266 
267 	switch (kind & CTLTYPE) {
268 	case CTLTYPE_INT:
269 		if (strncmp(fmt, "IK", 2) == 0)
270 			intval = strIKtoi(newvalstr, &endptr, fmt);
271 		else
272 			intval = (int)strtol(newvalstr, &endptr, 0);
273 		newval = &intval;
274 		valsize = sizeof(intval);
275 		break;
276 	case CTLTYPE_UINT:
277 		uintval = (int) strtoul(newvalstr, &endptr, 0);
278 		newval = &uintval;
279 		valsize = sizeof(uintval);
280 		break;
281 	case CTLTYPE_LONG:
282 		longval = strtol(newvalstr, &endptr, 0);
283 		newval = &longval;
284 		valsize = sizeof(longval);
285 		break;
286 	case CTLTYPE_ULONG:
287 		ulongval = strtoul(newvalstr, &endptr, 0);
288 		newval = &ulongval;
289 		valsize = sizeof(ulongval);
290 		break;
291 	case CTLTYPE_S8:
292 		i8val = (int8_t)strtol(newvalstr, &endptr, 0);
293 		newval = &i8val;
294 		valsize = sizeof(i8val);
295 		break;
296 	case CTLTYPE_S16:
297 		i16val = (int16_t)strtol(newvalstr, &endptr, 0);
298 		newval = &i16val;
299 		valsize = sizeof(i16val);
300 		break;
301 	case CTLTYPE_S32:
302 		i32val = (int32_t)strtol(newvalstr, &endptr, 0);
303 		newval = &i32val;
304 		valsize = sizeof(i32val);
305 		break;
306 	case CTLTYPE_S64:
307 		i64val = strtoimax(newvalstr, &endptr, 0);
308 		newval = &i64val;
309 		valsize = sizeof(i64val);
310 		break;
311 	case CTLTYPE_U8:
312 		u8val = (uint8_t)strtoul(newvalstr, &endptr, 0);
313 		newval = &u8val;
314 		valsize = sizeof(u8val);
315 		break;
316 	case CTLTYPE_U16:
317 		u16val = (uint16_t)strtoul(newvalstr, &endptr, 0);
318 		newval = &u16val;
319 		valsize = sizeof(u16val);
320 		break;
321 	case CTLTYPE_U32:
322 		u32val = (uint32_t)strtoul(newvalstr, &endptr, 0);
323 		newval = &u32val;
324 		valsize = sizeof(u32val);
325 		break;
326 	case CTLTYPE_U64:
327 		u64val = strtoumax(newvalstr, &endptr, 0);
328 		newval = &u64val;
329 		valsize = sizeof(u64val);
330 		break;
331 	default:
332 		/* NOTREACHED */
333 		abort();
334 	}
335 
336 	if (errno != 0 || endptr == newvalstr ||
337 	    (endptr != NULL && *endptr != '\0'))
338 		return (false);
339 
340 	newbuf = realloc(*newbufp, *newsizep + valsize);
341 	if (newbuf == NULL)
342 		err(1, "out of memory");
343 	memcpy((char *)newbuf + *newsizep, newval, valsize);
344 	*newbufp = newbuf;
345 	*newsizep += valsize;
346 
347 	return (true);
348 }
349 
350 /*
351  * Parse a name into a MIB entry.
352  * Lookup and print out the MIB entry if it exists.
353  * Set a new value if requested.
354  */
355 static int
356 parse(const char *string, int lineno)
357 {
358 	int len, i, j;
359 	const void *newval;
360 	char *newvalstr = NULL;
361 	void *newbuf;
362 	size_t newsize = Bflag;
363 	int mib[CTL_MAXNAME];
364 	char *cp, *bufp, buf[BUFSIZ], fmt[BUFSIZ], line[BUFSIZ];
365 	u_int kind;
366 
367 	if (lineno)
368 		snprintf(line, sizeof(line), " at line %d", lineno);
369 	else
370 		line[0] = '\0';
371 
372 	cp = buf;
373 	if (snprintf(buf, BUFSIZ, "%s", string) >= BUFSIZ) {
374 		warnx("oid too long: '%s'%s", string, line);
375 		return (1);
376 	}
377 	bufp = strsep(&cp, "=:");
378 	if (cp != NULL) {
379 		/* Tflag just lists tunables, do not allow assignment */
380 		if (Tflag || Wflag) {
381 			warnx("Can't set variables when using -T or -W");
382 			usage();
383 		}
384 		while (isspace(*cp))
385 			cp++;
386 		/* Strip a pair of " or ' if any. */
387 		switch (*cp) {
388 		case '\"':
389 		case '\'':
390 			if (cp[strlen(cp) - 1] == *cp)
391 				cp[strlen(cp) - 1] = '\0';
392 			cp++;
393 		}
394 		newvalstr = cp;
395 		newsize = strlen(cp);
396 	}
397 	/* Trim spaces */
398 	cp = bufp + strlen(bufp) - 1;
399 	while (cp >= bufp && isspace((int)*cp)) {
400 		*cp = '\0';
401 		cp--;
402 	}
403 	len = name2oid(bufp, mib);
404 
405 	if (len < 0) {
406 		if (iflag)
407 			return (0);
408 		if (qflag)
409 			return (1);
410 		else {
411 			if (errno == ENOENT) {
412 				warnx("unknown oid '%s'%s", bufp, line);
413 			} else {
414 				warn("unknown oid '%s'%s", bufp, line);
415 			}
416 			return (1);
417 		}
418 	}
419 
420 	if (oidfmt(mib, len, fmt, &kind)) {
421 		warn("couldn't find format of oid '%s'%s", bufp, line);
422 		if (iflag)
423 			return (1);
424 		else
425 			exit(1);
426 	}
427 
428 	if (newvalstr == NULL || dflag) {
429 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
430 			if (dflag) {
431 				i = show_var(mib, len);
432 				if (!i && !bflag)
433 					putchar('\n');
434 			}
435 			sysctl_all(mib, len);
436 		} else {
437 			i = show_var(mib, len);
438 			if (!i && !bflag)
439 				putchar('\n');
440 		}
441 	} else {
442 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
443 			warnx("oid '%s' isn't a leaf node%s", bufp, line);
444 			return (1);
445 		}
446 
447 		if (!(kind & CTLFLAG_WR)) {
448 			if (kind & CTLFLAG_TUN) {
449 				warnx("oid '%s' is a read only tunable%s", bufp, line);
450 				warnx("Tunable values are set in /boot/loader.conf");
451 			} else
452 				warnx("oid '%s' is read only%s", bufp, line);
453 			return (1);
454 		}
455 
456 		switch (kind & CTLTYPE) {
457 		case CTLTYPE_INT:
458 		case CTLTYPE_UINT:
459 		case CTLTYPE_LONG:
460 		case CTLTYPE_ULONG:
461 		case CTLTYPE_S8:
462 		case CTLTYPE_S16:
463 		case CTLTYPE_S32:
464 		case CTLTYPE_S64:
465 		case CTLTYPE_U8:
466 		case CTLTYPE_U16:
467 		case CTLTYPE_U32:
468 		case CTLTYPE_U64:
469 			if (strlen(newvalstr) == 0) {
470 				warnx("empty numeric value");
471 				return (1);
472 			}
473 			/* FALLTHROUGH */
474 		case CTLTYPE_STRING:
475 			break;
476 		default:
477 			warnx("oid '%s' is type %d,"
478 				" cannot set that%s", bufp,
479 				kind & CTLTYPE, line);
480 			return (1);
481 		}
482 
483 		newbuf = NULL;
484 
485 		switch (kind & CTLTYPE) {
486 		case CTLTYPE_STRING:
487 			newval = newvalstr;
488 			break;
489 		default:
490 			newsize = 0;
491 			while ((cp = strsep(&newvalstr, " ,")) != NULL) {
492 				if (*cp == '\0')
493 					continue;
494 				if (!parse_numeric(cp, fmt, kind, &newbuf,
495 				    &newsize)) {
496 					warnx("invalid %s '%s'%s",
497 					    ctl_typename[kind & CTLTYPE],
498 					    cp, line);
499 					free(newbuf);
500 					return (1);
501 				}
502 			}
503 			newval = newbuf;
504 			break;
505 		}
506 
507 		i = show_var(mib, len);
508 		if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
509 			free(newbuf);
510 			if (!i && !bflag)
511 				putchar('\n');
512 			switch (errno) {
513 			case EOPNOTSUPP:
514 				warnx("%s: value is not available%s",
515 					string, line);
516 				return (1);
517 			case ENOTDIR:
518 				warnx("%s: specification is incomplete%s",
519 					string, line);
520 				return (1);
521 			case ENOMEM:
522 				warnx("%s: type is unknown to this program%s",
523 					string, line);
524 				return (1);
525 			default:
526 				warn("%s%s", string, line);
527 				return (1);
528 			}
529 		}
530 		free(newbuf);
531 		if (!bflag)
532 			printf(" -> ");
533 		i = nflag;
534 		nflag = 1;
535 		j = show_var(mib, len);
536 		if (!j && !bflag)
537 			putchar('\n');
538 		nflag = i;
539 	}
540 
541 	return (0);
542 }
543 
544 static int
545 parsefile(const char *filename)
546 {
547 	FILE *file;
548 	char line[BUFSIZ], *p, *pq, *pdq;
549 	int warncount = 0, lineno = 0;
550 
551 	file = fopen(filename, "r");
552 	if (file == NULL)
553 		err(EX_NOINPUT, "%s", filename);
554 	while (fgets(line, sizeof(line), file) != NULL) {
555 		lineno++;
556 		p = line;
557 		pq = strchr(line, '\'');
558 		pdq = strchr(line, '\"');
559 		/* Replace the first # with \0. */
560 		while((p = strchr(p, '#')) != NULL) {
561 			if (pq != NULL && p > pq) {
562 				if ((p = strchr(pq+1, '\'')) != NULL)
563 					*(++p) = '\0';
564 				break;
565 			} else if (pdq != NULL && p > pdq) {
566 				if ((p = strchr(pdq+1, '\"')) != NULL)
567 					*(++p) = '\0';
568 				break;
569 			} else if (p == line || *(p-1) != '\\') {
570 				*p = '\0';
571 				break;
572 			}
573 			p++;
574 		}
575 		/* Trim spaces */
576 		p = line + strlen(line) - 1;
577 		while (p >= line && isspace((int)*p)) {
578 			*p = '\0';
579 			p--;
580 		}
581 		p = line;
582 		while (isspace((int)*p))
583 			p++;
584 		if (*p == '\0')
585 			continue;
586 		else
587 			warncount += parse(p, lineno);
588 	}
589 	fclose(file);
590 
591 	return (warncount);
592 }
593 
594 /* These functions will dump out various interesting structures. */
595 
596 static int
597 S_clockinfo(size_t l2, void *p)
598 {
599 	struct clockinfo *ci = (struct clockinfo*)p;
600 
601 	if (l2 != sizeof(*ci)) {
602 		warnx("S_clockinfo %zu != %zu", l2, sizeof(*ci));
603 		return (1);
604 	}
605 	printf(hflag ? "{ hz = %'d, tick = %'d, profhz = %'d, stathz = %'d }" :
606 		"{ hz = %d, tick = %d, profhz = %d, stathz = %d }",
607 		ci->hz, ci->tick, ci->profhz, ci->stathz);
608 	return (0);
609 }
610 
611 static int
612 S_loadavg(size_t l2, void *p)
613 {
614 	struct loadavg *tv = (struct loadavg*)p;
615 
616 	if (l2 != sizeof(*tv)) {
617 		warnx("S_loadavg %zu != %zu", l2, sizeof(*tv));
618 		return (1);
619 	}
620 	printf(hflag ? "{ %'.2f %'.2f %'.2f }" : "{ %.2f %.2f %.2f }",
621 		(double)tv->ldavg[0]/(double)tv->fscale,
622 		(double)tv->ldavg[1]/(double)tv->fscale,
623 		(double)tv->ldavg[2]/(double)tv->fscale);
624 	return (0);
625 }
626 
627 static int
628 S_timeval(size_t l2, void *p)
629 {
630 	struct timeval *tv = (struct timeval*)p;
631 	time_t tv_sec;
632 	char *p1, *p2;
633 
634 	if (l2 != sizeof(*tv)) {
635 		warnx("S_timeval %zu != %zu", l2, sizeof(*tv));
636 		return (1);
637 	}
638 	printf(hflag ? "{ sec = %'jd, usec = %'ld } " :
639 		"{ sec = %jd, usec = %ld } ",
640 		(intmax_t)tv->tv_sec, tv->tv_usec);
641 	tv_sec = tv->tv_sec;
642 	p1 = strdup(ctime(&tv_sec));
643 	for (p2=p1; *p2 ; p2++)
644 		if (*p2 == '\n')
645 			*p2 = '\0';
646 	fputs(p1, stdout);
647 	free(p1);
648 	return (0);
649 }
650 
651 static int
652 S_vmtotal(size_t l2, void *p)
653 {
654 	struct vmtotal *v;
655 	int pageKilo;
656 
657 	if (l2 != sizeof(*v)) {
658 		warnx("S_vmtotal %zu != %zu", l2, sizeof(*v));
659 		return (1);
660 	}
661 
662 	v = p;
663 	pageKilo = getpagesize() / 1024;
664 
665 #define	pg2k(a)	((uintmax_t)(a) * pageKilo)
666 	printf("\nSystem wide totals computed every five seconds:"
667 	    " (values in kilobytes)\n");
668 	printf("===============================================\n");
669 	printf("Processes:\t\t(RUNQ: %d Disk Wait: %d Page Wait: "
670 	    "%d Sleep: %d)\n",
671 	    v->t_rq, v->t_dw, v->t_pw, v->t_sl);
672 	printf("Virtual Memory:\t\t(Total: %juK Active: %juK)\n",
673 	    pg2k(v->t_vm), pg2k(v->t_avm));
674 	printf("Real Memory:\t\t(Total: %juK Active: %juK)\n",
675 	    pg2k(v->t_rm), pg2k(v->t_arm));
676 	printf("Shared Virtual Memory:\t(Total: %juK Active: %juK)\n",
677 	    pg2k(v->t_vmshr), pg2k(v->t_avmshr));
678 	printf("Shared Real Memory:\t(Total: %juK Active: %juK)\n",
679 	    pg2k(v->t_rmshr), pg2k(v->t_armshr));
680 	printf("Free Memory:\t%juK", pg2k(v->t_free));
681 	return (0);
682 }
683 
684 static int
685 S_input_id(size_t l2, void *p)
686 {
687 	struct input_id *id = p;
688 
689 	if (l2 != sizeof(*id)) {
690 		warnx("S_input_id %zu != %zu", l2, sizeof(*id));
691 		return (1);
692 	}
693 
694 	printf("{ bustype = 0x%04x, vendor = 0x%04x, "
695 	    "product = 0x%04x, version = 0x%04x }",
696 	    id->bustype, id->vendor, id->product, id->version);
697 	return (0);
698 }
699 
700 static int
701 S_pagesizes(size_t l2, void *p)
702 {
703 	char buf[256];
704 	u_long *ps;
705 	size_t l;
706 	int i;
707 
708 	l = snprintf(buf, sizeof(buf), "{ ");
709 	ps = p;
710 	for (i = 0; i * sizeof(*ps) < l2 && ps[i] != 0 && l < sizeof(buf);
711 	    i++) {
712 		l += snprintf(&buf[l], sizeof(buf) - l,
713 		    "%s%lu", i == 0 ? "" : ", ", ps[i]);
714 	}
715 	if (l < sizeof(buf))
716 		(void)snprintf(&buf[l], sizeof(buf) - l, " }");
717 
718 	printf("%s", buf);
719 
720 	return (0);
721 }
722 
723 #ifdef __amd64__
724 static int
725 S_efi_map(size_t l2, void *p)
726 {
727 	struct efi_map_header *efihdr;
728 	struct efi_md *map;
729 	const char *type;
730 	size_t efisz;
731 	int ndesc, i;
732 
733 	static const char * const types[] = {
734 		[EFI_MD_TYPE_NULL] =	"Reserved",
735 		[EFI_MD_TYPE_CODE] =	"LoaderCode",
736 		[EFI_MD_TYPE_DATA] =	"LoaderData",
737 		[EFI_MD_TYPE_BS_CODE] =	"BootServicesCode",
738 		[EFI_MD_TYPE_BS_DATA] =	"BootServicesData",
739 		[EFI_MD_TYPE_RT_CODE] =	"RuntimeServicesCode",
740 		[EFI_MD_TYPE_RT_DATA] =	"RuntimeServicesData",
741 		[EFI_MD_TYPE_FREE] =	"ConventionalMemory",
742 		[EFI_MD_TYPE_BAD] =	"UnusableMemory",
743 		[EFI_MD_TYPE_RECLAIM] =	"ACPIReclaimMemory",
744 		[EFI_MD_TYPE_FIRMWARE] = "ACPIMemoryNVS",
745 		[EFI_MD_TYPE_IOMEM] =	"MemoryMappedIO",
746 		[EFI_MD_TYPE_IOPORT] =	"MemoryMappedIOPortSpace",
747 		[EFI_MD_TYPE_PALCODE] =	"PalCode",
748 		[EFI_MD_TYPE_PERSISTENT] = "PersistentMemory",
749 	};
750 
751 	/*
752 	 * Memory map data provided by UEFI via the GetMemoryMap
753 	 * Boot Services API.
754 	 */
755 	if (l2 < sizeof(*efihdr)) {
756 		warnx("S_efi_map length less than header");
757 		return (1);
758 	}
759 	efihdr = p;
760 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
761 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
762 
763 	if (efihdr->descriptor_size == 0)
764 		return (0);
765 	if (l2 != efisz + efihdr->memory_size) {
766 		warnx("S_efi_map length mismatch %zu vs %zu", l2, efisz +
767 		    efihdr->memory_size);
768 		return (1);
769 	}
770 	ndesc = efihdr->memory_size / efihdr->descriptor_size;
771 
772 	printf("\n%23s %12s %12s %8s %4s",
773 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
774 
775 	for (i = 0; i < ndesc; i++,
776 	    map = efi_next_descriptor(map, efihdr->descriptor_size)) {
777 		type = NULL;
778 		if (map->md_type < nitems(types))
779 			type = types[map->md_type];
780 		if (type == NULL)
781 			type = "<INVALID>";
782 		printf("\n%23s %012jx %12p %08jx ", type,
783 		    (uintmax_t)map->md_phys, map->md_virt,
784 		    (uintmax_t)map->md_pages);
785 		if (map->md_attr & EFI_MD_ATTR_UC)
786 			printf("UC ");
787 		if (map->md_attr & EFI_MD_ATTR_WC)
788 			printf("WC ");
789 		if (map->md_attr & EFI_MD_ATTR_WT)
790 			printf("WT ");
791 		if (map->md_attr & EFI_MD_ATTR_WB)
792 			printf("WB ");
793 		if (map->md_attr & EFI_MD_ATTR_UCE)
794 			printf("UCE ");
795 		if (map->md_attr & EFI_MD_ATTR_WP)
796 			printf("WP ");
797 		if (map->md_attr & EFI_MD_ATTR_RP)
798 			printf("RP ");
799 		if (map->md_attr & EFI_MD_ATTR_XP)
800 			printf("XP ");
801 		if (map->md_attr & EFI_MD_ATTR_RT)
802 			printf("RUNTIME");
803 	}
804 	return (0);
805 }
806 #endif
807 
808 #if defined(__amd64__) || defined(__i386__)
809 static int
810 S_bios_smap_xattr(size_t l2, void *p)
811 {
812 	struct bios_smap_xattr *smap, *end;
813 
814 	if (l2 % sizeof(*smap) != 0) {
815 		warnx("S_bios_smap_xattr %zu is not a multiple of %zu", l2,
816 		    sizeof(*smap));
817 		return (1);
818 	}
819 
820 	end = (struct bios_smap_xattr *)((char *)p + l2);
821 	for (smap = p; smap < end; smap++)
822 		printf("\nSMAP type=%02x, xattr=%02x, base=%016jx, len=%016jx",
823 		    smap->type, smap->xattr, (uintmax_t)smap->base,
824 		    (uintmax_t)smap->length);
825 	return (0);
826 }
827 #endif
828 
829 static int
830 strIKtoi(const char *str, char **endptrp, const char *fmt)
831 {
832 	int kelv;
833 	float temp;
834 	size_t len;
835 	const char *p;
836 	int prec, i;
837 
838 	assert(errno == 0);
839 
840 	len = strlen(str);
841 	/* caller already checked this */
842 	assert(len > 0);
843 
844 	/*
845 	 * A format of "IK" is in deciKelvin. A format of "IK3" is in
846 	 * milliKelvin. The single digit following IK is log10 of the
847 	 * multiplying factor to convert Kelvin into the untis of this sysctl,
848 	 * or the dividing factor to convert the sysctl value to Kelvin. Numbers
849 	 * larger than 6 will run into precision issues with 32-bit integers.
850 	 * Characters that aren't ASCII digits after the 'K' are ignored. No
851 	 * localization is present because this is an interface from the kernel
852 	 * to this program (eg not an end-user interface), so isdigit() isn't
853 	 * used here.
854 	 */
855 	if (fmt[2] != '\0' && fmt[2] >= '0' && fmt[2] <= '9')
856 		prec = fmt[2] - '0';
857 	else
858 		prec = 1;
859 	p = &str[len - 1];
860 	if (*p == 'C' || *p == 'F' || *p == 'K') {
861 		temp = strtof(str, endptrp);
862 		if (*endptrp != str && *endptrp == p && errno == 0) {
863 			if (*p == 'F')
864 				temp = (temp - 32) * 5 / 9;
865 			*endptrp = NULL;
866 			if (*p != 'K')
867 				temp += 273.15;
868 			for (i = 0; i < prec; i++)
869 				temp *= 10.0;
870 			return ((int)(temp + 0.5));
871 		}
872 	} else {
873 		/* No unit specified -> treat it as a raw number */
874 		kelv = (int)strtol(str, endptrp, 10);
875 		if (*endptrp != str && *endptrp == p && errno == 0) {
876 			*endptrp = NULL;
877 			return (kelv);
878 		}
879 	}
880 
881 	errno = ERANGE;
882 	return (0);
883 }
884 
885 /*
886  * These functions uses a presently undocumented interface to the kernel
887  * to walk the tree and get the type so it can print the value.
888  * This interface is under work and consideration, and should probably
889  * be killed with a big axe by the first person who can find the time.
890  * (be aware though, that the proper interface isn't as obvious as it
891  * may seem, there are various conflicting requirements.
892  */
893 
894 static int
895 name2oid(const char *name, int *oidp)
896 {
897 	int oid[2];
898 	int i;
899 	size_t j;
900 
901 	oid[0] = 0;
902 	oid[1] = 3;
903 
904 	j = CTL_MAXNAME * sizeof(int);
905 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
906 	if (i < 0)
907 		return (i);
908 	j /= sizeof(int);
909 	return (j);
910 }
911 
912 static int
913 oidfmt(int *oid, int len, char *fmt, u_int *kind)
914 {
915 	int qoid[CTL_MAXNAME+2];
916 	u_char buf[BUFSIZ];
917 	int i;
918 	size_t j;
919 
920 	qoid[0] = 0;
921 	qoid[1] = 4;
922 	memcpy(qoid + 2, oid, len * sizeof(int));
923 
924 	j = sizeof(buf);
925 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
926 	if (i)
927 		err(1, "sysctl fmt %d %zu %d", i, j, errno);
928 
929 	if (kind)
930 		*kind = *(u_int *)buf;
931 
932 	if (fmt)
933 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
934 	return (0);
935 }
936 
937 /*
938  * This formats and outputs the value of one variable
939  *
940  * Returns zero if anything was actually output.
941  * Returns one if didn't know what to do with this.
942  * Return minus one if we had errors.
943  */
944 static int
945 show_var(int *oid, int nlen)
946 {
947 	u_char buf[BUFSIZ], *val, *oval, *p;
948 	char name[BUFSIZ], fmt[BUFSIZ];
949 	const char *sep, *sep1, *prntype;
950 	int qoid[CTL_MAXNAME+2];
951 	uintmax_t umv;
952 	intmax_t mv;
953 	int i, hexlen, sign, ctltype;
954 	size_t intlen;
955 	size_t j, len;
956 	u_int kind;
957 	float base;
958 	int (*func)(size_t, void *);
959 	int prec;
960 
961 	/* Silence GCC. */
962 	umv = mv = intlen = 0;
963 
964 	bzero(buf, BUFSIZ);
965 	bzero(fmt, BUFSIZ);
966 	bzero(name, BUFSIZ);
967 	qoid[0] = 0;
968 	memcpy(qoid + 2, oid, nlen * sizeof(int));
969 
970 	qoid[1] = 1;
971 	j = sizeof(name);
972 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
973 	if (i || !j)
974 		err(1, "sysctl name %d %zu %d", i, j, errno);
975 
976 	oidfmt(oid, nlen, fmt, &kind);
977 	/* if Wflag then only list sysctls that are writeable and not stats. */
978 	if (Wflag && ((kind & CTLFLAG_WR) == 0 || (kind & CTLFLAG_STATS) != 0))
979 		return 1;
980 
981 	/* if Tflag then only list sysctls that are tuneables. */
982 	if (Tflag && (kind & CTLFLAG_TUN) == 0)
983 		return 1;
984 
985 	if (Nflag) {
986 		printf("%s", name);
987 		return (0);
988 	}
989 
990 	if (eflag)
991 		sep = "=";
992 	else
993 		sep = ": ";
994 
995 	ctltype = (kind & CTLTYPE);
996 	if (tflag || dflag) {
997 		if (!nflag)
998 			printf("%s%s", name, sep);
999         	if (ctl_typename[ctltype] != NULL)
1000             		prntype = ctl_typename[ctltype];
1001         	else
1002             		prntype = "unknown";
1003 		if (tflag && dflag)
1004 			printf("%s%s", prntype, sep);
1005 		else if (tflag) {
1006 			printf("%s", prntype);
1007 			return (0);
1008 		}
1009 		qoid[1] = 5;
1010 		j = sizeof(buf);
1011 		i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
1012 		printf("%s", buf);
1013 		return (0);
1014 	}
1015 
1016 	/* don't fetch opaques that we don't know how to print */
1017 	if (ctltype == CTLTYPE_OPAQUE) {
1018 		if (strcmp(fmt, "S,clockinfo") == 0)
1019 			func = S_clockinfo;
1020 		else if (strcmp(fmt, "S,timeval") == 0)
1021 			func = S_timeval;
1022 		else if (strcmp(fmt, "S,loadavg") == 0)
1023 			func = S_loadavg;
1024 		else if (strcmp(fmt, "S,vmtotal") == 0)
1025 			func = S_vmtotal;
1026 		else if (strcmp(fmt, "S,input_id") == 0)
1027 			func = S_input_id;
1028 		else if (strcmp(fmt, "S,pagesizes") == 0)
1029 			func = S_pagesizes;
1030 #ifdef __amd64__
1031 		else if (strcmp(fmt, "S,efi_map_header") == 0)
1032 			func = S_efi_map;
1033 #endif
1034 #if defined(__amd64__) || defined(__i386__)
1035 		else if (strcmp(fmt, "S,bios_smap_xattr") == 0)
1036 			func = S_bios_smap_xattr;
1037 #endif
1038 		else {
1039 			func = NULL;
1040 			if (!bflag && !oflag && !xflag)
1041 				return (1);
1042 		}
1043 	}
1044 
1045 	/* find an estimate of how much we need for this var */
1046 	if (Bflag)
1047 		j = Bflag;
1048 	else {
1049 		j = 0;
1050 		i = sysctl(oid, nlen, 0, &j, 0, 0);
1051 		j += j; /* we want to be sure :-) */
1052 	}
1053 
1054 	val = oval = malloc(j + 1);
1055 	if (val == NULL) {
1056 		warnx("malloc failed");
1057 		return (1);
1058 	}
1059 	len = j;
1060 	i = sysctl(oid, nlen, val, &len, 0, 0);
1061 	if (i != 0 || (len == 0 && ctltype != CTLTYPE_STRING)) {
1062 		free(oval);
1063 		return (1);
1064 	}
1065 
1066 	if (bflag) {
1067 		fwrite(val, 1, len, stdout);
1068 		free(oval);
1069 		return (0);
1070 	}
1071 	val[len] = '\0';
1072 	p = val;
1073 	sign = ctl_sign[ctltype];
1074 	intlen = ctl_size[ctltype];
1075 
1076 	switch (ctltype) {
1077 	case CTLTYPE_STRING:
1078 		if (!nflag)
1079 			printf("%s%s", name, sep);
1080 		printf("%.*s", (int)len, p);
1081 		free(oval);
1082 		return (0);
1083 
1084 	case CTLTYPE_INT:
1085 	case CTLTYPE_UINT:
1086 	case CTLTYPE_LONG:
1087 	case CTLTYPE_ULONG:
1088 	case CTLTYPE_S8:
1089 	case CTLTYPE_S16:
1090 	case CTLTYPE_S32:
1091 	case CTLTYPE_S64:
1092 	case CTLTYPE_U8:
1093 	case CTLTYPE_U16:
1094 	case CTLTYPE_U32:
1095 	case CTLTYPE_U64:
1096 		if (!nflag)
1097 			printf("%s%s", name, sep);
1098 		hexlen = 2 + (intlen * CHAR_BIT + 3) / 4;
1099 		sep1 = "";
1100 		while (len >= intlen) {
1101 			switch (kind & CTLTYPE) {
1102 			case CTLTYPE_INT:
1103 			case CTLTYPE_UINT:
1104 				umv = *(u_int *)p;
1105 				mv = *(int *)p;
1106 				break;
1107 			case CTLTYPE_LONG:
1108 			case CTLTYPE_ULONG:
1109 				umv = *(u_long *)p;
1110 				mv = *(long *)p;
1111 				break;
1112 			case CTLTYPE_S8:
1113 			case CTLTYPE_U8:
1114 				umv = *(uint8_t *)p;
1115 				mv = *(int8_t *)p;
1116 				break;
1117 			case CTLTYPE_S16:
1118 			case CTLTYPE_U16:
1119 				umv = *(uint16_t *)p;
1120 				mv = *(int16_t *)p;
1121 				break;
1122 			case CTLTYPE_S32:
1123 			case CTLTYPE_U32:
1124 				umv = *(uint32_t *)p;
1125 				mv = *(int32_t *)p;
1126 				break;
1127 			case CTLTYPE_S64:
1128 			case CTLTYPE_U64:
1129 				umv = *(uint64_t *)p;
1130 				mv = *(int64_t *)p;
1131 				break;
1132 			}
1133 			fputs(sep1, stdout);
1134 			if (xflag)
1135 				printf("%#0*jx", hexlen, umv);
1136 			else if (!sign)
1137 				printf(hflag ? "%'ju" : "%ju", umv);
1138 			else if (fmt[1] == 'K') {
1139 				if (mv < 0)
1140 					printf("%jd", mv);
1141 				else {
1142 					/*
1143 					 * See strIKtoi for details on fmt.
1144 					 */
1145 					prec = 1;
1146 					if (fmt[2] != '\0')
1147 						prec = fmt[2] - '0';
1148 					base = 1.0;
1149 					for (int i = 0; i < prec; i++)
1150 						base *= 10.0;
1151 					printf("%.*fC", prec,
1152 					    (float)mv / base - 273.15);
1153 				}
1154 			} else
1155 				printf(hflag ? "%'jd" : "%jd", mv);
1156 			sep1 = " ";
1157 			len -= intlen;
1158 			p += intlen;
1159 		}
1160 		free(oval);
1161 		return (0);
1162 
1163 	case CTLTYPE_OPAQUE:
1164 		i = 0;
1165 		if (func) {
1166 			if (!nflag)
1167 				printf("%s%s", name, sep);
1168 			i = (*func)(len, p);
1169 			free(oval);
1170 			return (i);
1171 		}
1172 		/* FALLTHROUGH */
1173 	default:
1174 		if (!oflag && !xflag) {
1175 			free(oval);
1176 			return (1);
1177 		}
1178 		if (!nflag)
1179 			printf("%s%s", name, sep);
1180 		printf("Format:%s Length:%zu Dump:0x", fmt, len);
1181 		while (len-- && (xflag || p < val + 16))
1182 			printf("%02x", *p++);
1183 		if (!xflag && len > 16)
1184 			printf("...");
1185 		free(oval);
1186 		return (0);
1187 	}
1188 	free(oval);
1189 	return (1);
1190 }
1191 
1192 static int
1193 sysctl_all(int *oid, int len)
1194 {
1195 	int name1[22], name2[22];
1196 	int i, j;
1197 	size_t l1, l2;
1198 
1199 	name1[0] = 0;
1200 	name1[1] = 2;
1201 	l1 = 2;
1202 	if (len) {
1203 		memcpy(name1+2, oid, len * sizeof(int));
1204 		l1 += len;
1205 	} else {
1206 		name1[2] = 1;
1207 		l1++;
1208 	}
1209 	for (;;) {
1210 		l2 = sizeof(name2);
1211 		j = sysctl(name1, l1, name2, &l2, 0, 0);
1212 		if (j < 0) {
1213 			if (errno == ENOENT)
1214 				return (0);
1215 			else
1216 				err(1, "sysctl(getnext) %d %zu", j, l2);
1217 		}
1218 
1219 		l2 /= sizeof(int);
1220 
1221 		if (len < 0 || l2 < (unsigned int)len)
1222 			return (0);
1223 
1224 		for (i = 0; i < len; i++)
1225 			if (name2[i] != oid[i])
1226 				return (0);
1227 
1228 		i = show_var(name2, l2);
1229 		if (!i && !bflag)
1230 			putchar('\n');
1231 
1232 		memcpy(name1+2, name2, l2 * sizeof(int));
1233 		l1 = 2 + l2;
1234 	}
1235 }
1236