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