xref: /freebsd/sbin/sysctl/sysctl.c (revision fcb560670601b2a4d87bb31d7531c8dcc37ee71b)
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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1993\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)from: sysctl.c	8.1 (Berkeley) 6/6/93";
39 #endif
40 static const char rcsid[] =
41   "$FreeBSD$";
42 #endif /* not lint */
43 
44 #include <sys/param.h>
45 #include <sys/time.h>
46 #include <sys/resource.h>
47 #include <sys/stat.h>
48 #include <sys/sysctl.h>
49 #include <sys/vmmeter.h>
50 
51 #ifdef __amd64__
52 #include <sys/efi.h>
53 #include <machine/metadata.h>
54 #endif
55 
56 #if defined(__amd64__) || defined(__i386__)
57 #include <machine/pc/bios.h>
58 #endif
59 
60 #include <assert.h>
61 #include <ctype.h>
62 #include <err.h>
63 #include <errno.h>
64 #include <inttypes.h>
65 #include <locale.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <sysexits.h>
70 #include <unistd.h>
71 
72 static const char *conffile;
73 
74 static int	aflag, bflag, dflag, eflag, hflag, iflag;
75 static int	Nflag, nflag, oflag, qflag, Tflag, Wflag, xflag;
76 
77 static int	oidfmt(int *, int, char *, u_int *);
78 static int	parsefile(const char *);
79 static int	parse(const char *, int);
80 static int	show_var(int *, int);
81 static int	sysctl_all(int *oid, int len);
82 static int	name2oid(const char *, int *);
83 
84 static int	strIKtoi(const char *, char **);
85 
86 static int ctl_sign[CTLTYPE+1] = {
87 	[CTLTYPE_INT] = 1,
88 	[CTLTYPE_LONG] = 1,
89 	[CTLTYPE_S64] = 1,
90 };
91 
92 static int ctl_size[CTLTYPE+1] = {
93 	[CTLTYPE_INT] = sizeof(int),
94 	[CTLTYPE_UINT] = sizeof(u_int),
95 	[CTLTYPE_LONG] = sizeof(long),
96 	[CTLTYPE_ULONG] = sizeof(u_long),
97 	[CTLTYPE_S64] = sizeof(int64_t),
98 	[CTLTYPE_U64] = sizeof(uint64_t),
99 };
100 
101 static const char *ctl_typename[CTLTYPE+1] = {
102 	[CTLTYPE_INT] = "integer",
103 	[CTLTYPE_UINT] = "unsigned integer",
104 	[CTLTYPE_LONG] = "long integer",
105 	[CTLTYPE_ULONG] = "unsigned long",
106 	[CTLTYPE_S64] = "int64_t",
107 	[CTLTYPE_U64] = "uint64_t",
108 };
109 
110 static void
111 usage(void)
112 {
113 
114 	(void)fprintf(stderr, "%s\n%s\n",
115 	    "usage: sysctl [-bdehiNnoqTWx] [-f filename] name[=value] ...",
116 	    "       sysctl [-bdehNnoqTWx] -a");
117 	exit(1);
118 }
119 
120 int
121 main(int argc, char **argv)
122 {
123 	int ch;
124 	int warncount = 0;
125 
126 	setlocale(LC_NUMERIC, "");
127 	setbuf(stdout,0);
128 	setbuf(stderr,0);
129 
130 	while ((ch = getopt(argc, argv, "Aabdef:hiNnoqTwWxX")) != -1) {
131 		switch (ch) {
132 		case 'A':
133 			/* compatibility */
134 			aflag = oflag = 1;
135 			break;
136 		case 'a':
137 			aflag = 1;
138 			break;
139 		case 'b':
140 			bflag = 1;
141 			break;
142 		case 'd':
143 			dflag = 1;
144 			break;
145 		case 'e':
146 			eflag = 1;
147 			break;
148 		case 'f':
149 			conffile = optarg;
150 			break;
151 		case 'h':
152 			hflag = 1;
153 			break;
154 		case 'i':
155 			iflag = 1;
156 			break;
157 		case 'N':
158 			Nflag = 1;
159 			break;
160 		case 'n':
161 			nflag = 1;
162 			break;
163 		case 'o':
164 			oflag = 1;
165 			break;
166 		case 'q':
167 			qflag = 1;
168 			break;
169 		case 'T':
170 			Tflag = 1;
171 			break;
172 		case 'w':
173 			/* compatibility */
174 			/* ignored */
175 			break;
176 		case 'W':
177 			Wflag = 1;
178 			break;
179 		case 'X':
180 			/* compatibility */
181 			aflag = xflag = 1;
182 			break;
183 		case 'x':
184 			xflag = 1;
185 			break;
186 		default:
187 			usage();
188 		}
189 	}
190 	argc -= optind;
191 	argv += optind;
192 
193 	if (Nflag && nflag)
194 		usage();
195 	if (aflag && argc == 0)
196 		exit(sysctl_all(0, 0));
197 	if (argc == 0 && conffile == NULL)
198 		usage();
199 
200 	warncount = 0;
201 	if (conffile != NULL)
202 		warncount += parsefile(conffile);
203 
204 	while (argc-- > 0)
205 		warncount += parse(*argv++, 0);
206 
207 	return (warncount);
208 }
209 
210 /*
211  * Parse a name into a MIB entry.
212  * Lookup and print out the MIB entry if it exists.
213  * Set a new value if requested.
214  */
215 static int
216 parse(const char *string, int lineno)
217 {
218 	int len, i, j;
219 	const void *newval;
220 	const char *newvalstr = NULL;
221 	int intval;
222 	unsigned int uintval;
223 	long longval;
224 	unsigned long ulongval;
225 	size_t newsize = 0;
226 	int64_t i64val;
227 	uint64_t u64val;
228 	int mib[CTL_MAXNAME];
229 	char *cp, *bufp, buf[BUFSIZ], *endptr = NULL, fmt[BUFSIZ], line[BUFSIZ];
230 	u_int kind;
231 
232 	if (lineno)
233 		snprintf(line, sizeof(line), " at line %d", lineno);
234 	else
235 		line[0] = '\0';
236 
237 	cp = buf;
238 	if (snprintf(buf, BUFSIZ, "%s", string) >= BUFSIZ) {
239 		warnx("oid too long: '%s'%s", string, line);
240 		return (1);
241 	}
242 	bufp = strsep(&cp, "=:");
243 	if (cp != NULL) {
244 		/* Tflag just lists tunables, do not allow assignment */
245 		if (Tflag || Wflag) {
246 			warnx("Can't set variables when using -T or -W");
247 			usage();
248 		}
249 		while (isspace(*cp))
250 			cp++;
251 		/* Strip a pair of " or ' if any. */
252 		switch (*cp) {
253 		case '\"':
254 		case '\'':
255 			if (cp[strlen(cp) - 1] == *cp)
256 				cp[strlen(cp) - 1] = '\0';
257 			cp++;
258 		}
259 		newvalstr = cp;
260 		newsize = strlen(cp);
261 	}
262 	len = name2oid(bufp, mib);
263 
264 	if (len < 0) {
265 		if (iflag)
266 			return (0);
267 		if (qflag)
268 			return (1);
269 		else {
270 			warn("unknown oid '%s'%s", bufp, line);
271 			return (1);
272 		}
273 	}
274 
275 	if (oidfmt(mib, len, fmt, &kind)) {
276 		warn("couldn't find format of oid '%s'%s", bufp, line);
277 		if (iflag)
278 			return (1);
279 		else
280 			exit(1);
281 	}
282 
283 	if (newvalstr == NULL || dflag) {
284 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
285 			if (dflag) {
286 				i = show_var(mib, len);
287 				if (!i && !bflag)
288 					putchar('\n');
289 			}
290 			sysctl_all(mib, len);
291 		} else {
292 			i = show_var(mib, len);
293 			if (!i && !bflag)
294 				putchar('\n');
295 		}
296 	} else {
297 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
298 			warnx("oid '%s' isn't a leaf node%s", bufp, line);
299 			return (1);
300 		}
301 
302 		if (!(kind & CTLFLAG_WR)) {
303 			if (kind & CTLFLAG_TUN) {
304 				warnx("oid '%s' is a read only tunable%s", bufp, line);
305 				warnx("Tunable values are set in /boot/loader.conf");
306 			} else
307 				warnx("oid '%s' is read only%s", bufp, line);
308 			return (1);
309 		}
310 
311 		switch (kind & CTLTYPE) {
312 		case CTLTYPE_INT:
313 		case CTLTYPE_UINT:
314 		case CTLTYPE_LONG:
315 		case CTLTYPE_ULONG:
316 		case CTLTYPE_S64:
317 		case CTLTYPE_U64:
318 			if (strlen(newvalstr) == 0) {
319 				warnx("empty numeric value");
320 				return (1);
321 			}
322 			/* FALLTHROUGH */
323 		case CTLTYPE_STRING:
324 			break;
325 		default:
326 			warnx("oid '%s' is type %d,"
327 				" cannot set that%s", bufp,
328 				kind & CTLTYPE, line);
329 			return (1);
330 		}
331 
332 		errno = 0;
333 
334 		switch (kind & CTLTYPE) {
335 			case CTLTYPE_INT:
336 				if (strcmp(fmt, "IK") == 0)
337 					intval = strIKtoi(newvalstr, &endptr);
338 				else
339 					intval = (int)strtol(newvalstr, &endptr,
340 					    0);
341 				newval = &intval;
342 				newsize = sizeof(intval);
343 				break;
344 			case CTLTYPE_UINT:
345 				uintval = (int) strtoul(newvalstr, &endptr, 0);
346 				newval = &uintval;
347 				newsize = sizeof(uintval);
348 				break;
349 			case CTLTYPE_LONG:
350 				longval = strtol(newvalstr, &endptr, 0);
351 				newval = &longval;
352 				newsize = sizeof(longval);
353 				break;
354 			case CTLTYPE_ULONG:
355 				ulongval = strtoul(newvalstr, &endptr, 0);
356 				newval = &ulongval;
357 				newsize = sizeof(ulongval);
358 				break;
359 			case CTLTYPE_STRING:
360 				newval = newvalstr;
361 				break;
362 			case CTLTYPE_S64:
363 				i64val = strtoimax(newvalstr, &endptr, 0);
364 				newval = &i64val;
365 				newsize = sizeof(i64val);
366 				break;
367 			case CTLTYPE_U64:
368 				u64val = strtoumax(newvalstr, &endptr, 0);
369 				newval = &u64val;
370 				newsize = sizeof(u64val);
371 				break;
372 			default:
373 				/* NOTREACHED */
374 				abort();
375 		}
376 
377 		if (errno != 0 || endptr == newvalstr ||
378 		    (endptr != NULL && *endptr != '\0')) {
379 			warnx("invalid %s '%s'%s", ctl_typename[kind & CTLTYPE],
380 			    newvalstr, line);
381 			return (1);
382 		}
383 
384 		i = show_var(mib, len);
385 		if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
386 			if (!i && !bflag)
387 				putchar('\n');
388 			switch (errno) {
389 			case EOPNOTSUPP:
390 				warnx("%s: value is not available%s",
391 					string, line);
392 				return (1);
393 			case ENOTDIR:
394 				warnx("%s: specification is incomplete%s",
395 					string, line);
396 				return (1);
397 			case ENOMEM:
398 				warnx("%s: type is unknown to this program%s",
399 					string, line);
400 				return (1);
401 			default:
402 				warn("%s%s", string, line);
403 				return (1);
404 			}
405 		}
406 		if (!bflag)
407 			printf(" -> ");
408 		i = nflag;
409 		nflag = 1;
410 		j = show_var(mib, len);
411 		if (!j && !bflag)
412 			putchar('\n');
413 		nflag = i;
414 	}
415 
416 	return (0);
417 }
418 
419 static int
420 parsefile(const char *filename)
421 {
422 	FILE *file;
423 	char line[BUFSIZ], *p, *pq, *pdq;
424 	int warncount = 0, lineno = 0;
425 
426 	file = fopen(filename, "r");
427 	if (file == NULL)
428 		err(EX_NOINPUT, "%s", filename);
429 	while (fgets(line, sizeof(line), file) != NULL) {
430 		lineno++;
431 		p = line;
432 		pq = strchr(line, '\'');
433 		pdq = strchr(line, '\"');
434 		/* Replace the first # with \0. */
435 		while((p = strchr(p, '#')) != NULL) {
436 			if (pq != NULL && p > pq) {
437 				if ((p = strchr(pq+1, '\'')) != NULL)
438 					*(++p) = '\0';
439 				break;
440 			} else if (pdq != NULL && p > pdq) {
441 				if ((p = strchr(pdq+1, '\"')) != NULL)
442 					*(++p) = '\0';
443 				break;
444 			} else if (p == line || *(p-1) != '\\') {
445 				*p = '\0';
446 				break;
447 			}
448 			p++;
449 		}
450 		/* Trim spaces */
451 		p = line + strlen(line) - 1;
452 		while (p >= line && isspace((int)*p)) {
453 			*p = '\0';
454 			p--;
455 		}
456 		p = line;
457 		while (isspace((int)*p))
458 			p++;
459 		if (*p == '\0')
460 			continue;
461 		else
462 			warncount += parse(p, lineno);
463 	}
464 	fclose(file);
465 
466 	return (warncount);
467 }
468 
469 /* These functions will dump out various interesting structures. */
470 
471 static int
472 S_clockinfo(size_t l2, void *p)
473 {
474 	struct clockinfo *ci = (struct clockinfo*)p;
475 
476 	if (l2 != sizeof(*ci)) {
477 		warnx("S_clockinfo %zu != %zu", l2, sizeof(*ci));
478 		return (1);
479 	}
480 	printf(hflag ? "{ hz = %'d, tick = %'d, profhz = %'d, stathz = %'d }" :
481 		"{ hz = %d, tick = %d, profhz = %d, stathz = %d }",
482 		ci->hz, ci->tick, ci->profhz, ci->stathz);
483 	return (0);
484 }
485 
486 static int
487 S_loadavg(size_t l2, void *p)
488 {
489 	struct loadavg *tv = (struct loadavg*)p;
490 
491 	if (l2 != sizeof(*tv)) {
492 		warnx("S_loadavg %zu != %zu", l2, sizeof(*tv));
493 		return (1);
494 	}
495 	printf(hflag ? "{ %'.2f %'.2f %'.2f }" : "{ %.2f %.2f %.2f }",
496 		(double)tv->ldavg[0]/(double)tv->fscale,
497 		(double)tv->ldavg[1]/(double)tv->fscale,
498 		(double)tv->ldavg[2]/(double)tv->fscale);
499 	return (0);
500 }
501 
502 static int
503 S_timeval(size_t l2, void *p)
504 {
505 	struct timeval *tv = (struct timeval*)p;
506 	time_t tv_sec;
507 	char *p1, *p2;
508 
509 	if (l2 != sizeof(*tv)) {
510 		warnx("S_timeval %zu != %zu", l2, sizeof(*tv));
511 		return (1);
512 	}
513 	printf(hflag ? "{ sec = %'jd, usec = %'ld } " :
514 		"{ sec = %jd, usec = %ld } ",
515 		(intmax_t)tv->tv_sec, tv->tv_usec);
516 	tv_sec = tv->tv_sec;
517 	p1 = strdup(ctime(&tv_sec));
518 	for (p2=p1; *p2 ; p2++)
519 		if (*p2 == '\n')
520 			*p2 = '\0';
521 	fputs(p1, stdout);
522 	free(p1);
523 	return (0);
524 }
525 
526 static int
527 S_vmtotal(size_t l2, void *p)
528 {
529 	struct vmtotal *v = (struct vmtotal *)p;
530 	int pageKilo = getpagesize() / 1024;
531 
532 	if (l2 != sizeof(*v)) {
533 		warnx("S_vmtotal %zu != %zu", l2, sizeof(*v));
534 		return (1);
535 	}
536 
537 	printf(
538 	    "\nSystem wide totals computed every five seconds:"
539 	    " (values in kilobytes)\n");
540 	printf("===============================================\n");
541 	printf(
542 	    "Processes:\t\t(RUNQ: %hd Disk Wait: %hd Page Wait: "
543 	    "%hd Sleep: %hd)\n",
544 	    v->t_rq, v->t_dw, v->t_pw, v->t_sl);
545 	printf(
546 	    "Virtual Memory:\t\t(Total: %dK Active: %dK)\n",
547 	    v->t_vm * pageKilo, v->t_avm * pageKilo);
548 	printf("Real Memory:\t\t(Total: %dK Active: %dK)\n",
549 	    v->t_rm * pageKilo, v->t_arm * pageKilo);
550 	printf("Shared Virtual Memory:\t(Total: %dK Active: %dK)\n",
551 	    v->t_vmshr * pageKilo, v->t_avmshr * pageKilo);
552 	printf("Shared Real Memory:\t(Total: %dK Active: %dK)\n",
553 	    v->t_rmshr * pageKilo, v->t_armshr * pageKilo);
554 	printf("Free Memory:\t%dK", v->t_free * pageKilo);
555 
556 	return (0);
557 }
558 
559 #ifdef __amd64__
560 #define efi_next_descriptor(ptr, size) \
561 	((struct efi_md *)(((uint8_t *) ptr) + size))
562 
563 static int
564 S_efi_map(size_t l2, void *p)
565 {
566 	struct efi_map_header *efihdr;
567 	struct efi_md *map;
568 	const char *type;
569 	size_t efisz;
570 	int ndesc, i;
571 
572 	static const char *types[] = {
573 		"Reserved",
574 		"LoaderCode",
575 		"LoaderData",
576 		"BootServicesCode",
577 		"BootServicesData",
578 		"RuntimeServicesCode",
579 		"RuntimeServicesData",
580 		"ConventionalMemory",
581 		"UnusableMemory",
582 		"ACPIReclaimMemory",
583 		"ACPIMemoryNVS",
584 		"MemoryMappedIO",
585 		"MemoryMappedIOPortSpace",
586 		"PalCode"
587 	};
588 
589 	/*
590 	 * Memory map data provided by UEFI via the GetMemoryMap
591 	 * Boot Services API.
592 	 */
593 	if (l2 < sizeof(*efihdr)) {
594 		warnx("S_efi_map length less than header");
595 		return (1);
596 	}
597 	efihdr = p;
598 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
599 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
600 
601 	if (efihdr->descriptor_size == 0)
602 		return (0);
603 	if (l2 != efisz + efihdr->memory_size) {
604 		warnx("S_efi_map length mismatch %zu vs %zu", l2, efisz +
605 		    efihdr->memory_size);
606 		return (1);
607 	}
608 	ndesc = efihdr->memory_size / efihdr->descriptor_size;
609 
610 	printf("\n%23s %12s %12s %8s %4s",
611 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
612 
613 	for (i = 0; i < ndesc; i++,
614 	    map = efi_next_descriptor(map, efihdr->descriptor_size)) {
615 		if (map->md_type <= EFI_MD_TYPE_PALCODE)
616 			type = types[map->md_type];
617 		else
618 			type = "<INVALID>";
619 		printf("\n%23s %012lx %12p %08lx ", type, map->md_phys,
620 		    map->md_virt, map->md_pages);
621 		if (map->md_attr & EFI_MD_ATTR_UC)
622 			printf("UC ");
623 		if (map->md_attr & EFI_MD_ATTR_WC)
624 			printf("WC ");
625 		if (map->md_attr & EFI_MD_ATTR_WT)
626 			printf("WT ");
627 		if (map->md_attr & EFI_MD_ATTR_WB)
628 			printf("WB ");
629 		if (map->md_attr & EFI_MD_ATTR_UCE)
630 			printf("UCE ");
631 		if (map->md_attr & EFI_MD_ATTR_WP)
632 			printf("WP ");
633 		if (map->md_attr & EFI_MD_ATTR_RP)
634 			printf("RP ");
635 		if (map->md_attr & EFI_MD_ATTR_XP)
636 			printf("XP ");
637 		if (map->md_attr & EFI_MD_ATTR_RT)
638 			printf("RUNTIME");
639 	}
640 	return (0);
641 }
642 #endif
643 
644 #if defined(__amd64__) || defined(__i386__)
645 static int
646 S_bios_smap_xattr(size_t l2, void *p)
647 {
648 	struct bios_smap_xattr *smap, *end;
649 
650 	if (l2 % sizeof(*smap) != 0) {
651 		warnx("S_bios_smap_xattr %zu is not a multiple of %zu", l2,
652 		    sizeof(*smap));
653 		return (1);
654 	}
655 
656 	end = (struct bios_smap_xattr *)((char *)p + l2);
657 	for (smap = p; smap < end; smap++)
658 		printf("\nSMAP type=%02x, xattr=%02x, base=%016jx, len=%016jx",
659 		    smap->type, smap->xattr, (uintmax_t)smap->base,
660 		    (uintmax_t)smap->length);
661 	return (0);
662 }
663 #endif
664 
665 static int
666 strIKtoi(const char *str, char **endptrp)
667 {
668 	int kelv;
669 	float temp;
670 	size_t len;
671 	const char *p;
672 
673 	assert(errno == 0);
674 
675 	len = strlen(str);
676 	/* caller already checked this */
677 	assert(len > 0);
678 
679 	p = &str[len - 1];
680 	if (*p == 'C' || *p == 'F') {
681 		temp = strtof(str, endptrp);
682 		if (*endptrp != str && *endptrp == p && errno == 0) {
683 			if (*p == 'F')
684 				temp = (temp - 32) * 5 / 9;
685 			*endptrp = NULL;
686 			return (temp * 10 + 2732);
687 		}
688 	} else {
689 		kelv = (int)strtol(str, endptrp, 10);
690 		if (*endptrp != str && *endptrp == p && errno == 0) {
691 			*endptrp = NULL;
692 			return (kelv);
693 		}
694 	}
695 
696 	errno = ERANGE;
697 	return (0);
698 }
699 
700 /*
701  * These functions uses a presently undocumented interface to the kernel
702  * to walk the tree and get the type so it can print the value.
703  * This interface is under work and consideration, and should probably
704  * be killed with a big axe by the first person who can find the time.
705  * (be aware though, that the proper interface isn't as obvious as it
706  * may seem, there are various conflicting requirements.
707  */
708 
709 static int
710 name2oid(const char *name, int *oidp)
711 {
712 	int oid[2];
713 	int i;
714 	size_t j;
715 
716 	oid[0] = 0;
717 	oid[1] = 3;
718 
719 	j = CTL_MAXNAME * sizeof(int);
720 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
721 	if (i < 0)
722 		return (i);
723 	j /= sizeof(int);
724 	return (j);
725 }
726 
727 static int
728 oidfmt(int *oid, int len, char *fmt, u_int *kind)
729 {
730 	int qoid[CTL_MAXNAME+2];
731 	u_char buf[BUFSIZ];
732 	int i;
733 	size_t j;
734 
735 	qoid[0] = 0;
736 	qoid[1] = 4;
737 	memcpy(qoid + 2, oid, len * sizeof(int));
738 
739 	j = sizeof(buf);
740 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
741 	if (i)
742 		err(1, "sysctl fmt %d %zu %d", i, j, errno);
743 
744 	if (kind)
745 		*kind = *(u_int *)buf;
746 
747 	if (fmt)
748 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
749 	return (0);
750 }
751 
752 /*
753  * This formats and outputs the value of one variable
754  *
755  * Returns zero if anything was actually output.
756  * Returns one if didn't know what to do with this.
757  * Return minus one if we had errors.
758  */
759 static int
760 show_var(int *oid, int nlen)
761 {
762 	u_char buf[BUFSIZ], *val, *oval, *p;
763 	char name[BUFSIZ], fmt[BUFSIZ];
764 	const char *sep, *sep1;
765 	int qoid[CTL_MAXNAME+2];
766 	uintmax_t umv;
767 	intmax_t mv;
768 	int i, hexlen, sign, ctltype;
769 	size_t intlen;
770 	size_t j, len;
771 	u_int kind;
772 	int (*func)(size_t, void *);
773 
774 	/* Silence GCC. */
775 	umv = mv = intlen = 0;
776 
777 	bzero(buf, BUFSIZ);
778 	bzero(fmt, BUFSIZ);
779 	bzero(name, BUFSIZ);
780 	qoid[0] = 0;
781 	memcpy(qoid + 2, oid, nlen * sizeof(int));
782 
783 	qoid[1] = 1;
784 	j = sizeof(name);
785 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
786 	if (i || !j)
787 		err(1, "sysctl name %d %zu %d", i, j, errno);
788 
789 	oidfmt(oid, nlen, fmt, &kind);
790 	/* if Wflag then only list sysctls that are writeable and not stats. */
791 	if (Wflag && ((kind & CTLFLAG_WR) == 0 || (kind & CTLFLAG_STATS) != 0))
792 		return 1;
793 
794 	/* if Tflag then only list sysctls that are tuneables. */
795 	if (Tflag && (kind & CTLFLAG_TUN) == 0)
796 		return 1;
797 
798 	if (Nflag) {
799 		printf("%s", name);
800 		return (0);
801 	}
802 
803 	if (eflag)
804 		sep = "=";
805 	else
806 		sep = ": ";
807 
808 	if (dflag) {	/* just print description */
809 		qoid[1] = 5;
810 		j = sizeof(buf);
811 		i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
812 		if (!nflag)
813 			printf("%s%s", name, sep);
814 		printf("%s", buf);
815 		return (0);
816 	}
817 	/* find an estimate of how much we need for this var */
818 	j = 0;
819 	i = sysctl(oid, nlen, 0, &j, 0, 0);
820 	j += j; /* we want to be sure :-) */
821 
822 	val = oval = malloc(j + 1);
823 	if (val == NULL) {
824 		warnx("malloc failed");
825 		return (1);
826 	}
827 	ctltype = (kind & CTLTYPE);
828 	len = j;
829 	i = sysctl(oid, nlen, val, &len, 0, 0);
830 	if (i != 0 || (len == 0 && ctltype != CTLTYPE_STRING)) {
831 		free(oval);
832 		return (1);
833 	}
834 
835 	if (bflag) {
836 		fwrite(val, 1, len, stdout);
837 		free(oval);
838 		return (0);
839 	}
840 	val[len] = '\0';
841 	p = val;
842 	sign = ctl_sign[ctltype];
843 	intlen = ctl_size[ctltype];
844 
845 	switch (ctltype) {
846 	case CTLTYPE_STRING:
847 		if (!nflag)
848 			printf("%s%s", name, sep);
849 		printf("%.*s", (int)len, p);
850 		free(oval);
851 		return (0);
852 
853 	case CTLTYPE_INT:
854 	case CTLTYPE_UINT:
855 	case CTLTYPE_LONG:
856 	case CTLTYPE_ULONG:
857 	case CTLTYPE_S64:
858 	case CTLTYPE_U64:
859 		if (!nflag)
860 			printf("%s%s", name, sep);
861 		hexlen = 2 + (intlen * CHAR_BIT + 3) / 4;
862 		sep1 = "";
863 		while (len >= intlen) {
864 			switch (kind & CTLTYPE) {
865 			case CTLTYPE_INT:
866 			case CTLTYPE_UINT:
867 				umv = *(u_int *)p;
868 				mv = *(int *)p;
869 				break;
870 			case CTLTYPE_LONG:
871 			case CTLTYPE_ULONG:
872 				umv = *(u_long *)p;
873 				mv = *(long *)p;
874 				break;
875 			case CTLTYPE_S64:
876 			case CTLTYPE_U64:
877 				umv = *(uint64_t *)p;
878 				mv = *(int64_t *)p;
879 				break;
880 			}
881 			fputs(sep1, stdout);
882 			if (xflag)
883 				printf("%#0*jx", hexlen, umv);
884 			else if (!sign)
885 				printf(hflag ? "%'ju" : "%ju", umv);
886 			else if (fmt[1] == 'K') {
887 				if (mv < 0)
888 					printf("%jd", mv);
889 				else
890 					printf("%.1fC", (mv - 2732.0) / 10);
891 			} else
892 				printf(hflag ? "%'jd" : "%jd", mv);
893 			sep1 = " ";
894 			len -= intlen;
895 			p += intlen;
896 		}
897 		free(oval);
898 		return (0);
899 
900 	case CTLTYPE_OPAQUE:
901 		i = 0;
902 		if (strcmp(fmt, "S,clockinfo") == 0)
903 			func = S_clockinfo;
904 		else if (strcmp(fmt, "S,timeval") == 0)
905 			func = S_timeval;
906 		else if (strcmp(fmt, "S,loadavg") == 0)
907 			func = S_loadavg;
908 		else if (strcmp(fmt, "S,vmtotal") == 0)
909 			func = S_vmtotal;
910 #ifdef __amd64__
911 		else if (strcmp(fmt, "S,efi_map_header") == 0)
912 			func = S_efi_map;
913 #endif
914 #if defined(__amd64__) || defined(__i386__)
915 		else if (strcmp(fmt, "S,bios_smap_xattr") == 0)
916 			func = S_bios_smap_xattr;
917 #endif
918 		else
919 			func = NULL;
920 		if (func) {
921 			if (!nflag)
922 				printf("%s%s", name, sep);
923 			i = (*func)(len, p);
924 			free(oval);
925 			return (i);
926 		}
927 		/* FALLTHROUGH */
928 	default:
929 		if (!oflag && !xflag) {
930 			free(oval);
931 			return (1);
932 		}
933 		if (!nflag)
934 			printf("%s%s", name, sep);
935 		printf("Format:%s Length:%zu Dump:0x", fmt, len);
936 		while (len-- && (xflag || p < val + 16))
937 			printf("%02x", *p++);
938 		if (!xflag && len > 16)
939 			printf("...");
940 		free(oval);
941 		return (0);
942 	}
943 	free(oval);
944 	return (1);
945 }
946 
947 static int
948 sysctl_all(int *oid, int len)
949 {
950 	int name1[22], name2[22];
951 	int i, j;
952 	size_t l1, l2;
953 
954 	name1[0] = 0;
955 	name1[1] = 2;
956 	l1 = 2;
957 	if (len) {
958 		memcpy(name1+2, oid, len * sizeof(int));
959 		l1 += len;
960 	} else {
961 		name1[2] = 1;
962 		l1++;
963 	}
964 	for (;;) {
965 		l2 = sizeof(name2);
966 		j = sysctl(name1, l1, name2, &l2, 0, 0);
967 		if (j < 0) {
968 			if (errno == ENOENT)
969 				return (0);
970 			else
971 				err(1, "sysctl(getnext) %d %zu", j, l2);
972 		}
973 
974 		l2 /= sizeof(int);
975 
976 		if (len < 0 || l2 < (unsigned int)len)
977 			return (0);
978 
979 		for (i = 0; i < len; i++)
980 			if (name2[i] != oid[i])
981 				return (0);
982 
983 		i = show_var(name2, l2);
984 		if (!i && !bflag)
985 			putchar('\n');
986 
987 		memcpy(name1+2, name2, l2 * sizeof(int));
988 		l1 = 2 + l2;
989 	}
990 }
991