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