xref: /netbsd-src/sbin/sysctl/sysctl.c (revision eb961d0e02b7a46a9acfa877b02df48df6637278)
1 /*	$NetBSD: sysctl.c,v 1.111 2006/02/08 18:13:56 christos Exp $ */
2 
3 /*-
4  * Copyright (c) 2003 The NetBSD Foundation, Inc.
5  *	All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andrew Brown.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of The NetBSD Foundation nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1993
37  *	The Regents of the University of California.  All rights reserved.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions
41  * are met:
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  * 3. Neither the name of the University nor the names of its contributors
48  *    may be used to endorse or promote products derived from this software
49  *    without specific prior written permission.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61  * SUCH DAMAGE.
62  */
63 
64 #include <sys/cdefs.h>
65 #ifndef lint
66 __COPYRIGHT(
67 "@(#) Copyright (c) 1993\n\
68 	The Regents of the University of California.  All rights reserved.\n");
69 #endif /* not lint */
70 
71 #ifndef lint
72 #if 0
73 static char sccsid[] = "@(#)sysctl.c	8.1 (Berkeley) 6/6/93";
74 #else
75 __RCSID("$NetBSD: sysctl.c,v 1.111 2006/02/08 18:13:56 christos Exp $");
76 #endif
77 #endif /* not lint */
78 
79 #include <sys/types.h>
80 #include <sys/param.h>
81 #include <sys/sysctl.h>
82 #include <sys/mount.h>
83 #include <sys/resource.h>
84 #include <sys/stat.h>
85 #include <sys/sched.h>
86 #include <sys/socket.h>
87 #include <netinet/in.h>
88 #include <netinet/ip_var.h>
89 #include <netinet/tcp.h>
90 #include <netinet/tcp_timer.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet/icmp6.h>
93 #include <nfs/rpcv2.h>
94 #include <nfs/nfsproto.h>
95 #include <nfs/nfs.h>
96 #include <machine/cpu.h>
97 #include <netkey/key_var.h>
98 
99 #include <assert.h>
100 #include <ctype.h>
101 #include <err.h>
102 #include <errno.h>
103 #include <inttypes.h>
104 #include <regex.h>
105 #include <stdarg.h>
106 #include <stdio.h>
107 #include <stdlib.h>
108 #include <string.h>
109 #include <time.h>
110 #include <unistd.h>
111 
112 /*
113  * this needs to be able to do the printing and the setting
114  */
115 #define HANDLER_PROTO const char *, const char *, char *, \
116 	int *, u_int, const struct sysctlnode *, \
117 	u_int, void *
118 #define HANDLER_ARGS const char *sname, const char *dname, char *value, \
119 	int *name, u_int namelen, const struct sysctlnode *pnode, \
120 	u_int type, void *v
121 #define DISPLAY_VALUE	0
122 #define DISPLAY_OLD	1
123 #define DISPLAY_NEW	2
124 
125 /*
126  * generic routines
127  */
128 static const struct handlespec *findhandler(const char *, int);
129 static void canonicalize(const char *, char *);
130 static void purge_tree(struct sysctlnode *);
131 static void print_tree(int *, u_int, struct sysctlnode *, u_int, int);
132 static void write_number(int *, u_int, struct sysctlnode *, char *);
133 static void write_string(int *, u_int, struct sysctlnode *, char *);
134 static void display_number(const struct sysctlnode *, const char *,
135 			   const void *, size_t, int);
136 static void display_string(const struct sysctlnode *, const char *,
137 			   const void *, size_t, int);
138 static void display_struct(const struct sysctlnode *, const char *,
139 			   const void *, size_t, int);
140 static void hex_dump(const unsigned char *, size_t);
141 static void usage(void);
142 static void parse(char *);
143 static void parse_create(char *);
144 static void parse_destroy(char *);
145 static void parse_describe(char *);
146 static void getdesc1(int *, u_int, struct sysctlnode *);
147 static void getdesc(int *, u_int, struct sysctlnode *);
148 static void trim_whitespace(char *, int);
149 static void sysctlerror(int);
150 static void sysctlparseerror(u_int, const char *);
151 static void sysctlperror(const char *, ...);
152 #define EXIT(n) do { \
153 	if (fn == NULL) exit(n); else return; } while (/*CONSTCOND*/0)
154 
155 /*
156  * "borrowed" from libc:sysctlgetmibinfo.c
157  */
158 int __learn_tree(int *, u_int, struct sysctlnode *);
159 
160 /*
161  * "handlers"
162  */
163 static void printother(HANDLER_PROTO);
164 static void kern_clockrate(HANDLER_PROTO);
165 static void kern_boottime(HANDLER_PROTO);
166 static void kern_consdev(HANDLER_PROTO);
167 static void kern_cp_time(HANDLER_PROTO);
168 static void kern_cp_id(HANDLER_PROTO);
169 static void vm_loadavg(HANDLER_PROTO);
170 static void proc_limit(HANDLER_PROTO);
171 #ifdef CPU_DISKINFO
172 static void machdep_diskinfo(HANDLER_PROTO);
173 #endif /* CPU_DISKINFO */
174 static void mode_bits(HANDLER_PROTO);
175 
176 static const struct handlespec {
177 	const char *ps_re;
178 	void (*ps_p)(HANDLER_PROTO);
179 	void (*ps_w)(HANDLER_PROTO);
180 	const void *ps_d;
181 } handlers[] = {
182 	{ "/kern/clockrate",			kern_clockrate },
183 	{ "/kern/vnode",			printother, NULL, "pstat" },
184 	{ "/kern/proc(2|_args)?",		printother, NULL, "ps" },
185 	{ "/kern/file2?",			printother, NULL, "pstat" },
186 	{ "/kern/ntptime",			printother, NULL,
187 						"ntpdc -c kerninfo" },
188 	{ "/kern/msgbuf",			printother, NULL, "dmesg" },
189 	{ "/kern/boottime",			kern_boottime },
190 	{ "/kern/consdev",			kern_consdev },
191 	{ "/kern/cp_time(/[0-9]+)?",		kern_cp_time },
192 	{ "/kern/sysvipc_info",			printother, NULL, "ipcs" },
193 	{ "/kern/cp_id(/[0-9]+)?",		kern_cp_id },
194 
195 	{ "/vm/vmmeter",			printother, NULL,
196 						"vmstat' or 'systat" },
197 	{ "/vm/loadavg",			vm_loadavg },
198 	{ "/vm/uvmexp2?",			printother, NULL,
199 						"vmstat' or 'systat" },
200 
201 	{ "/vfs/nfs/nfsstats",			printother, NULL, "nfsstat" },
202 
203 	{ "/net/inet6?/tcp6?/ident",		printother, NULL, "identd" },
204 	{ "/net/inet6/icmp6/nd6_[dp]rlist",	printother, NULL, "ndp" },
205 	{ "/net/key/dumps[ap]",			printother, NULL, "setkey" },
206 	{ "/net/[^/]+/[^/]+/pcblist",		printother, NULL,
207 						"netstat' or 'sockstat" },
208 	{ "/net/(inet|inet6)/[^/]+/stats",	printother, NULL, "netstat"},
209 	{ "/net/bpf/(stats|peers)",		printother, NULL, "netstat"},
210 
211 	{ "/net/inet.*/tcp.*/deb.*",		printother, NULL, "trpt" },
212 
213 	{ "/net/ns/spp/deb.*",			printother, NULL, "trsp" },
214 
215 	{ "/hw/diskstats",			printother, NULL, "iostat" },
216 
217 #ifdef CPU_CONSDEV
218 	{ "/machdep/consdev",			kern_consdev },
219 #endif /* CPU_CONSDEV */
220 #ifdef CPU_DISKINFO
221 	{ "/machdep/diskinfo",			machdep_diskinfo },
222 #endif /* CPU_CONSDEV */
223 
224 	{ "/proc/[^/]+/rlimit/[^/]+/[^/]+",	proc_limit, proc_limit },
225 
226 	{ "/security/setid_core/mode",		mode_bits, mode_bits },
227 
228 	/*
229 	 * these will only be called when the given node has no children
230 	 */
231 	{ "/net/[^/]+",				printother, NULL, NULL },
232 	{ "/debug",				printother, NULL, NULL },
233 	{ "/ddb",				printother, NULL, NULL },
234 	{ "/vendor",				printother, NULL, NULL },
235 
236 	{ NULL },
237 };
238 
239 struct sysctlnode my_root = {
240 #if defined(lint)
241 	0
242 #else /* defined(lint) */
243 	.sysctl_flags = SYSCTL_VERSION|CTLFLAG_ROOT|CTLTYPE_NODE,
244 	sysc_init_field(_sysctl_size, sizeof(struct sysctlnode)),
245 	.sysctl_num = 0,
246 	.sysctl_name = "(prog_root)",
247 #endif /* defined(lint) */
248 };
249 
250 int	Aflag, aflag, dflag, Mflag, nflag, qflag, rflag, wflag, xflag;
251 size_t	nr;
252 char	*fn;
253 int	req, stale;
254 FILE	*warnfp = stderr;
255 
256 /*
257  * vah-riables n stuff
258  */
259 char gsname[SYSCTL_NAMELEN * CTL_MAXNAME + CTL_MAXNAME],
260 	canonname[SYSCTL_NAMELEN * CTL_MAXNAME + CTL_MAXNAME],
261 	gdname[10 * CTL_MAXNAME + CTL_MAXNAME];
262 char sep[] = ".";
263 const char *eq = " = ";
264 const char *lname[] = {
265 	"top", "second", "third", "fourth", "fifth", "sixth",
266 	"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"
267 };
268 
269 /*
270  * you've heard of main, haven't you?
271  */
272 int
273 main(int argc, char *argv[])
274 {
275 	int name[CTL_MAXNAME];
276 	int ch;
277 
278 	while ((ch = getopt(argc, argv, "Aabdef:Mnqrwx")) != -1) {
279 		switch (ch) {
280 		case 'A':
281 			Aflag++;
282 			break;
283 		case 'a':
284 			aflag++;
285 			break;
286 		case 'd':
287 			dflag++;
288 			break;
289 		case 'e':
290 			eq = "=";
291 			break;
292 		case 'f':
293 			fn = optarg;
294 			wflag++;
295 			break;
296 		case 'M':
297 			Mflag++;
298 			break;
299 		case 'n':
300 			nflag++;
301 			break;
302 		case 'q':
303 			qflag++;
304 			break;
305 		case 'b':	/* FreeBSD compat */
306 		case 'r':
307 			rflag++;
308 			break;
309 		case 'w':
310 			wflag++;
311 			break;
312 		case 'x':
313 			xflag++;
314 			break;
315 		default:
316 			usage();
317 		}
318 	}
319 
320 	argc -= optind;
321 	argv += optind;
322 
323 	if (qflag && !wflag)
324 		usage();
325 	if (xflag && rflag)
326 		usage();
327 	/* if ((xflag || rflag) && wflag)
328 		usage(); */
329 	/* if (aflag && Mflag)
330 		usage(); */
331 	if ((Aflag || Mflag || dflag) && argc == 0 && fn == NULL)
332 		aflag = 1;
333 
334 	if (Aflag)
335 		warnfp = stdout;
336 	stale = req = 0;
337 
338 	if (aflag) {
339 		print_tree(&name[0], 0, NULL, CTLTYPE_NODE, 1);
340 		/* if (argc == 0) */
341 		return (0);
342 	}
343 
344 	if (fn) {
345 		FILE *fp;
346 		char *l;
347 
348 		fp = fopen(fn, "r");
349 		if (fp == NULL) {
350 			err(1, "%s", fn);
351 		} else {
352 			nr = 0;
353 			while ((l = fparseln(fp, NULL, &nr, NULL, 0)) != NULL)
354 			{
355 				if (*l) {
356 					parse(l);
357 					free(l);
358 				}
359 			}
360 			fclose(fp);
361 		}
362 		return (0);
363 	}
364 
365 	if (argc == 0)
366 		usage();
367 
368 	while (argc-- > 0)
369 		parse(*argv++);
370 
371 	return (0);
372 }
373 
374 /*
375  * ********************************************************************
376  * how to find someone special to handle the reading (or maybe even
377  * writing) of a particular node
378  * ********************************************************************
379  */
380 static const struct handlespec *
381 findhandler(const char *s, int w)
382 {
383 	const struct handlespec *p;
384 	regex_t re;
385 	int i, j, l;
386 	char eb[64];
387 	regmatch_t match[1];
388 
389 	p = &handlers[0];
390 	l = strlen(s);
391 	for (i = 0; p[i].ps_re != NULL; i++) {
392 		j = regcomp(&re, p[i].ps_re, REG_EXTENDED);
393 		if (j != 0) {
394 			regerror(j, &re, eb, sizeof(eb));
395 			errx(1, "regcomp: %s: %s", p[i].ps_re, eb);
396 		}
397 		j = regexec(&re, s, 1, match, 0);
398 		if (j == 0) {
399 			if (match[0].rm_so == 0 && match[0].rm_eo == l &&
400 			    (w ? p[i].ps_w : p[i].ps_p) != NULL)
401 				return (&p[i]);
402 		}
403 		else if (j != REG_NOMATCH) {
404 			regerror(j, &re, eb, sizeof(eb));
405 			errx(1, "regexec: %s: %s", p[i].ps_re, eb);
406 		}
407 	}
408 
409 	return (NULL);
410 }
411 
412 /*
413  * after sysctlgetmibinfo is done with the name, we convert all
414  * separators to / and stuff one at the front if it was missing
415  */
416 static void
417 canonicalize(const char *i, char *o)
418 {
419 	const char *t;
420 	char p[SYSCTL_NAMELEN + 1];
421 	int l;
422 
423 	if (i[0] != *sep) {
424 		o[0] = '/';
425 		o[1] = '\0';
426 	}
427 	else
428 		o[0] = '\0';
429 
430 	t = i;
431 	do {
432 		i = t;
433 		t = strchr(i, sep[0]);
434 		if (t == NULL)
435 			strcat(o, i);
436 		else {
437 			l = t - i;
438 			t++;
439 			memcpy(p, i, l);
440 			p[l] = '\0';
441 			strcat(o, p);
442 			strcat(o, "/");
443 		}
444 	} while (t != NULL);
445 }
446 
447 /*
448  * ********************************************************************
449  * convert this special number to a special string so we can print the
450  * mib
451  * ********************************************************************
452  */
453 static const char *
454 sf(u_int f)
455 {
456 	static char s[256];
457 	const char *c;
458 
459 	s[0] = '\0';
460 	c = "";
461 
462 #define print_flag(_f, _s, _c, _q, _x) \
463 	if (((_f) & (__CONCAT(CTLFLAG_,_x))) == (__CONCAT(CTLFLAG_,_q))) { \
464 		strlcat((_s), (_c), sizeof(_s)); \
465 		strlcat((_s), __STRING(_q), sizeof(_s)); \
466 		(_c) = ","; \
467 		(_f) &= ~(__CONCAT(CTLFLAG_,_x)); \
468 	}
469 	print_flag(f, s, c, READONLY,  READWRITE);
470 	print_flag(f, s, c, READONLY1, READWRITE);
471 	print_flag(f, s, c, READONLY2, READWRITE);
472 	print_flag(f, s, c, READWRITE, READWRITE);
473 	print_flag(f, s, c, ANYWRITE,  ANYWRITE);
474 	print_flag(f, s, c, PRIVATE,   PRIVATE);
475 	print_flag(f, s, c, PERMANENT, PERMANENT);
476 	print_flag(f, s, c, OWNDATA,   OWNDATA);
477 	print_flag(f, s, c, IMMEDIATE, IMMEDIATE);
478 	print_flag(f, s, c, HEX,       HEX);
479 	print_flag(f, s, c, ROOT,      ROOT);
480 	print_flag(f, s, c, ANYNUMBER, ANYNUMBER);
481 	print_flag(f, s, c, HIDDEN,    HIDDEN);
482 	print_flag(f, s, c, ALIAS,     ALIAS);
483 #undef print_flag
484 
485 	if (f) {
486 		char foo[9];
487 		snprintf(foo, sizeof(foo), "%x", f);
488 		strlcat(s, c, sizeof(s));
489 		strlcat(s, foo, sizeof(s));
490 	}
491 
492 	return (s);
493 }
494 
495 static const char *
496 st(u_int t)
497 {
498 
499 	switch (t) {
500 	case CTLTYPE_NODE:
501 		return "NODE";
502 	case CTLTYPE_INT:
503 		return "INT";
504 	case CTLTYPE_STRING:
505 		return "STRING";
506 	case CTLTYPE_QUAD:
507                 return "QUAD";
508 	case CTLTYPE_STRUCT:
509 		return "STRUCT";
510 	}
511 
512 	return "???";
513 }
514 
515 /*
516  * ********************************************************************
517  * recursively eliminate all data belonging to the given node
518  * ********************************************************************
519  */
520 static void
521 purge_tree(struct sysctlnode *rnode)
522 {
523 	struct sysctlnode *node;
524 
525 	if (rnode == NULL ||
526 	    SYSCTL_TYPE(rnode->sysctl_flags) != CTLTYPE_NODE ||
527 	    rnode->sysctl_child == NULL)
528 		return;
529 
530 	for (node = rnode->sysctl_child;
531 	     node < &rnode->sysctl_child[rnode->sysctl_clen];
532 	     node++)
533 		purge_tree(node);
534 	free(rnode->sysctl_child);
535 	rnode->sysctl_csize = 0;
536 	rnode->sysctl_clen = 0;
537 	rnode->sysctl_child = NULL;
538 
539 	if (rnode->sysctl_desc == (const char*)-1)
540 		rnode->sysctl_desc = NULL;
541 	if (rnode->sysctl_desc != NULL)
542 		free(__UNCONST(rnode->sysctl_desc));
543 	rnode->sysctl_desc = NULL;
544 }
545 
546 /*
547  * ********************************************************************
548  * print this node and any others underneath it
549  * ********************************************************************
550  */
551 static void
552 print_tree(int *name, u_int namelen, struct sysctlnode *pnode, u_int type,
553 	   int add)
554 {
555 	struct sysctlnode *node;
556 	int rc, ni;
557 	size_t sz;
558 	char *sp, *dp, n[20];
559 	const struct handlespec *p;
560 
561 	sp = &gsname[strlen(gsname)];
562 	dp = &gdname[strlen(gdname)];
563 
564 	if (sp != &gsname[0] && dp == &gdname[0]) {
565 		/*
566 		 * aw...shucks.  now we must play catch up
567 		 */
568 		for (ni = 0; ni < namelen; ni++) {
569 			(void)snprintf(n, sizeof(n), "%d", name[ni]);
570 			if (ni > 0)
571 				strncat(gdname, ".", sizeof(gdname));
572 			strncat(gdname, n, sizeof(gdname));
573 		}
574 	}
575 
576 	if (pnode == NULL)
577 		pnode = &my_root;
578 	else if (add) {
579 		snprintf(n, sizeof(n), "%d", pnode->sysctl_num);
580 		if (namelen > 1) {
581 			strncat(gsname, sep, sizeof(gsname));
582 			strncat(gdname, ".", sizeof(gdname));
583 		}
584 		strncat(gsname, pnode->sysctl_name, sizeof(gsname));
585 		strncat(gdname, n, sizeof(gdname));
586 	}
587 
588 	if (Mflag && pnode != &my_root) {
589 		if (nflag)
590 			printf("%s: ", gdname);
591 		else
592 			printf("%s (%s): ", gsname, gdname);
593 		printf("CTLTYPE_%s", st(type));
594 		if (type == CTLTYPE_NODE) {
595 			if (SYSCTL_FLAGS(pnode->sysctl_flags) & CTLFLAG_ALIAS)
596 				printf(", alias %d",
597 				       pnode->sysctl_alias);
598 			else
599 				printf(", children %d/%d",
600 				       pnode->sysctl_clen,
601 				       pnode->sysctl_csize);
602 		}
603 		printf(", size %zu", pnode->sysctl_size);
604 		printf(", flags 0x%x<%s>",
605 		       SYSCTL_FLAGS(pnode->sysctl_flags),
606 		       sf(SYSCTL_FLAGS(pnode->sysctl_flags)));
607 		if (pnode->sysctl_func)
608 			printf(", func=%p", pnode->sysctl_func);
609 		printf(", ver=%d", pnode->sysctl_ver);
610 		printf("\n");
611 		if (type != CTLTYPE_NODE) {
612 			*sp = *dp = '\0';
613 			return;
614 		}
615 	}
616 
617 	if (dflag && pnode != &my_root) {
618 		if (Aflag || type != CTLTYPE_NODE) {
619 			if (pnode->sysctl_desc == NULL)
620 				getdesc1(name, namelen, pnode);
621 			if (Aflag || !add ||
622 			    (pnode->sysctl_desc != NULL &&
623 			     pnode->sysctl_desc != (const char*)-1)) {
624 				if (!nflag)
625 					printf("%s: ", gsname);
626 				if (pnode->sysctl_desc == NULL ||
627 				    pnode->sysctl_desc == (const char*)-1)
628 					printf("(no description)\n");
629 				else
630 					printf("%s\n", pnode->sysctl_desc);
631 			}
632 		}
633 
634 		if (type != CTLTYPE_NODE) {
635 			*sp = *dp = '\0';
636 			return;
637 		}
638 	}
639 
640 	/*
641 	 * if this is an alias and we added our name, that means we
642 	 * got here by recursing down into the tree, so skip it.  The
643 	 * only way to print an aliased node is with either -M or by
644 	 * name specifically.
645 	 */
646 	if (SYSCTL_FLAGS(pnode->sysctl_flags) & CTLFLAG_ALIAS && add) {
647 		*sp = *dp = '\0';
648 		return;
649 	}
650 
651 	canonicalize(gsname, canonname);
652 	p = findhandler(canonname, 0);
653 	if (type != CTLTYPE_NODE && p != NULL) {
654 		(*p->ps_p)(gsname, gdname, NULL, name, namelen, pnode, type,
655 			   __UNCONST(p->ps_d));
656 		*sp = *dp = '\0';
657 		return;
658 	}
659 
660 	if (type != CTLTYPE_NODE && pnode->sysctl_size == 0) {
661 		rc = sysctl(&name[0], namelen, NULL, &sz, NULL, 0);
662 		if (rc == -1) {
663 			sysctlerror(1);
664 			*sp = *dp = '\0';
665 			return;
666 		}
667 		if (sz == 0) {
668 			if ((Aflag || req) && !Mflag)
669 				printf("%s: node contains no data\n", gsname);
670 			*sp = *dp = '\0';
671 			return;
672 		}
673 	}
674 	else
675 		sz = pnode->sysctl_size;
676 
677 	switch (type) {
678 	case CTLTYPE_NODE: {
679 		__learn_tree(name, namelen, pnode);
680 		node = pnode->sysctl_child;
681 		if (node == NULL) {
682 			if (dflag)
683 				/* do nothing */;
684 			else if (p != NULL)
685 				(*p->ps_p)(gsname, gdname, NULL, name, namelen,
686 					   pnode, type, __UNCONST(p->ps_d));
687 			else if ((Aflag || req) && !Mflag)
688 				printf("%s: no children\n", gsname);
689 		}
690 		else {
691 			if (dflag)
692 				/*
693 				 * get all descriptions for next level
694 				 * in one chunk
695 				 */
696 				getdesc(name, namelen, pnode);
697 			req = 0;
698 			for (ni = 0; ni < pnode->sysctl_clen; ni++) {
699 				name[namelen] = node[ni].sysctl_num;
700 				if ((node[ni].sysctl_flags & CTLFLAG_HIDDEN) &&
701 				    !(Aflag || req))
702 					continue;
703 				print_tree(name, namelen + 1, &node[ni],
704 					   SYSCTL_TYPE(node[ni].sysctl_flags),
705 					   1);
706 			}
707 		}
708 		break;
709 	}
710 	case CTLTYPE_INT: {
711 		int i;
712 		rc = sysctl(name, namelen, &i, &sz, NULL, 0);
713 		if (rc == -1) {
714 			sysctlerror(1);
715 			break;
716 		}
717 		display_number(pnode, gsname, &i, sizeof(i), DISPLAY_VALUE);
718 		break;
719 	}
720 	case CTLTYPE_STRING: {
721 		unsigned char buf[1024], *tbuf;
722 		tbuf = buf;
723 		sz = sizeof(buf);
724 		rc = sysctl(&name[0], namelen, tbuf, &sz, NULL, 0);
725 		if (rc == -1 && errno == ENOMEM) {
726 			tbuf = malloc(sz);
727 			if (tbuf == NULL) {
728 				sysctlerror(1);
729 				break;
730 			}
731 			rc = sysctl(&name[0], namelen, tbuf, &sz, NULL, 0);
732 		}
733 		if (rc == -1)
734 			sysctlerror(1);
735 		else
736 			display_string(pnode, gsname, tbuf, sz, DISPLAY_VALUE);
737 		if (tbuf != buf)
738 			free(tbuf);
739 		break;
740 	}
741 	case CTLTYPE_QUAD: {
742 		u_quad_t q;
743 		sz = sizeof(q);
744 		rc = sysctl(&name[0], namelen, &q, &sz, NULL, 0);
745 		if (rc == -1) {
746 			sysctlerror(1);
747 			break;
748 		}
749 		display_number(pnode, gsname, &q, sizeof(q), DISPLAY_VALUE);
750 		break;
751 	}
752 	case CTLTYPE_STRUCT: {
753 		/*
754 		 * we shouldn't actually get here, but if we
755 		 * do, would it be nice to have *something* to
756 		 * do other than completely ignore the
757 		 * request.
758 		 */
759 		unsigned char *d;
760 		if ((d = malloc(sz)) == NULL) {
761 			fprintf(warnfp, "%s: !malloc failed!\n", gsname);
762 			break;
763 		}
764 		rc = sysctl(&name[0], namelen, d, &sz, NULL, 0);
765 		if (rc == -1) {
766 			sysctlerror(1);
767 			break;
768 		}
769 		display_struct(pnode, gsname, d, sz, DISPLAY_VALUE);
770 		free(d);
771 		break;
772 	}
773 	default:
774 		/* should i print an error here? */
775 		break;
776 	}
777 
778 	*sp = *dp = '\0';
779 }
780 
781 /*
782  * ********************************************************************
783  * parse a request, possibly determining that it's a create or destroy
784  * request
785  * ********************************************************************
786  */
787 static void
788 parse(char *l)
789 {
790 	struct sysctlnode *node;
791 	const struct handlespec *w;
792 	int name[CTL_MAXNAME], dodesc = 0;
793 	u_int namelen, type;
794 	char *key, *value, *dot;
795 	size_t sz;
796 
797 	req = 1;
798 	key = l;
799 	value = strchr(l, '=');
800 	if (value != NULL)
801 		*value++ = '\0';
802 
803 	if ((dot = strpbrk(key, "./")) == NULL)
804 		sep[0] = '.';
805 	else
806 		sep[0] = dot[0];
807 	sep[1] = '\0';
808 
809 	while (key[0] == sep[0] && key[1] == sep[0]) {
810 		if (value != NULL)
811 			value[-1] = '=';
812 		if (strncmp(key + 2, "create", 6) == 0 &&
813 		    (key[8] == '=' || key[8] == sep[0]))
814 			parse_create(key + 8 + (key[8] == '=' ? 1 : 0));
815 		else if (strncmp(key + 2, "destroy", 7) == 0 &&
816 			 (key[9] == '=' || key[9] == sep[0]))
817 			parse_destroy(key + 9 + (key[9] == '=' ? 1 : 0));
818 		else if (strncmp(key + 2, "describe", 8) == 0 &&
819 			 (key[10] == '=' || key[10] == sep[0])) {
820 			key += 10 + (key[10] == '=');
821 			if ((value = strchr(key, '=')) != NULL)
822 				parse_describe(key);
823 			else {
824 				if (!dflag)
825 					dodesc = 1;
826 				break;
827 			}
828 		}
829 		else
830 			sysctlperror("unable to parse '%s'\n", key);
831 		return;
832 	}
833 
834 	if (stale) {
835 		purge_tree(&my_root);
836 		stale = 0;
837 	}
838 	node = &my_root;
839 	namelen = CTL_MAXNAME;
840 	sz = sizeof(gsname);
841 
842 	if (sysctlgetmibinfo(key, &name[0], &namelen, gsname, &sz, &node,
843 			     SYSCTL_VERSION) == -1) {
844 		sysctlparseerror(namelen, l);
845 		EXIT(1);
846 	}
847 
848 	type = SYSCTL_TYPE(node->sysctl_flags);
849 
850 	if (value == NULL) {
851 		if (dodesc)
852 			dflag = 1;
853 		print_tree(&name[0], namelen, node, type, 0);
854 		if (dodesc)
855 			dflag = 0;
856 		gsname[0] = '\0';
857 		return;
858 	}
859 
860 	if (fn)
861 		trim_whitespace(value, 1);
862 
863 	if (!wflag) {
864 		sysctlperror("Must specify -w to set variables\n");
865 		exit(1);
866 	}
867 
868 	canonicalize(gsname, canonname);
869 	if (type != CTLTYPE_NODE && (w = findhandler(canonname, 1)) != NULL) {
870 		(*w->ps_w)(gsname, gdname, value, name, namelen, node, type,
871 			   __UNCONST(w->ps_d));
872 		gsname[0] = '\0';
873 		return;
874 	}
875 
876 	switch (type) {
877 	case CTLTYPE_NODE:
878 		/*
879 		 * XXX old behavior is to print.  should we error instead?
880 		 */
881 		print_tree(&name[0], namelen, node, CTLTYPE_NODE, 1);
882 		break;
883 	case CTLTYPE_INT:
884 		write_number(&name[0], namelen, node, value);
885 		break;
886 	case CTLTYPE_STRING:
887 		write_string(&name[0], namelen, node, value);
888 		break;
889 	case CTLTYPE_QUAD:
890 		write_number(&name[0], namelen, node, value);
891 		break;
892 	case CTLTYPE_STRUCT:
893 		/*
894 		 * XXX old behavior is to print.  should we error instead?
895 		 */
896 		/* fprintf(warnfp, "you can't write to %s\n", gsname); */
897 		print_tree(&name[0], namelen, node, type, 0);
898 		break;
899 	}
900 }
901 
902 /*
903 
904   //create=foo.bar.whatever...,
905   [type=(int|quad|string|struct|node),]
906   [size=###,]
907   [n=###,]
908   [flags=(iohxparw12),]
909   [addr=0x####,|symbol=...|value=...]
910 
911   size is optional for some types.  type must be set before anything
912   else.  nodes can have [r12whp], but nothing else applies.  if no
913   size or type is given, node is asserted.  writeable is the default,
914   with [r12w] being read-only, writeable below securelevel 1,
915   writeable below securelevel 2, and unconditionally writeable
916   respectively.  if you specify addr, it is assumed to be the name of
917   a kernel symbol, if value, CTLFLAG_OWNDATA will be asserted for
918   strings, CTLFLAG_IMMEDIATE for ints and u_quad_ts.  you cannot
919   specify both value and addr.
920 
921 */
922 
923 static void
924 parse_create(char *l)
925 {
926 	struct sysctlnode node;
927 	size_t sz;
928 	char *nname, *key, *value, *data, *addr, *c, *t;
929 	int name[CTL_MAXNAME], i, rc, method, flags, rw;
930 	u_int namelen, type;
931 	u_quad_t uq;
932 	quad_t q;
933 
934 	if (!wflag) {
935 		sysctlperror("Must specify -w to create nodes\n");
936 		exit(1);
937 	}
938 
939 	/*
940 	 * these are the pieces that make up the description of a new
941 	 * node
942 	 */
943 	memset(&node, 0, sizeof(node));
944 	node.sysctl_num = CTL_CREATE;  /* any number is fine */
945 	flags = 0;
946 	rw = -1;
947 	type = 0;
948 	sz = 0;
949 	data = addr = NULL;
950 	memset(name, 0, sizeof(name));
951 	namelen = 0;
952 	method = 0;
953 
954 	/*
955 	 * misc stuff used when constructing
956 	 */
957 	i = 0;
958 	uq = 0;
959 	key = NULL;
960 	value = NULL;
961 
962 	/*
963 	 * the name of the thing we're trying to create is first, so
964 	 * pick it off.
965 	 */
966 	nname = l;
967 	if ((c = strchr(nname, ',')) != NULL)
968 		*c++ = '\0';
969 
970 	while (c != NULL) {
971 
972 		/*
973 		 * pull off the next "key=value" pair
974 		 */
975 		key = c;
976 		if ((t = strchr(key, '=')) != NULL) {
977 			*t++ = '\0';
978 			value = t;
979 		}
980 		else
981 			value = NULL;
982 
983 		/*
984 		 * if the "key" is "value", then that eats the rest of
985 		 * the string, so we're done, otherwise bite it off at
986 		 * the next comma.
987 		 */
988 		if (strcmp(key, "value") == 0) {
989 			c = NULL;
990 			data = value;
991 			break;
992 		}
993 		else {
994 			if ((c = strchr(value, ',')) != NULL)
995 				*c++ = '\0';
996 		}
997 
998 		/*
999 		 * note that we (mostly) let the invoker of sysctl(8)
1000 		 * play rampant here and depend on the kernel to tell
1001 		 * them that they were wrong.  well...within reason.
1002 		 * we later check the various parameters against each
1003 		 * other to make sure it makes some sort of sense.
1004 		 */
1005 		if (strcmp(key, "addr") == 0) {
1006 			/*
1007 			 * we can't check these two.  only the kernel
1008 			 * can tell us when it fails to find the name
1009 			 * (or if the address is invalid).
1010 			 */
1011 			if (method != 0) {
1012 				sysctlperror(
1013 				    "%s: already have %s for new node\n",
1014 				    nname,
1015 				    method == CTL_CREATE ? "addr" : "symbol");
1016 				EXIT(1);
1017 			}
1018 			errno = 0;
1019 			addr = (void*)strtoul(value, &t, 0);
1020 			if (t == value || *t != '\0' || errno != 0) {
1021 				sysctlperror(
1022 				    "%s: '%s' is not a valid address\n",
1023 				    nname, value);
1024 				EXIT(1);
1025 			}
1026 			method = CTL_CREATE;
1027 		}
1028 		else if (strcmp(key, "symbol") == 0) {
1029 			if (method != 0) {
1030 				sysctlperror(
1031 				    "%s: already have %s for new node\n",
1032 				    nname,
1033 				    method == CTL_CREATE ? "addr" : "symbol");
1034 				EXIT(1);
1035 			}
1036 			addr = value;
1037 			method = CTL_CREATESYM;
1038 		}
1039 		else if (strcmp(key, "type") == 0) {
1040 			if (strcmp(value, "node") == 0)
1041 				type = CTLTYPE_NODE;
1042 			else if (strcmp(value, "int") == 0) {
1043 				sz = sizeof(int);
1044 				type = CTLTYPE_INT;
1045 			}
1046 			else if (strcmp(value, "string") == 0)
1047 				type = CTLTYPE_STRING;
1048 			else if (strcmp(value, "quad") == 0) {
1049 				sz = sizeof(u_quad_t);
1050 				type = CTLTYPE_QUAD;
1051 			}
1052 			else if (strcmp(value, "struct") == 0)
1053 				type = CTLTYPE_STRUCT;
1054 			else {
1055 				sysctlperror(
1056 					"%s: '%s' is not a valid type\n",
1057 					nname, value);
1058 				EXIT(1);
1059 			}
1060 		}
1061 		else if (strcmp(key, "size") == 0) {
1062 			errno = 0;
1063 			/*
1064 			 * yes, i know size_t is not an unsigned long,
1065 			 * but we can all agree that it ought to be,
1066 			 * right?
1067 			 */
1068 			sz = strtoul(value, &t, 0);
1069 			if (t == value || *t != '\0' || errno != 0) {
1070 				sysctlperror(
1071 					"%s: '%s' is not a valid size\n",
1072 					nname, value);
1073 				EXIT(1);
1074 			}
1075 		}
1076 		else if (strcmp(key, "n") == 0) {
1077 			errno = 0;
1078 			q = strtoll(value, &t, 0);
1079 			if (t == value || *t != '\0' || errno != 0 ||
1080 			    q < INT_MIN || q > UINT_MAX) {
1081 				sysctlperror(
1082 				    "%s: '%s' is not a valid mib number\n",
1083 				    nname, value);
1084 				EXIT(1);
1085 			}
1086 			node.sysctl_num = (int)q;
1087 		}
1088 		else if (strcmp(key, "flags") == 0) {
1089 			t = value;
1090 			while (*t != '\0') {
1091 				switch (*t) {
1092 				case 'a':
1093 					flags |= CTLFLAG_ANYWRITE;
1094 					break;
1095 				case 'h':
1096 					flags |= CTLFLAG_HIDDEN;
1097 					break;
1098 				case 'i':
1099 					flags |= CTLFLAG_IMMEDIATE;
1100 					break;
1101 				case 'o':
1102 					flags |= CTLFLAG_OWNDATA;
1103 					break;
1104 				case 'p':
1105 					flags |= CTLFLAG_PRIVATE;
1106 					break;
1107 				case 'x':
1108 					flags |= CTLFLAG_HEX;
1109 					break;
1110 
1111 				case 'r':
1112 					rw = CTLFLAG_READONLY;
1113 					break;
1114 				case '1':
1115 					rw = CTLFLAG_READONLY1;
1116 					break;
1117 				case '2':
1118 					rw = CTLFLAG_READONLY2;
1119 					break;
1120 				case 'w':
1121 					rw = CTLFLAG_READWRITE;
1122 					break;
1123 				default:
1124 					sysctlperror(
1125 					   "%s: '%c' is not a valid flag\n",
1126 					    nname, *t);
1127 					EXIT(1);
1128 				}
1129 				t++;
1130 			}
1131 		}
1132 		else {
1133 			sysctlperror("%s: unrecognized keyword '%s'\n",
1134 				     nname, key);
1135 			EXIT(1);
1136 		}
1137 	}
1138 
1139 	/*
1140 	 * now that we've finished parsing the given string, fill in
1141 	 * anything they didn't specify
1142 	 */
1143 	if (type == 0)
1144 		type = CTLTYPE_NODE;
1145 
1146 	/*
1147 	 * the "data" can be interpreted various ways depending on the
1148 	 * type of node we're creating, as can the size
1149 	 */
1150 	if (data != NULL) {
1151 		if (addr != NULL) {
1152 			sysctlperror(
1153 				"%s: cannot specify both value and "
1154 				"address\n", nname);
1155 			EXIT(1);
1156 		}
1157 
1158 		switch (type) {
1159 		case CTLTYPE_INT:
1160 			errno = 0;
1161 			q = strtoll(data, &t, 0);
1162 			if (t == data || *t != '\0' || errno != 0 ||
1163 				q < INT_MIN || q > UINT_MAX) {
1164 				sysctlperror(
1165 				    "%s: '%s' is not a valid integer\n",
1166 				    nname, value);
1167 				EXIT(1);
1168 			}
1169 			i = (int)q;
1170 			if (!(flags & CTLFLAG_OWNDATA)) {
1171 				flags |= CTLFLAG_IMMEDIATE;
1172 				node.sysctl_idata = i;
1173 			}
1174 			else
1175 				node.sysctl_data = &i;
1176 			if (sz == 0)
1177 				sz = sizeof(int);
1178 			break;
1179 		case CTLTYPE_STRING:
1180 			flags |= CTLFLAG_OWNDATA;
1181 			node.sysctl_data = data;
1182 			if (sz == 0)
1183 				sz = strlen(data) + 1;
1184 			else if (sz < strlen(data) + 1) {
1185 				sysctlperror("%s: ignoring size=%zu for "
1186 					"string node, too small for given "
1187 					"value\n", nname, sz);
1188 				sz = strlen(data) + 1;
1189 			}
1190 			break;
1191 		case CTLTYPE_QUAD:
1192 			errno = 0;
1193 			uq = strtouq(data, &t, 0);
1194 			if (t == data || *t != '\0' || errno != 0) {
1195 				sysctlperror(
1196 					"%s: '%s' is not a valid quad\n",
1197 					nname, value);
1198 				EXIT(1);
1199 			}
1200 			if (!(flags & CTLFLAG_OWNDATA)) {
1201 				flags |= CTLFLAG_IMMEDIATE;
1202 				node.sysctl_qdata = uq;
1203 			}
1204 			else
1205 				node.sysctl_data = &uq;
1206 			if (sz == 0)
1207 				sz = sizeof(u_quad_t);
1208 			break;
1209 		case CTLTYPE_STRUCT:
1210 			sysctlperror("%s: struct not initializable\n",
1211 				     nname);
1212 			EXIT(1);
1213 		}
1214 
1215 		/*
1216 		 * these methods have all provided local starting
1217 		 * values that the kernel must copy in
1218 		 */
1219 	}
1220 
1221 	/*
1222 	 * hmm...no data, but we have an address of data.  that's
1223 	 * fine.
1224 	 */
1225 	else if (addr != 0)
1226 		node.sysctl_data = (void*)addr;
1227 
1228 	/*
1229 	 * no data and no address?  well...okay.  we might be able to
1230 	 * manage that.
1231 	 */
1232 	else if (type != CTLTYPE_NODE) {
1233 		if (sz == 0) {
1234 			sysctlperror(
1235 			    "%s: need a size or a starting value\n",
1236 			    nname);
1237                         EXIT(1);
1238                 }
1239 		if (!(flags & CTLFLAG_IMMEDIATE))
1240 			flags |= CTLFLAG_OWNDATA;
1241 	}
1242 
1243 	/*
1244 	 * now we do a few sanity checks on the description we've
1245 	 * assembled
1246 	 */
1247 	if ((flags & CTLFLAG_IMMEDIATE) &&
1248 	    (type == CTLTYPE_STRING || type == CTLTYPE_STRUCT)) {
1249 		sysctlperror("%s: cannot make an immediate %s\n",
1250 			     nname,
1251 			     (type == CTLTYPE_STRING) ? "string" : "struct");
1252 		EXIT(1);
1253 	}
1254 	if (type == CTLTYPE_NODE && node.sysctl_data != NULL) {
1255 		sysctlperror("%s: nodes do not have data\n", nname);
1256 		EXIT(1);
1257 	}
1258 
1259 	/*
1260 	 * some types must have a particular size
1261 	 */
1262 	if (sz != 0) {
1263 		if ((type == CTLTYPE_INT && sz != sizeof(int)) ||
1264 		    (type == CTLTYPE_QUAD && sz != sizeof(u_quad_t)) ||
1265 		    (type == CTLTYPE_NODE && sz != 0)) {
1266 			sysctlperror("%s: wrong size for type\n", nname);
1267 			EXIT(1);
1268 		}
1269 	}
1270 	else if (type == CTLTYPE_STRUCT) {
1271 		sysctlperror("%s: struct must have size\n", nname);
1272 		EXIT(1);
1273 	}
1274 
1275 	/*
1276 	 * now...if no one said anything yet, we default nodes or
1277 	 * any type that owns data being writeable, and everything
1278 	 * else being readonly.
1279 	 */
1280 	if (rw == -1) {
1281 		if (type == CTLTYPE_NODE ||
1282 		    (flags & (CTLFLAG_OWNDATA|CTLFLAG_IMMEDIATE)))
1283 			rw = CTLFLAG_READWRITE;
1284 		else
1285 			rw = CTLFLAG_READONLY;
1286 	}
1287 
1288 	/*
1289 	 * if a kernel address was specified, that can't be made
1290 	 * writeable by us.
1291 	if (rw != CTLFLAG_READONLY && addr) {
1292 		sysctlperror("%s: kernel data can only be readable\n", nname);
1293 		EXIT(1);
1294 	}
1295 	 */
1296 
1297 	/*
1298 	 * what separator were they using in the full name of the new
1299 	 * node?
1300 	 */
1301 	if ((t = strpbrk(nname, "./")) == NULL)
1302 		sep[0] = '.';
1303 	else
1304 		sep[0] = t[0];
1305 	sep[1] = '\0';
1306 
1307 	/*
1308 	 * put it all together, now.  t'ain't much, is it?
1309 	 */
1310 	node.sysctl_flags = SYSCTL_VERSION|flags|rw|type;
1311 	node.sysctl_size = sz;
1312 	t = strrchr(nname, sep[0]);
1313 	if (t != NULL)
1314 		strlcpy(node.sysctl_name, t + 1, sizeof(node.sysctl_name));
1315 	else
1316 		strlcpy(node.sysctl_name, nname, sizeof(node.sysctl_name));
1317 	if (t == nname)
1318 		t = NULL;
1319 
1320 	/*
1321 	 * if this is a new top-level node, then we don't need to find
1322 	 * the mib for its parent
1323 	 */
1324 	if (t == NULL) {
1325 		namelen = 0;
1326 		gsname[0] = '\0';
1327 	}
1328 
1329 	/*
1330 	 * on the other hand, if it's not a top-level node...
1331 	 */
1332 	else {
1333 		namelen = sizeof(name) / sizeof(name[0]);
1334 		sz = sizeof(gsname);
1335 		*t = '\0';
1336 		rc = sysctlgetmibinfo(nname, &name[0], &namelen,
1337 				      gsname, &sz, NULL, SYSCTL_VERSION);
1338 		*t = sep[0];
1339 		if (rc == -1) {
1340 			sysctlparseerror(namelen, nname);
1341 			EXIT(1);
1342 		}
1343 	}
1344 
1345 	/*
1346 	 * yes, a new node is being created
1347 	 */
1348 	if (method != 0)
1349 		name[namelen++] = method;
1350 	else
1351 		name[namelen++] = CTL_CREATE;
1352 
1353 	sz = sizeof(node);
1354 	rc = sysctl(&name[0], namelen, &node, &sz, &node, sizeof(node));
1355 
1356 	if (rc == -1) {
1357 		sysctlperror("%s: CTL_CREATE failed: %s\n",
1358 			     nname, strerror(errno));
1359 		EXIT(1);
1360 	}
1361 	else {
1362 		if (!qflag && !nflag)
1363 			printf("%s(%s): (created)\n", nname, st(type));
1364 		stale = 1;
1365 	}
1366 }
1367 
1368 static void
1369 parse_destroy(char *l)
1370 {
1371 	struct sysctlnode node;
1372 	size_t sz;
1373 	int name[CTL_MAXNAME], rc;
1374 	u_int namelen;
1375 
1376 	if (!wflag) {
1377 		sysctlperror("Must specify -w to destroy nodes\n");
1378 		exit(1);
1379 	}
1380 
1381 	memset(name, 0, sizeof(name));
1382 	namelen = sizeof(name) / sizeof(name[0]);
1383 	sz = sizeof(gsname);
1384 	rc = sysctlgetmibinfo(l, &name[0], &namelen, gsname, &sz, NULL,
1385 			      SYSCTL_VERSION);
1386 	if (rc == -1) {
1387 		sysctlparseerror(namelen, l);
1388 		EXIT(1);
1389 	}
1390 
1391 	memset(&node, 0, sizeof(node));
1392 	node.sysctl_flags = SYSCTL_VERSION;
1393 	node.sysctl_num = name[namelen - 1];
1394 	name[namelen - 1] = CTL_DESTROY;
1395 
1396 	sz = sizeof(node);
1397 	rc = sysctl(&name[0], namelen, &node, &sz, &node, sizeof(node));
1398 
1399 	if (rc == -1) {
1400 		sysctlperror("%s: CTL_DESTROY failed: %s\n",
1401 			     l, strerror(errno));
1402 		EXIT(1);
1403 	}
1404 	else {
1405 		if (!qflag && !nflag)
1406 			printf("%s(%s): (destroyed)\n", gsname,
1407 			       st(SYSCTL_TYPE(node.sysctl_flags)));
1408 		stale = 1;
1409 	}
1410 }
1411 
1412 static void
1413 parse_describe(char *l)
1414 {
1415 	struct sysctlnode newdesc;
1416 	char buf[1024], *value;
1417 	struct sysctldesc *d = (void*)&buf[0];
1418 	int name[CTL_MAXNAME], rc;
1419 	u_int namelen;
1420 	size_t sz;
1421 
1422 	if (!wflag) {
1423 		sysctlperror("Must specify -w to set descriptions\n");
1424 		exit(1);
1425 	}
1426 
1427 	value = strchr(l, '=');
1428 	*value++ = '\0';
1429 
1430 	memset(name, 0, sizeof(name));
1431 	namelen = sizeof(name) / sizeof(name[0]);
1432 	sz = sizeof(gsname);
1433 	rc = sysctlgetmibinfo(l, &name[0], &namelen, gsname, &sz, NULL,
1434 			      SYSCTL_VERSION);
1435 	if (rc == -1) {
1436 		sysctlparseerror(namelen, l);
1437 		EXIT(1);
1438 	}
1439 
1440 	sz = sizeof(buf);
1441 	memset(&newdesc, 0, sizeof(newdesc));
1442 	newdesc.sysctl_flags = SYSCTL_VERSION|CTLFLAG_OWNDESC;
1443 	newdesc.sysctl_num = name[namelen - 1];
1444 	newdesc.sysctl_desc = value;
1445 	name[namelen - 1] = CTL_DESCRIBE;
1446 	rc = sysctl(name, namelen, d, &sz, &newdesc, sizeof(newdesc));
1447 	if (rc == -1)
1448 		sysctlperror("%s: CTL_DESCRIBE failed: %s\n",
1449 			     gsname, strerror(errno));
1450 	else if (d->descr_len == 1)
1451 		sysctlperror("%s: description not set\n", gsname);
1452 	else if (!qflag && !nflag)
1453 		printf("%s: %s\n", gsname, d->descr_str);
1454 }
1455 
1456 /*
1457  * ********************************************************************
1458  * when things go wrong...
1459  * ********************************************************************
1460  */
1461 static void
1462 usage(void)
1463 {
1464 	const char *progname = getprogname();
1465 
1466 	(void)fprintf(stderr,
1467 		      "usage:\t%s %s\n"
1468 		      "\t%s %s\n"
1469 		      "\t%s %s\n"
1470 		      "\t%s %s\n"
1471 		      "\t%s %s\n"
1472 		      "\t%s %s\n",
1473 		      progname, "[-dne] [-x[x]|-r] variable ...",
1474 		      progname, "[-ne] [-q] -w variable=value ...",
1475 		      progname, "[-dne] -a",
1476 		      progname, "[-dne] -A",
1477 		      progname, "[-ne] -M",
1478 		      progname, "[-dne] [-q] -f file");
1479 	exit(1);
1480 }
1481 
1482 static void
1483 getdesc1(int *name, u_int namelen, struct sysctlnode *pnode)
1484 {
1485 	struct sysctlnode node;
1486 	char buf[1024], *desc;
1487 	struct sysctldesc *d = (void*)buf;
1488 	size_t sz = sizeof(buf);
1489 	int rc;
1490 
1491 	memset(&node, 0, sizeof(node));
1492 	node.sysctl_flags = SYSCTL_VERSION;
1493 	node.sysctl_num = name[namelen - 1];
1494 	name[namelen - 1] = CTL_DESCRIBE;
1495 	rc = sysctl(name, namelen, d, &sz, &node, sizeof(node));
1496 
1497 	if (rc == -1 ||
1498 	    d->descr_len == 1 ||
1499 	    d->descr_num != pnode->sysctl_num ||
1500 	    d->descr_ver != pnode->sysctl_ver)
1501 		desc = (char *)-1;
1502 	else
1503 		desc = malloc(d->descr_len);
1504 
1505 	if (desc == NULL)
1506 		desc = (char *)-1;
1507 	if (desc != (char *)-1)
1508 		memcpy(desc, &d->descr_str[0], d->descr_len);
1509 	name[namelen - 1] = node.sysctl_num;
1510 	if (pnode->sysctl_desc != NULL &&
1511 	    pnode->sysctl_desc != (const char *)-1)
1512 		free(__UNCONST(pnode->sysctl_desc));
1513 	pnode->sysctl_desc = desc;
1514 }
1515 
1516 static void
1517 getdesc(int *name, u_int namelen, struct sysctlnode *pnode)
1518 {
1519 	struct sysctlnode *node = pnode->sysctl_child;
1520 	struct sysctldesc *d, *p, *plim;
1521 	char *desc;
1522 	size_t sz;
1523 	int rc, i;
1524 
1525 	sz = 128 * pnode->sysctl_clen;
1526 	name[namelen] = CTL_DESCRIBE;
1527 
1528 	/*
1529 	 * attempt *twice* to get the description chunk.  if two tries
1530 	 * doesn't work, give up.
1531 	 */
1532 	i = 0;
1533 	do {
1534 		d = malloc(sz);
1535 		if (d == NULL)
1536 			return;
1537 		rc = sysctl(name, namelen + 1, d, &sz, NULL, 0);
1538 		if (rc == -1) {
1539 			free(d);
1540 			d = NULL;
1541 			if (i == 0 && errno == ENOMEM)
1542 				i = 1;
1543 			else
1544 				return;
1545 		}
1546 	} while (d == NULL);
1547 
1548 	/*
1549 	 * hokey nested loop here, giving O(n**2) behavior, but should
1550 	 * suffice for now
1551 	 */
1552 	plim = /*LINTED ptr cast*/(struct sysctldesc *)((char*)d + sz);
1553 	for (i = 0; i < pnode->sysctl_clen; i++) {
1554 		node = &pnode->sysctl_child[i];
1555 		for (p = d; p < plim; p = NEXT_DESCR(p))
1556 			if (node->sysctl_num == p->descr_num)
1557 				break;
1558 		if (p < plim && node->sysctl_ver == p->descr_ver) {
1559 			/*
1560 			 * match found, attempt to attach description
1561 			 */
1562 			if (p->descr_len == 1)
1563 				desc = NULL;
1564 			else
1565 				desc = malloc(p->descr_len);
1566 			if (desc == NULL)
1567 				desc = (char *)-1;
1568 			else
1569 				memcpy(desc, &p->descr_str[0], p->descr_len);
1570 			node->sysctl_desc = desc;
1571 		}
1572 	}
1573 
1574 	free(d);
1575 }
1576 
1577 static void
1578 trim_whitespace(char *s, int dir)
1579 {
1580 	char *i, *o;
1581 
1582 	i = o = s;
1583 	if (dir & 1)
1584 		while (isspace((unsigned char)*i))
1585 			i++;
1586 	while ((*o++ = *i++) != '\0');
1587 	o -= 2; /* already past nul, skip back to before it */
1588 	if (dir & 2)
1589 		while (o > s && isspace((unsigned char)*o))
1590 			*o-- = '\0';
1591 }
1592 
1593 void
1594 sysctlerror(int soft)
1595 {
1596 	if (soft) {
1597 		switch (errno) {
1598 		case ENOENT:
1599 		case ENOPROTOOPT:
1600 		case ENOTDIR:
1601 		case EINVAL:
1602 		case EOPNOTSUPP:
1603 		case EPROTONOSUPPORT:
1604 			if (Aflag || req)
1605 				sysctlperror("%s: the value is not available\n",
1606 					     gsname);
1607 			return;
1608 		}
1609 	}
1610 
1611 	sysctlperror("%s: sysctl() failed with %s\n",
1612 		     gsname, strerror(errno));
1613 	if (!soft)
1614 		EXIT(1);
1615 }
1616 
1617 void
1618 sysctlparseerror(u_int namelen, const char *pname)
1619 {
1620 
1621 	sysctlperror("%s level name '%s' in '%s' is invalid\n",
1622 		     lname[namelen], gsname, pname);
1623 }
1624 
1625 static void
1626 sysctlperror(const char *fmt, ...)
1627 {
1628 	va_list ap;
1629 
1630 	(void)fprintf(warnfp, "%s: ", getprogname());
1631 	if (fn)
1632 		(void)fprintf(warnfp, "%s#%zu: ", fn, nr);
1633 	va_start(ap, fmt);
1634 	(void)vfprintf(warnfp, fmt, ap);
1635 	va_end(ap);
1636 }
1637 
1638 
1639 /*
1640  * ********************************************************************
1641  * how to write to a "simple" node
1642  * ********************************************************************
1643  */
1644 static void
1645 write_number(int *name, u_int namelen, struct sysctlnode *node, char *value)
1646 {
1647 	u_int ii, io;
1648 	u_quad_t qi, qo;
1649 	size_t si, so;
1650 	int rc;
1651 	void *i, *o;
1652 	char *t;
1653 
1654 	if (fn)
1655 		trim_whitespace(value, 3);
1656 
1657 	si = so = 0;
1658 	i = o = NULL;
1659 	errno = 0;
1660 	qi = strtouq(value, &t, 0);
1661 	if (qi == UQUAD_MAX && errno == ERANGE) {
1662 		sysctlperror("%s: %s\n", value, strerror(errno));
1663 		EXIT(1);
1664 	}
1665 	if (t == value || *t != '\0') {
1666 		sysctlperror("%s: not a number\n", value);
1667 		EXIT(1);
1668 	}
1669 
1670 	switch (SYSCTL_TYPE(node->sysctl_flags)) {
1671 	case CTLTYPE_INT:
1672 		ii = (u_int)qi;
1673 		io = (u_int)(qi >> 32);
1674 		if (io != (u_int)-1 && io != 0) {
1675 			sysctlperror("%s: %s\n", value, strerror(ERANGE));
1676 			EXIT(1);
1677 		}
1678 		o = &io;
1679 		so = sizeof(io);
1680 		i = &ii;
1681 		si = sizeof(ii);
1682 		break;
1683 	case CTLTYPE_QUAD:
1684 		o = &qo;
1685 		so = sizeof(qo);
1686 		i = &qi;
1687 		si = sizeof(qi);
1688 		break;
1689 	}
1690 
1691 	rc = sysctl(name, namelen, o, &so, i, si);
1692 	if (rc == -1) {
1693 		sysctlerror(0);
1694 		return;
1695 	}
1696 
1697 	switch (SYSCTL_TYPE(node->sysctl_flags)) {
1698 	case CTLTYPE_INT:
1699 		display_number(node, gsname, &io, sizeof(io), DISPLAY_OLD);
1700 		display_number(node, gsname, &ii, sizeof(ii), DISPLAY_NEW);
1701 		break;
1702 	case CTLTYPE_QUAD:
1703 		display_number(node, gsname, &qo, sizeof(qo), DISPLAY_OLD);
1704 		display_number(node, gsname, &qi, sizeof(qi), DISPLAY_NEW);
1705 		break;
1706 	}
1707 }
1708 
1709 static void
1710 write_string(int *name, u_int namelen, struct sysctlnode *node, char *value)
1711 {
1712 	char *i, *o;
1713 	size_t si, so;
1714 	int rc;
1715 
1716 	i = value;
1717 	si = strlen(i) + 1;
1718 	so = node->sysctl_size;
1719 	if (si > so && so != 0) {
1720 		sysctlperror("%s: string too long\n", value);
1721 		EXIT(1);
1722 	}
1723 	o = malloc(so);
1724 	if (o == NULL) {
1725 		sysctlperror("%s: !malloc failed!\n", gsname);
1726 		exit(1);
1727 	}
1728 
1729 	rc = sysctl(name, namelen, o, &so, i, si);
1730 	if (rc == -1) {
1731 		sysctlerror(0);
1732 		return;
1733 	}
1734 
1735 	display_string(node, gsname, o, so, DISPLAY_OLD);
1736 	display_string(node, gsname, i, si, DISPLAY_NEW);
1737 	free(o);
1738 }
1739 
1740 /*
1741  * ********************************************************************
1742  * simple ways to print stuff consistently
1743  * ********************************************************************
1744  */
1745 static void
1746 display_number(const struct sysctlnode *node, const char *name,
1747 	       const void *data, size_t sz, int n)
1748 {
1749 	u_quad_t q;
1750 	int i;
1751 
1752 	if (qflag)
1753 		return;
1754 	if ((nflag || rflag) && (n == DISPLAY_OLD))
1755 		return;
1756 
1757 	if (rflag && n != DISPLAY_OLD) {
1758 		fwrite(data, sz, 1, stdout);
1759 		return;
1760 	}
1761 
1762 	if (!nflag) {
1763 		if (n == DISPLAY_VALUE)
1764 			printf("%s%s", name, eq);
1765 		else if (n == DISPLAY_OLD)
1766 			printf("%s: ", name);
1767 	}
1768 
1769 	if (xflag > 1) {
1770 		if (n != DISPLAY_NEW)
1771 			printf("\n");
1772 		hex_dump(data, sz);
1773 		return;
1774 	}
1775 
1776 	switch (SYSCTL_TYPE(node->sysctl_flags)) {
1777 	case CTLTYPE_INT:
1778 		memcpy(&i, data, sz);
1779 		if (xflag)
1780 			printf("0x%0*x", (int)sz * 2, i);
1781 		else if (node->sysctl_flags & CTLFLAG_HEX)
1782 			printf("%#x", i);
1783 		else
1784 			printf("%d", i);
1785 		break;
1786 	case CTLTYPE_QUAD:
1787 		memcpy(&q, data, sz);
1788 		if (xflag)
1789 			printf("0x%0*" PRIx64, (int)sz * 2, q);
1790 		else if (node->sysctl_flags & CTLFLAG_HEX)
1791 			printf("%#" PRIx64, q);
1792 		else
1793 			printf("%" PRIu64, q);
1794 		break;
1795 	}
1796 
1797 	if (n == DISPLAY_OLD)
1798 		printf(" -> ");
1799 	else
1800 		printf("\n");
1801 }
1802 
1803 static void
1804 display_string(const struct sysctlnode *node, const char *name,
1805 	       const void *data, size_t sz, int n)
1806 {
1807 	const unsigned char *buf = data;
1808 	int ni;
1809 
1810 	if (qflag)
1811 		return;
1812 	if ((nflag || rflag) && (n == DISPLAY_OLD))
1813 		return;
1814 
1815 	if (rflag && n != DISPLAY_OLD) {
1816 		fwrite(data, sz, 1, stdout);
1817 		return;
1818 	}
1819 
1820 	if (!nflag) {
1821 		if (n == DISPLAY_VALUE)
1822 			printf("%s%s", name, eq);
1823 		else if (n == DISPLAY_OLD)
1824 			printf("%s: ", name);
1825 	}
1826 
1827 	if (xflag > 1) {
1828 		if (n != DISPLAY_NEW)
1829 			printf("\n");
1830 		hex_dump(data, sz);
1831 		return;
1832 	}
1833 
1834 	if (xflag || node->sysctl_flags & CTLFLAG_HEX) {
1835 		for (ni = 0; ni < (int)sz; ni++) {
1836 			if (xflag)
1837 				printf("%02x", buf[ni]);
1838 			if (buf[ni] == '\0')
1839 				break;
1840 			if (!xflag)
1841 				printf("\\x%2.2x", buf[ni]);
1842 		}
1843 	}
1844 	else
1845 		printf("%.*s", (int)sz, buf);
1846 
1847 	if (n == DISPLAY_OLD)
1848 		printf(" -> ");
1849 	else
1850 		printf("\n");
1851 }
1852 
1853 /*ARGSUSED*/
1854 static void
1855 display_struct(const struct sysctlnode *node, const char *name,
1856 	       const void *data, size_t sz, int n)
1857 {
1858 	const unsigned char *buf = data;
1859 	int ni;
1860 	size_t more;
1861 
1862 	if (qflag)
1863 		return;
1864 	if (!(xflag || rflag)) {
1865 		if (Aflag || req)
1866 			sysctlperror(
1867 			    "%s: this type is unknown to this program\n",
1868 			    gsname);
1869 		return;
1870 	}
1871 	if ((nflag || rflag) && (n == DISPLAY_OLD))
1872 		return;
1873 
1874 	if (rflag && n != DISPLAY_OLD) {
1875 		fwrite(data, sz, 1, stdout);
1876 		return;
1877 	}
1878 
1879         if (!nflag) {
1880                 if (n == DISPLAY_VALUE)
1881                         printf("%s%s", name, eq);
1882                 else if (n == DISPLAY_OLD)
1883                         printf("%s: ", name);
1884         }
1885 
1886 	if (xflag > 1) {
1887 		if (n != DISPLAY_NEW)
1888 			printf("\n");
1889 		hex_dump(data, sz);
1890 		return;
1891 	}
1892 
1893 	if (sz > 16) {
1894 		more = sz - 16;
1895 		sz = 16;
1896 	}
1897 	else
1898 		more = 0;
1899 	for (ni = 0; ni < (int)sz; ni++)
1900 		printf("%02x", buf[ni]);
1901 	if (more)
1902 		printf("...(%zu more bytes)", more);
1903 	printf("\n");
1904 }
1905 
1906 static void
1907 hex_dump(const unsigned char *buf, size_t len)
1908 {
1909 	int i, j;
1910 	char line[80], tmp[12];
1911 
1912 	memset(line, ' ', sizeof(line));
1913 	for (i = 0, j = 15; i < len; i++) {
1914 		j = i % 16;
1915 		/* reset line */
1916 		if (j == 0) {
1917 			line[58] = '|';
1918 			line[77] = '|';
1919 			line[78] = 0;
1920 			snprintf(tmp, sizeof(tmp), "%07d", i);
1921 			memcpy(&line[0], tmp, 7);
1922 		}
1923 		/* copy out hex version of byte */
1924 		snprintf(tmp, sizeof(tmp), "%02x", buf[i]);
1925 		memcpy(&line[9 + j * 3], tmp, 2);
1926 		/* copy out plain version of byte */
1927 		line[60 + j] = (isprint(buf[i])) ? buf[i] : '.';
1928 		/* print a full line and erase it */
1929 		if (j == 15) {
1930 			printf("%s\n", line);
1931 			memset(line, ' ', sizeof(line));
1932 		}
1933 	}
1934 	if (line[0] != ' ')
1935 		printf("%s\n", line);
1936 	printf("%07zu bytes\n", len);
1937 }
1938 
1939 /*
1940  * ********************************************************************
1941  * functions that handle particular nodes
1942  * ********************************************************************
1943  */
1944 /*ARGSUSED*/
1945 static void
1946 printother(HANDLER_ARGS)
1947 {
1948 	int rc;
1949 	void *p;
1950 	size_t sz1, sz2;
1951 
1952 	if (!(Aflag || req) || Mflag)
1953 		return;
1954 
1955 	/*
1956 	 * okay...you asked for it, so let's give it a go
1957 	 */
1958 	while (type != CTLTYPE_NODE && (xflag || rflag)) {
1959 		rc = sysctl(name, namelen, NULL, &sz1, NULL, 0);
1960 		if (rc == -1 || sz1 == 0)
1961 			break;
1962 		p = malloc(sz1);
1963 		if (p == NULL)
1964 			break;
1965 		sz2 = sz1;
1966 		rc = sysctl(name, namelen, p, &sz2, NULL, 0);
1967 		if (rc == -1 || sz1 != sz2) {
1968 			free(p);
1969 			break;
1970 		}
1971 		display_struct(pnode, gsname, p, sz1, DISPLAY_VALUE);
1972 		free(p);
1973 		return;
1974 	}
1975 
1976 	/*
1977 	 * that didn't work...do we have a specific message for this
1978 	 * thing?
1979 	 */
1980 	if (v != NULL) {
1981 		sysctlperror("%s: use '%s' to view this information\n",
1982 			     gsname, (const char *)v);
1983 		return;
1984 	}
1985 
1986 	/*
1987 	 * hmm...i wonder if we have any generic hints?
1988 	 */
1989 	switch (name[0]) {
1990 	case CTL_NET:
1991 		sysctlperror("%s: use 'netstat' to view this information\n",
1992 			     sname);
1993 		break;
1994 	case CTL_DEBUG:
1995 		sysctlperror("%s: missing 'options DEBUG' from kernel?\n",
1996 			     sname);
1997 		break;
1998 	case CTL_DDB:
1999 		sysctlperror("%s: missing 'options DDB' from kernel?\n",
2000 			     sname);
2001 		break;
2002 	case CTL_VENDOR:
2003 		sysctlperror("%s: no vendor extensions installed\n",
2004 			     sname);
2005 		break;
2006 	}
2007 }
2008 
2009 /*ARGSUSED*/
2010 static void
2011 kern_clockrate(HANDLER_ARGS)
2012 {
2013 	struct clockinfo clkinfo;
2014 	size_t sz;
2015 	int rc;
2016 
2017 	sz = sizeof(clkinfo);
2018 	rc = sysctl(name, namelen, &clkinfo, &sz, NULL, 0);
2019 	if (rc == -1) {
2020 		sysctlerror(1);
2021 		return;
2022 	}
2023 	if (sz != sizeof(clkinfo))
2024 		errx(1, "%s: !returned size wrong!", sname);
2025 
2026 	if (xflag || rflag) {
2027 		display_struct(pnode, sname, &clkinfo, sz,
2028 			       DISPLAY_VALUE);
2029 		return;
2030 	}
2031 	else if (!nflag)
2032 		printf("%s: ", sname);
2033 	printf("tick = %d, tickadj = %d, hz = %d, profhz = %d, stathz = %d\n",
2034 	       clkinfo.tick, clkinfo.tickadj,
2035 	       clkinfo.hz, clkinfo.profhz, clkinfo.stathz);
2036 }
2037 
2038 /*ARGSUSED*/
2039 static void
2040 kern_boottime(HANDLER_ARGS)
2041 {
2042 	struct timeval timeval;
2043 	time_t boottime;
2044 	size_t sz;
2045 	int rc;
2046 
2047 	sz = sizeof(timeval);
2048 	rc = sysctl(name, namelen, &timeval, &sz, NULL, 0);
2049 	if (rc == -1) {
2050 		sysctlerror(1);
2051 		return;
2052 	}
2053 	if (sz != sizeof(timeval))
2054 		errx(1, "%s: !returned size wrong!", sname);
2055 
2056 	boottime = timeval.tv_sec;
2057 	if (xflag || rflag)
2058 		display_struct(pnode, sname, &timeval, sz,
2059 			       DISPLAY_VALUE);
2060 	else if (!nflag)
2061 		/* ctime() provides the \n */
2062 		printf("%s%s%s", sname, eq, ctime(&boottime));
2063 	else if (nflag == 1)
2064 		printf("%ld\n", (long)boottime);
2065 	else
2066 		printf("%ld.%06ld\n", (long)timeval.tv_sec,
2067 		       (long)timeval.tv_usec);
2068 }
2069 
2070 /*ARGSUSED*/
2071 static void
2072 kern_consdev(HANDLER_ARGS)
2073 {
2074 	dev_t cons;
2075 	size_t sz;
2076 	int rc;
2077 
2078 	sz = sizeof(cons);
2079 	rc = sysctl(name, namelen, &cons, &sz, NULL, 0);
2080 	if (rc == -1) {
2081 		sysctlerror(1);
2082 		return;
2083 	}
2084 	if (sz != sizeof(cons))
2085 		errx(1, "%s: !returned size wrong!", sname);
2086 
2087 	if (xflag || rflag)
2088 		display_struct(pnode, sname, &cons, sz,
2089 			       DISPLAY_VALUE);
2090 	else {
2091 		if (!nflag)
2092 			printf("%s%s", sname, eq);
2093 		if (nflag < 2 && (sname = devname(cons, S_IFCHR)) != NULL)
2094 			printf("%s\n", sname);
2095 		else
2096 			printf("0x%x\n", cons);
2097 	}
2098 }
2099 
2100 /*ARGSUSED*/
2101 static void
2102 kern_cp_time(HANDLER_ARGS)
2103 {
2104 	u_int64_t *cp_time;
2105 	size_t sz, osz;
2106 	int rc, i, n;
2107 	char s[sizeof("kern.cp_time.nnnnnn")];
2108 	const char *tname;
2109 
2110 	/*
2111 	 * three things to do here.
2112 	 * case 1: get sum (no Aflag and namelen == 2)
2113 	 * case 2: get specific processor (namelen == 3)
2114 	 * case 3: get all processors (Aflag and namelen == 2)
2115 	 */
2116 
2117 	if (namelen == 2 && Aflag) {
2118 		sz = sizeof(n);
2119 		rc = sysctlbyname("hw.ncpu", &n, &sz, NULL, 0);
2120 		if (rc != 0)
2121 			return; /* XXX print an error, eh? */
2122 		n++; /* Add on space for the sum. */
2123 		sz = n * sizeof(u_int64_t) * CPUSTATES;
2124 	}
2125 	else {
2126 		n = -1; /* Just print one data set. */
2127 		sz = sizeof(u_int64_t) * CPUSTATES;
2128 	}
2129 
2130 	cp_time = malloc(sz);
2131 	if (cp_time == NULL) {
2132 		sysctlerror(1);
2133 		return;
2134 	}
2135 
2136 	osz = sz;
2137 	rc = sysctl(name, namelen, cp_time + (n != -1) * CPUSTATES, &osz,
2138 		    NULL, 0);
2139 
2140 	if (rc == -1) {
2141 		sysctlerror(1);
2142 		free(cp_time);
2143 		return;
2144 	}
2145 
2146 	/*
2147 	 * Check, but account for space we'll occupy with the sum.
2148 	 */
2149 	if (osz != sz - (n != -1) * CPUSTATES * sizeof(u_int64_t))
2150 		errx(1, "%s: !returned size wrong!", sname);
2151 
2152 	/*
2153 	 * Compute the actual sum.  Two calls would be easier (we
2154 	 * could just call ourselves recursively above), but the
2155 	 * numbers wouldn't add up.
2156 	 */
2157 	if (n != -1) {
2158 		memset(cp_time, 0, sizeof(u_int64_t) * CPUSTATES);
2159 		for (i = 1; i < n; i++) {
2160 			cp_time[CP_USER] += cp_time[i * CPUSTATES + CP_USER];
2161                         cp_time[CP_NICE] += cp_time[i * CPUSTATES + CP_NICE];
2162                         cp_time[CP_SYS] += cp_time[i * CPUSTATES + CP_SYS];
2163                         cp_time[CP_INTR] += cp_time[i * CPUSTATES + CP_INTR];
2164                         cp_time[CP_IDLE] += cp_time[i * CPUSTATES + CP_IDLE];
2165 		}
2166 	}
2167 
2168 	tname = sname;
2169 	for (i = 0; n == -1 || i < n; i++) {
2170 		if (i > 0) {
2171 			(void)snprintf(s, sizeof(s), "%s%s%d", sname, sep,
2172 				       i - 1);
2173 			tname = s;
2174 		}
2175 		if (xflag || rflag)
2176 			display_struct(pnode, tname, cp_time + (i * CPUSTATES),
2177 				       sizeof(u_int64_t) * CPUSTATES,
2178 				       DISPLAY_VALUE);
2179 		else {
2180 			if (!nflag)
2181 				printf("%s: ", tname);
2182 			printf("user = %" PRIu64
2183 			       ", nice = %" PRIu64
2184 			       ", sys = %" PRIu64
2185 			       ", intr = %" PRIu64
2186 			       ", idle = %" PRIu64
2187 			       "\n",
2188 			       cp_time[i * CPUSTATES + CP_USER],
2189 			       cp_time[i * CPUSTATES + CP_NICE],
2190 			       cp_time[i * CPUSTATES + CP_SYS],
2191 			       cp_time[i * CPUSTATES + CP_INTR],
2192 			       cp_time[i * CPUSTATES + CP_IDLE]);
2193 		}
2194 		/*
2195 		 * Just printing the one node.
2196 		 */
2197 		if (n == -1)
2198 			break;
2199 	}
2200 
2201 	free(cp_time);
2202 }
2203 
2204 /*ARGSUSED*/
2205 static void
2206 kern_cp_id(HANDLER_ARGS)
2207 {
2208 	u_int64_t *cp_id;
2209 	size_t sz, osz;
2210 	int rc, i, n;
2211 	char s[sizeof("kern.cp_id.nnnnnn")];
2212 	const char *tname;
2213 	struct sysctlnode node = *pnode;
2214 
2215 	/*
2216 	 * three things to do here.
2217 	 * case 1: print a specific cpu id (namelen == 3)
2218 	 * case 2: print all cpu ids separately (Aflag set)
2219 	 * case 3: print all cpu ids on one line
2220 	 */
2221 
2222 	if (namelen == 2) {
2223 		sz = sizeof(n);
2224 		rc = sysctlbyname("hw.ncpu", &n, &sz, NULL, 0);
2225 		if (rc != 0)
2226 			return; /* XXX print an error, eh? */
2227 		sz = n * sizeof(u_int64_t);
2228 	}
2229 	else {
2230 		n = -1; /* Just print one cpu id. */
2231 		sz = sizeof(u_int64_t);
2232 	}
2233 
2234 	cp_id = malloc(sz);
2235 	if (cp_id == NULL) {
2236 		sysctlerror(1);
2237 		return;
2238 	}
2239 
2240 	osz = sz;
2241 	rc = sysctl(name, namelen, cp_id, &osz, NULL, 0);
2242 	if (rc == -1) {
2243 		sysctlerror(1);
2244 		free(cp_id);
2245 		return;
2246 	}
2247 
2248 	/*
2249 	 * Check that we got back what we asked for.
2250 	 */
2251 	if (osz != sz)
2252 		errx(1, "%s: !returned size wrong!", sname);
2253 
2254 	/* pretend for output purposes */
2255 	node.sysctl_flags = SYSCTL_FLAGS(pnode->sysctl_flags) |
2256 		SYSCTL_TYPE(CTLTYPE_QUAD);
2257 
2258 	tname = sname;
2259 	if (namelen == 3)
2260 		display_number(&node, tname, cp_id,
2261 			       sizeof(u_int64_t),
2262 			       DISPLAY_VALUE);
2263 	else if (Aflag) {
2264 		for (i = 0; i < n; i++)
2265 			(void)snprintf(s, sizeof(s), "%s%s%d", sname, sep, i);
2266 			tname = s;
2267 			display_number(&node, tname, &cp_id[i],
2268 				       sizeof(u_int64_t),
2269 				       DISPLAY_VALUE);
2270 	}
2271 	else {
2272 		if (xflag || rflag)
2273 			display_struct(pnode, tname, cp_id, sz, DISPLAY_VALUE);
2274 		else {
2275 			if (!nflag)
2276 				printf("%s: ", tname);
2277 			for (i = 0; i < n; i++) {
2278 				if (i)
2279 					printf(", ");
2280 				printf("%d = %" PRIu64, i, cp_id[i]);
2281 			}
2282 			printf("\n");
2283 		}
2284 	}
2285 
2286 	free(cp_id);
2287 }
2288 
2289 /*ARGSUSED*/
2290 static void
2291 vm_loadavg(HANDLER_ARGS)
2292 {
2293 	struct loadavg loadavg;
2294 	size_t sz;
2295 	int rc;
2296 
2297 	sz = sizeof(loadavg);
2298 	rc = sysctl(name, namelen, &loadavg, &sz, NULL, 0);
2299 	if (rc == -1) {
2300 		sysctlerror(1);
2301 		return;
2302 	}
2303 	if (sz != sizeof(loadavg))
2304 		errx(1, "%s: !returned size wrong!", sname);
2305 
2306 	if (xflag || rflag) {
2307 		display_struct(pnode, sname, &loadavg, sz,
2308 			       DISPLAY_VALUE);
2309 		return;
2310 	}
2311 	if (!nflag)
2312 		printf("%s: ", sname);
2313 	printf("%.2f %.2f %.2f\n",
2314 	       (double) loadavg.ldavg[0] / loadavg.fscale,
2315 	       (double) loadavg.ldavg[1] / loadavg.fscale,
2316 	       (double) loadavg.ldavg[2] / loadavg.fscale);
2317 }
2318 
2319 /*ARGSUSED*/
2320 static void
2321 proc_limit(HANDLER_ARGS)
2322 {
2323 	u_quad_t olim, *newp, nlim;
2324 	size_t osz, nsz;
2325 	char *t;
2326 	int rc;
2327 
2328 	if (fn)
2329 		trim_whitespace(value, 3);
2330 
2331 	osz = sizeof(olim);
2332 	if (value != NULL) {
2333 		nsz = sizeof(nlim);
2334 		newp = &nlim;
2335 		if (strcmp(value, "unlimited") == 0)
2336 			nlim = RLIM_INFINITY;
2337 		else {
2338 			errno = 0;
2339 			nlim = strtouq(value, &t, 0);
2340 			if (t == value || *t != '\0' || errno != 0) {
2341 				sysctlperror("%s: '%s' is not a valid limit\n",
2342 					     sname, value);
2343 				EXIT(1);
2344 			}
2345 		}
2346 	}
2347 	else {
2348 		nsz = 0;
2349 		newp = NULL;
2350 	}
2351 
2352 	rc = sysctl(name, namelen, &olim, &osz, newp, nsz);
2353 	if (rc == -1) {
2354 		sysctlerror(newp == NULL);
2355 		return;
2356 	}
2357 
2358 	if (newp && qflag)
2359 		return;
2360 
2361 	if (rflag || xflag || olim != RLIM_INFINITY)
2362 		display_number(pnode, sname, &olim, sizeof(olim),
2363 			       newp ? DISPLAY_OLD : DISPLAY_VALUE);
2364 	else
2365 		display_string(pnode, sname, "unlimited", 10,
2366 			       newp ? DISPLAY_OLD : DISPLAY_VALUE);
2367 
2368 	if (newp) {
2369 		if (rflag || xflag || nlim != RLIM_INFINITY)
2370 			display_number(pnode, sname, &nlim, sizeof(nlim),
2371 				       DISPLAY_NEW);
2372 		else
2373 			display_string(pnode, sname, "unlimited", 10,
2374 				       DISPLAY_NEW);
2375 	}
2376 }
2377 
2378 #ifdef CPU_DISKINFO
2379 /*ARGSUSED*/
2380 static void
2381 machdep_diskinfo(HANDLER_ARGS)
2382 {
2383 	struct disklist *dl;
2384 	struct biosdisk_info *bi;
2385 	struct nativedisk_info *ni;
2386 	int rc;
2387 	size_t sz;
2388 	uint i, b, lim;
2389 
2390 	rc = sysctl(name, namelen, NULL, &sz, NULL, 0);
2391 	if (rc == -1) {
2392 		sysctlerror(1);
2393 		return;
2394 	}
2395 	dl = malloc(sz);
2396 	if (dl == NULL) {
2397 		sysctlerror(1);
2398 		return;
2399 	}
2400 	rc = sysctl(name, namelen, dl, &sz, NULL, 0);
2401 	if (rc == -1) {
2402 		sysctlerror(1);
2403 		return;
2404 	}
2405 
2406 	if (!nflag)
2407 		printf("%s: ", sname);
2408 	lim = dl->dl_nbiosdisks;
2409 	if (lim > MAX_BIOSDISKS)
2410 		lim = MAX_BIOSDISKS;
2411 	for (bi = dl->dl_biosdisks, i = 0; i < lim; bi++, i++)
2412 		printf("%x:%" PRIu64 "(%d/%d/%d),%x ",
2413 		       bi->bi_dev, bi->bi_lbasecs,
2414 		       bi->bi_cyl, bi->bi_head, bi->bi_sec,
2415 		       bi->bi_flags);
2416 	lim = dl->dl_nnativedisks;
2417 	ni = dl->dl_nativedisks;
2418 	bi = dl->dl_biosdisks;
2419 	/* LINTED -- pointer casts are tedious */
2420 	if ((char *)&ni[lim] != (char *)dl + sz) {
2421 		sysctlperror("%s: size mismatch\n", gsname);
2422 		return;
2423 	}
2424 	for (i = 0; i < lim; ni++, i++) {
2425 		char t = ':';
2426 		printf(" %.*s", (int)sizeof ni->ni_devname,
2427 		       ni->ni_devname);
2428 		for (b = 0; b < ni->ni_nmatches; t = ',', b++)
2429 			printf("%c%x", t,
2430 			       bi[ni->ni_biosmatches[b]].bi_dev);
2431 	}
2432 	printf("\n");
2433 }
2434 #endif /* CPU_DISKINFO */
2435 
2436 /*ARGSUSED*/
2437 static void
2438 mode_bits(HANDLER_ARGS)
2439 {
2440 	char buf[11], outbuf[100];
2441 	int o, m, *newp, rc;
2442 	size_t osz, nsz;
2443 	mode_t om, mm;
2444 
2445 	if (fn)
2446 		trim_whitespace(value, 3);
2447 
2448 	newp = NULL;
2449 	osz = sizeof(o);
2450 	if (value != NULL) {
2451 		void *foo;
2452 		int tt;
2453 		size_t ttsz = sizeof(tt);
2454 		mode_t old_umask;
2455 
2456 		nsz = sizeof(m);
2457 		newp = &m;
2458 		errno = 0;
2459 		rc = sysctl(name, namelen, &tt, &ttsz, NULL, 0);
2460 		if (rc == -1) {
2461 			sysctlperror("%s: failed query\n", sname);
2462 			return;
2463 		}
2464 
2465 		old_umask = umask(0);
2466 		foo = setmode(value);
2467 		umask(old_umask);
2468 		if (foo == NULL) {
2469 			sysctlperror("%s: '%s' is an invalid mode\n", sname,
2470 				     value);
2471 			EXIT(1);
2472 		}
2473 		old_umask = umask(0);
2474 		m = getmode(foo, (mode_t)tt);
2475 		umask(old_umask);
2476 		if (errno) {
2477 			sysctlperror("%s: '%s' is an invalid mode\n", sname,
2478 				     value);
2479 			EXIT(1);
2480 		}
2481 	}
2482 	else {
2483 		nsz = 0;
2484 		newp = NULL;
2485 	}
2486 
2487 	rc = sysctl(name, namelen, &o, &osz, newp, nsz);
2488 	if (rc == -1) {
2489 		sysctlerror(newp == NULL);
2490 		return;
2491 	}
2492 
2493 	if (newp && qflag)
2494 		return;
2495 
2496 	om = (mode_t)o;
2497 	mm = (mode_t)m;
2498 
2499 	if (rflag || xflag)
2500 		display_number(pnode, sname, &o, sizeof(o),
2501 			       newp ? DISPLAY_OLD : DISPLAY_VALUE);
2502 	else {
2503 		memset(buf, 0, sizeof(buf));
2504 		strmode(om, buf);
2505 		buf[10] = '\0';
2506 		rc = snprintf(outbuf, sizeof(outbuf), "%04o (%s)", om, buf + 1);
2507 		display_string(pnode, sname, outbuf, rc, newp ? DISPLAY_OLD : DISPLAY_VALUE);
2508 	}
2509 
2510 	if (newp) {
2511 		if (rflag || xflag)
2512 			display_number(pnode, sname, &m, sizeof(m),
2513 				       DISPLAY_NEW);
2514 		else {
2515 			memset(buf, 0, sizeof(buf));
2516 			strmode(mm, buf);
2517 			buf[10] = '\0';
2518 			rc = snprintf(outbuf, sizeof(outbuf), "%04o (%s)", mm, buf + 1);
2519 			display_string(pnode, sname, outbuf, rc, DISPLAY_NEW);
2520 		}
2521 	}
2522 }
2523