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