inet: return EHOSTDOWN if we cannot resolve an address in time
[dragonfly.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  * 3. 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  * @(#) Copyright (c) 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)from: sysctl.c   8.1 (Berkeley) 6/6/93
31  * $FreeBSD: src/sbin/sysctl/sysctl.c,v 1.25.2.11 2003/05/01 22:48:08 trhodes Exp $
32  */
33
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/sysctl.h>
37 #include <sys/resource.h>
38 #include <sys/sensors.h>
39 #include <sys/param.h>
40
41 #ifdef __x86_64__
42 #include <sys/efi.h>
43 #include <machine/metadata.h>
44 #endif
45
46 #include <ctype.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <inttypes.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54
55 static int      aflag, bflag, dflag, eflag, Nflag, nflag, oflag, xflag;
56 static int      iflag, qflag;
57
58 static int      oidfmt(int *, size_t, char *, u_int *);
59 static int      parse(const char *);
60 static int      show_var(int *, size_t);
61 static int      sysctl_all(int *, size_t);
62 static void     set_T_dev_t(const char *, void **, size_t *);
63 static int      set_IK(const char *, int *);
64
65 static void
66 usage(void)
67 {
68
69         fprintf(stderr, "%s\n%s\n",
70             "usage: sysctl [-bdeNnox] variable[=value] ...",
71             "       sysctl [-bdeNnox] -a");
72         exit(1);
73 }
74
75 int
76 main(int argc, char **argv)
77 {
78         int ch;
79         int warncount;
80
81         setbuf(stdout,0);
82         setbuf(stderr,0);
83
84         while ((ch = getopt(argc, argv, "AabdeiNnoqwxX")) != -1) {
85                 switch (ch) {
86                 case 'A':
87                         /* compatibility */
88                         aflag = oflag = 1;
89                         break;
90                 case 'a':
91                         aflag = 1;
92                         break;
93                 case 'b':
94                         bflag = 1;
95                         break;
96                 case 'd':
97                         dflag = 1;
98                         break;
99                 case 'e':
100                         eflag = 1;
101                         break;
102                 case 'i':
103                         iflag = 1;
104                         break;
105                 case 'N':
106                         Nflag = 1;
107                         break;
108                 case 'n':
109                         nflag = 1;
110                         break;
111                 case 'o':
112                         oflag = 1;
113                         break;
114                 case 'q':
115                         qflag = 1;
116                         break;
117                 case 'w':
118                         /* compatibility */
119                         /* ignored */
120                         break;
121                 case 'X':
122                         /* compatibility */
123                         aflag = xflag = 1;
124                         break;
125                 case 'x':
126                         xflag = 1;
127                         break;
128                 default:
129                         usage();
130                 }
131         }
132         argc -= optind;
133         argv += optind;
134
135         if (Nflag && nflag)
136                 usage();
137         if (aflag && argc == 0)
138                 exit(sysctl_all(0, 0));
139         if (argc == 0)
140                 usage();
141         warncount = 0;
142         while (argc-- > 0)
143                 warncount += parse(*argv++);
144
145         return warncount;
146 }
147
148 /*
149  * Parse a name into a MIB entry.
150  * Lookup and print out the MIB entry if it exists.
151  * Set a new value if requested.
152  */
153 static int
154 parse(const char *string)
155 {
156         size_t len;
157         int i, j;
158         void *newval = NULL;
159         int8_t i8val;
160         uint8_t u8val;
161         int16_t i16val;
162         uint16_t u16val;
163         int32_t i32val;
164         uint32_t u32val;
165         int64_t i64val;
166         uint64_t u64val;
167         int intval;
168         unsigned int uintval;
169         long longval;
170         unsigned long ulongval;
171         size_t newsize = 0;
172         int mib[CTL_MAXNAME];
173         char *cp, fmt[BUFSIZ];
174         const char *name;
175         char *name_allocated = NULL;
176         u_int kind;
177
178         if ((cp = strchr(string, '=')) != NULL) {
179                 if ((name_allocated = malloc(cp - string + 1)) == NULL)
180                         err(1, "malloc failed");
181                 strlcpy(name_allocated, string, cp - string + 1);
182                 name = name_allocated;
183                 
184                 while (isspace(*++cp))
185                         ;
186
187                 newval = cp;
188                 newsize = strlen(cp);
189         } else {
190                 name = string;
191         }
192
193         len = CTL_MAXNAME;
194         if (sysctlnametomib(name, mib, &len) < 0) {
195                 if (iflag)
196                         return 0;
197                 if (qflag)
198                         return 1;
199                 if (errno == ENOENT) {
200                         errx(1, "unknown oid '%s'", name);
201                 } else {
202                         err(1, "sysctlnametomib(\"%s\")", name);
203                 }
204         }
205
206         if (oidfmt(mib, len, fmt, &kind)) {
207                 warn("couldn't find format of oid '%s'", name);
208                 if (iflag)
209                         return 1;
210                 exit(1);
211         }
212
213         if (newval == NULL) {
214                 if ((kind & CTLTYPE) == CTLTYPE_NODE) {
215                         sysctl_all(mib, len);
216                 } else {
217                         i = show_var(mib, len);
218                         if (!i && !bflag)
219                                 putchar('\n');
220                 }
221         } else {
222                 if ((kind & CTLTYPE) == CTLTYPE_NODE)
223                         errx(1, "oid '%s' isn't a leaf node", name);
224
225                 if (!(kind&CTLFLAG_WR))
226                         errx(1, "oid '%s' is read only", name);
227         
228                 switch (kind & CTLTYPE) {
229                         case CTLTYPE_INT:
230                                 if (!(strcmp(fmt, "IK") == 0)) {
231                                         if (!set_IK(newval, &intval))
232                                                 errx(1, "invalid value '%s'",
233                                                     (char *)newval);
234                                 } else
235                                         intval = (int) strtol(newval, NULL, 0);
236                                 newval = &intval;
237                                 newsize = sizeof(intval);
238                                 break;
239                         case CTLTYPE_UINT:
240                                 uintval = (int) strtoul(newval, NULL, 0);
241                                 newval = &uintval;
242                                 newsize = sizeof uintval;
243                                 break;
244                         case CTLTYPE_LONG:
245                                 longval = strtol(newval, NULL, 0);
246                                 newval = &longval;
247                                 newsize = sizeof longval;
248                                 break;
249                         case CTLTYPE_ULONG:
250                                 ulongval = strtoul(newval, NULL, 0);
251                                 newval = &ulongval;
252                                 newsize = sizeof ulongval;
253                                 break;
254                         case CTLTYPE_STRING:
255                                 break;
256                         case CTLTYPE_S8:
257                                 i8val = (int8_t)strtol(newval, NULL, 0);
258                                 newval = &i8val;
259                                 newsize = sizeof(i8val);
260                                 break;
261                         case CTLTYPE_S16:
262                                 i16val = (int16_t)strtol(newval, NULL, 0);
263                                 newval = &i16val;
264                                 newsize = sizeof(i16val);
265                                 break;
266                         case CTLTYPE_S32:
267                                 i32val = (int32_t)strtol(newval, NULL, 0);
268                                 newval = &i32val;
269                                 newsize = sizeof(i32val);
270                                 break;
271                         case CTLTYPE_S64:
272                                 i64val = strtoimax(newval, NULL, 0);
273                                 newval = &i64val;
274                                 newsize = sizeof(i64val);
275                                 break;
276                         case CTLTYPE_U8:
277                                 u8val = (uint8_t)strtoul(newval, NULL, 0);
278                                 newval = &u8val;
279                                 newsize = sizeof(u8val);
280                                 break;
281                         case CTLTYPE_U16:
282                                 u16val = (uint16_t)strtoul(newval, NULL, 0);
283                                 newval = &u16val;
284                                 newsize = sizeof(u16val);
285                                 break;
286                         case CTLTYPE_U32:
287                                 u32val = (uint32_t)strtoul(newval, NULL, 0);
288                                 newval = &u32val;
289                                 newsize = sizeof(u32val);
290                                 break;
291                         case CTLTYPE_U64:
292                                 u64val = strtoumax(newval, NULL, 0);
293                                 newval = &u64val;
294                                 newsize = sizeof(u64val);
295                                 break;
296                         case CTLTYPE_OPAQUE:
297                                 if (strcmp(fmt, "T,dev_t") == 0 ||
298                                     strcmp(fmt, "T,udev_t") == 0
299                                 ) {
300                                         set_T_dev_t((char*)newval, &newval,
301                                                     &newsize);
302                                         break;
303                                 }
304                                 /* FALLTHROUGH */
305                         default:
306                                 errx(1, "oid '%s' is type %d,"
307                                         " cannot set that", name,
308                                         kind & CTLTYPE);
309                 }
310
311                 i = show_var(mib, len);
312                 if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
313                         if (!i && !bflag)
314                                 putchar('\n');
315                         switch (errno) {
316                         case EOPNOTSUPP:
317                                 errx(1, "%s: value is not available", 
318                                         string);
319                         case ENOTDIR:
320                                 errx(1, "%s: specification is incomplete", 
321                                         string);
322                         case ENOMEM:
323                                 errx(1, "%s: type is unknown to this program", 
324                                         string);
325                         default:
326                                 warn("%s", string);
327                                 return 1;
328                         }
329                 }
330                 if (!bflag)
331                         printf(" -> ");
332                 i = nflag;
333                 nflag = 1;
334                 j = show_var(mib, len);
335                 if (!j && !bflag)
336                         putchar('\n');
337                 nflag = i;
338         }
339
340         if (name_allocated != NULL)
341                 free(name_allocated);
342
343         return 0;
344 }
345
346 /* These functions will dump out various interesting structures. */
347
348 static int
349 S_clockinfo(size_t l2, void *p)
350 {
351         struct clockinfo *ci = (struct clockinfo*)p;
352         if (l2 != sizeof(*ci))
353                 err(1, "S_clockinfo %zu != %zu", l2, sizeof(*ci));
354         printf("{ hz = %d, tick = %d, tickadj = %d, profhz = %d, stathz = %d }",
355                 ci->hz, ci->tick, ci->tickadj, ci->profhz, ci->stathz);
356         return (0);
357 }
358
359 static int
360 S_loadavg(size_t l2, void *p)
361 {
362         struct loadavg *tv = (struct loadavg*)p;
363
364         if (l2 != sizeof(*tv))
365                 err(1, "S_loadavg %zu != %zu", l2, sizeof(*tv));
366
367         printf("{ %.2f %.2f %.2f }",
368                 (double)tv->ldavg[0]/(double)tv->fscale,
369                 (double)tv->ldavg[1]/(double)tv->fscale,
370                 (double)tv->ldavg[2]/(double)tv->fscale);
371         return (0);
372 }
373
374 static int
375 S_timespec(size_t l2, void *p)
376 {
377         struct timespec *ts = (struct timespec*)p;
378         time_t tv_sec;
379         char *p1, *p2;
380
381         if (l2 != sizeof(*ts))
382                 err(1, "S_timespec %zu != %zu", l2, sizeof(*ts));
383         printf("{ sec = %ld, nsec = %ld } ",
384                 ts->tv_sec, ts->tv_nsec);
385         tv_sec = ts->tv_sec;
386         p1 = strdup(ctime(&tv_sec));
387         for (p2=p1; *p2 ; p2++)
388                 if (*p2 == '\n')
389                         *p2 = '\0';
390         fputs(p1, stdout);
391         return (0);
392 }
393
394 static int
395 S_timeval(size_t l2, void *p)
396 {
397         struct timeval *tv = (struct timeval*)p;
398         time_t tv_sec;
399         char *p1, *p2;
400
401         if (l2 != sizeof(*tv))
402                 err(1, "S_timeval %zu != %zu", l2, sizeof(*tv));
403         printf("{ sec = %ld, usec = %ld } ",
404                 tv->tv_sec, tv->tv_usec);
405         tv_sec = tv->tv_sec;
406         p1 = strdup(ctime(&tv_sec));
407         for (p2=p1; *p2 ; p2++)
408                 if (*p2 == '\n')
409                         *p2 = '\0';
410         fputs(p1, stdout);
411         return (0);
412 }
413
414 static int
415 S_sensor(size_t l2, void *p)
416 {
417         struct sensor *s = (struct sensor *)p;
418
419         if (l2 != sizeof(*s)) {
420                 warnx("S_sensor %zu != %zu", l2, sizeof(*s));
421                 return (1);
422         }
423
424         if (s->flags & SENSOR_FINVALID) {
425                 /*
426                  * XXX: with this flag, the node should be entirely ignored,
427                  * but as the magic-based sysctl(8) is not too flexible, we
428                  * simply have to print out that the sensor is invalid.
429                  */
430                 printf("invalid");
431                 return (0);
432         }
433
434         if (s->flags & SENSOR_FUNKNOWN)
435                 printf("unknown");
436         else {
437                 switch (s->type) {
438                 case SENSOR_TEMP:
439                         printf("%.2f degC",
440                             (s->value - 273150000) / 1000000.0);
441                         break;
442                 case SENSOR_FANRPM:
443                         printf("%jd RPM", (intmax_t)s->value);
444                         break;
445                 case SENSOR_VOLTS_DC:
446                         printf("%.2f VDC", s->value / 1000000.0);
447                         break;
448                 case SENSOR_WATTS:
449                         printf("%.2f W", s->value / 1000000.0);
450                         break;
451                 case SENSOR_AMPS:
452                         printf("%.2f A", s->value / 1000000.0);
453                         break;
454                 case SENSOR_WATTHOUR:
455                         printf("%.2f Wh", s->value / 1000000.0);
456                         break;
457                 case SENSOR_AMPHOUR:
458                         printf("%.2f Ah", s->value / 1000000.0);
459                         break;
460                 case SENSOR_INDICATOR:
461                         printf("%s", s->value ? "On" : "Off");
462                         break;
463                 case SENSOR_FREQ:
464                         printf("%jd Hz", (intmax_t)s->value);
465                         break;
466                 case SENSOR_ECC:
467                 case SENSOR_INTEGER:
468                         printf("%jd", (intmax_t)s->value);
469                         break;
470                 case SENSOR_PERCENT:
471                         printf("%.2f%%", s->value / 1000.0);
472                         break;
473                 case SENSOR_LUX:
474                         printf("%.2f lx", s->value / 1000000.0);
475                         break;
476                 case SENSOR_DRIVE:
477                 {
478                         const char *name;
479
480                         switch (s->value) {
481                         case SENSOR_DRIVE_EMPTY:
482                                 name = "empty";
483                                 break;
484                         case SENSOR_DRIVE_READY:
485                                 name = "ready";
486                                 break;
487                         case SENSOR_DRIVE_POWERUP:
488                                 name = "powering up";
489                                 break;
490                         case SENSOR_DRIVE_ONLINE:
491                                 name = "online";
492                                 break;
493                         case SENSOR_DRIVE_IDLE:
494                                 name = "idle";
495                                 break;
496                         case SENSOR_DRIVE_ACTIVE:
497                                 name = "active";
498                                 break;
499                         case SENSOR_DRIVE_REBUILD:
500                                 name = "rebuilding";
501                                 break;
502                         case SENSOR_DRIVE_POWERDOWN:
503                                 name = "powering down";
504                                 break;
505                         case SENSOR_DRIVE_FAIL:
506                                 name = "failed";
507                                 break;
508                         case SENSOR_DRIVE_PFAIL:
509                                 name = "degraded";
510                                 break;
511                         default:
512                                 name = "unknown";
513                                 break;
514                         }
515                         printf("%s", name);
516                         break;
517                 }
518                 case SENSOR_TIMEDELTA:
519                         printf("%.6f secs", s->value / 1000000000.0);
520                         break;
521                 default:
522                         printf("unknown");
523                 }
524         }
525
526         if (s->desc[0] != '\0')
527                 printf(" (%s)", s->desc);
528
529         switch (s->status) {
530         case SENSOR_S_UNSPEC:
531                 break;
532         case SENSOR_S_OK:
533                 printf(", OK");
534                 break;
535         case SENSOR_S_WARN:
536                 printf(", WARNING");
537                 break;
538         case SENSOR_S_CRIT:
539                 printf(", CRITICAL");
540                 break;
541         case SENSOR_S_UNKNOWN:
542                 printf(", UNKNOWN");
543                 break;
544         }
545
546         if (s->tv.tv_sec) {
547                 time_t t = s->tv.tv_sec;
548                 char ct[26];
549
550                 ctime_r(&t, ct);
551                 ct[19] = '\0';
552                 printf(", %s.%03ld", ct, s->tv.tv_usec / 1000);
553         }
554
555         return (0);
556 }
557
558 #ifdef __x86_64__
559 static int
560 S_efi_map(size_t l2, void *p)
561 {
562         struct efi_map_header *efihdr;
563         struct efi_md *map;
564         const char *type;
565         size_t efisz;
566         int ndesc, i;
567
568         static const char *types[] = {
569                 "Reserved",
570                 "LoaderCode",
571                 "LoaderData",
572                 "BootServicesCode",
573                 "BootServicesData",
574                 "RuntimeServicesCode",
575                 "RuntimeServicesData",
576                 "ConventionalMemory",
577                 "UnusableMemory",
578                 "ACPIReclaimMemory",
579                 "ACPIMemoryNVS",
580                 "MemoryMappedIO",
581                 "MemoryMappedIOPortSpace",
582                 "PalCode"
583         };
584
585         /*
586          * Memory map data provided by UEFI via the GetMemoryMap
587          * Boot Services API.
588          */
589         if (l2 < sizeof(*efihdr)) {
590                 warnx("S_efi_map length less than header");
591                 return (1);
592         }
593         efihdr = p;
594         efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
595         map = (struct efi_md *)((uint8_t *)efihdr + efisz);
596
597         if (efihdr->descriptor_size == 0)
598                 return (0);
599         if (l2 != efisz + efihdr->memory_size) {
600                 warnx("S_efi_map length mismatch %zu vs %zu", l2, efisz +
601                     efihdr->memory_size);
602                 return (1);
603         }
604         ndesc = efihdr->memory_size / efihdr->descriptor_size;
605
606         printf("\n%23s %12s %12s %8s %4s",
607             "Type", "Physical", "Virtual", "#Pages", "Attr");
608
609         for (i = 0; i < ndesc; i++,
610             map = efi_next_descriptor(map, efihdr->descriptor_size)) {
611                 if (map->md_type <= EFI_MD_TYPE_PALCODE)
612                         type = types[map->md_type];
613                 else
614                         type = "<INVALID>";
615                 printf("\n%23s %012lx %12p %08lx ", type, map->md_phys,
616                     map->md_virt, map->md_pages);
617                 if (map->md_attr & EFI_MD_ATTR_UC)
618                         printf("UC ");
619                 if (map->md_attr & EFI_MD_ATTR_WC)
620                         printf("WC ");
621                 if (map->md_attr & EFI_MD_ATTR_WT)
622                         printf("WT ");
623                 if (map->md_attr & EFI_MD_ATTR_WB)
624                         printf("WB ");
625                 if (map->md_attr & EFI_MD_ATTR_UCE)
626                         printf("UCE ");
627                 if (map->md_attr & EFI_MD_ATTR_WP)
628                         printf("WP ");
629                 if (map->md_attr & EFI_MD_ATTR_RP)
630                         printf("RP ");
631                 if (map->md_attr & EFI_MD_ATTR_XP)
632                         printf("XP ");
633                 if (map->md_attr & EFI_MD_ATTR_RT)
634                         printf("RUNTIME");
635         }
636         return (0);
637 }
638 #endif
639
640 static int
641 T_dev_t(size_t l2, void *p)
642 {
643         dev_t *d = (dev_t *)p;
644         if (l2 != sizeof(*d))
645                 err(1, "T_dev_T %zu != %zu", l2, sizeof(*d));
646         if ((int)(*d) != -1) {
647                 if (minor(*d) > 255 || minor(*d) < 0)
648                         printf("{ major = %d, minor = 0x%x }",
649                                 major(*d), minor(*d));
650                 else
651                         printf("{ major = %d, minor = %d }",
652                                 major(*d), minor(*d));
653         }
654         return (0);
655 }
656
657 static void
658 set_T_dev_t(const char *path, void **val, size_t *size)
659 {
660         static struct stat statb;
661
662         if (strcmp(path, "none") && strcmp(path, "off")) {
663                 int rc = stat (path, &statb);
664                 if (rc) {
665                         err(1, "cannot stat %s", path);
666                 }
667
668                 if (!S_ISCHR(statb.st_mode)) {
669                         errx(1, "must specify a device special file.");
670                 }
671         } else {
672                 statb.st_rdev = NODEV;
673         }
674         *val = (char*) &statb.st_rdev;
675         *size = sizeof statb.st_rdev;
676 }
677
678 static int
679 set_IK(const char *str, int *val)
680 {
681         float temp;
682         int len, kelv;
683         const char *p;
684         char *endptr;
685
686         if ((len = strlen(str)) == 0)
687                 return (0);
688         p = &str[len - 1];
689         if (*p == 'C' || *p == 'F') {
690                 temp = strtof(str, &endptr);
691                 if (endptr == str || endptr != p)
692                         return 0;
693                 if (*p == 'F')
694                         temp = (temp - 32) * 5 / 9;
695                 kelv = temp * 10 + 2732;
696         } else {
697                 /*
698                  * I would like to just use, 0 but it would make numbers
699                  * like '023' which were interpreted as decimal before
700                  * suddenly interpreted as octal.
701                  */
702                 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
703                         kelv = (int)strtol(str, &endptr, 0);
704                 else
705                         kelv = (int)strtol(str, &endptr, 10);
706                 if (endptr == str || *endptr != '\0')
707                         return 0;
708         }
709         *val = kelv;
710         return 1;
711 }
712
713 /*
714  * These functions uses a presently undocumented interface to the kernel
715  * to walk the tree and get the type so it can print the value.
716  * This interface is under work and consideration, and should probably
717  * be killed with a big axe by the first person who can find the time.
718  * (be aware though, that the proper interface isn't as obvious as it
719  * may seem, there are various conflicting requirements.
720  */
721
722 static int
723 oidfmt(int *oid, size_t len, char *fmt, u_int *kind)
724 {
725         int qoid[CTL_MAXNAME+2];
726         u_char buf[BUFSIZ];
727         int i;
728         size_t j;
729
730         qoid[0] = 0;
731         qoid[1] = 4;
732         memcpy(qoid + 2, oid, len * sizeof(int));
733
734         j = sizeof(buf);
735         i = sysctl(qoid, len + 2, buf, &j, 0, 0);
736         if (i)
737                 err(1, "sysctl fmt %d %zu %d", i, j, errno);
738
739         if (kind)
740                 *kind = *(u_int *)buf;
741
742         if (fmt)
743                 strcpy(fmt, (char *)(buf + sizeof(u_int)));
744         return 0;
745 }
746
747 /*
748  * This formats and outputs the value of one variable
749  *
750  * Returns zero if anything was actually output.
751  * Returns one if didn't know what to do with this.
752  * Return minus one if we had errors.
753  */
754
755 static int
756 show_var(int *oid, size_t nlen)
757 {
758         u_char buf[BUFSIZ], *val = NULL, *p, *nul;
759         char name[BUFSIZ], *fmt;
760         const char *sep, *spacer;
761         int qoid[CTL_MAXNAME+2];
762         int i;
763         size_t j, len;
764         u_int kind;
765         int (*func)(size_t, void *);
766         int error = 0;
767
768         qoid[0] = 0;
769         memcpy(qoid + 2, oid, nlen * sizeof(int));
770
771         qoid[1] = 1;
772         j = sizeof(name);
773         i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
774         if (i || !j)
775                 err(1, "sysctl name %d %zu %d", i, j, errno);
776
777         if (Nflag) {
778                 printf("%s", name);
779                 return (0);
780         }
781
782         if (eflag)
783                 sep = "=";
784         else
785                 sep = ": ";
786
787         if (dflag) {    /* just print description */
788                 qoid[1] = 5;
789                 j = sizeof(buf);
790                 i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
791                 if (!nflag)
792                         printf("%s%s", name, sep);
793                 printf("%s", buf);
794                 return(0);
795         }
796         /* find an estimate of how much we need for this var */
797         j = 0;
798         i = sysctl(oid, nlen, 0, &j, 0, 0);
799         j += j; /* we want to be sure :-) */
800
801         val = malloc(j + 1);
802         if (val == NULL)
803                 return (1);
804
805         len = j;
806         i = sysctl(oid, nlen, val, &len, 0, 0);
807         if (i || !len) {
808                 error = 1;
809                 goto done;
810         }
811
812         if (bflag) {
813                 fwrite(val, 1, len, stdout);
814                 goto done;
815         }
816
817         val[len] = '\0';
818         fmt = buf;
819         oidfmt(oid, nlen, fmt, &kind);
820         p = val;
821         switch (*fmt) {
822         case 'A':
823                 if (!nflag)
824                         printf("%s%s", name, sep);
825                 nul = memchr(p, '\0', len);
826                 fwrite(p, nul == NULL ? (int)len : nul - p, 1, stdout);
827                 return (0);
828                 
829         case 'C':
830                 if (!nflag)
831                         printf("%s%s", name, sep);
832                 fmt++;
833                 spacer = "";
834                 while (len >= sizeof(char)) {
835                         if(*fmt == 'U')
836                                 printf("%s%hhu", spacer, *(unsigned char *)p);
837                         else
838                                 printf("%s%hhd", spacer, *(char *)p);
839                         spacer = " ";
840                         len -= sizeof(char);
841                         p += sizeof(char);
842                 }
843                 goto done;
844
845         case 'I':
846                 if (!nflag)
847                         printf("%s%s", name, sep);
848                 fmt++;
849                 spacer = "";
850                 while (len >= sizeof(int)) {
851                         if(*fmt == 'U')
852                                 printf("%s%u", spacer, *(unsigned int *)p);
853                         else if (*fmt == 'K' && *(int *)p >= 0)
854                                 printf("%s%.1fC", spacer, (*(int *)p - 2732) / 10.0);
855                         else
856                                 printf("%s%d", spacer, *(int *)p);
857                         spacer = " ";
858                         len -= sizeof(int);
859                         p += sizeof(int);
860                 }
861                 goto done;
862
863         case 'L':
864                 if (!nflag)
865                         printf("%s%s", name, sep);
866                 fmt++;
867                 spacer = "";
868                 while (len >= sizeof(long)) {
869                         if(*fmt == 'U')
870                                 printf("%s%lu", spacer, *(unsigned long *)p);
871                         else
872                                 printf("%s%ld", spacer, *(long *)p);
873                         spacer = " ";
874                         len -= sizeof(long);
875                         p += sizeof(long);
876                 }
877                 goto done;
878
879         case 'P':
880                 if (!nflag)
881                         printf("%s%s", name, sep);
882                 printf("%p", *(void **)p);
883                 goto done;
884
885         case 'Q':
886                 if (!nflag)
887                         printf("%s%s", name, sep);
888                 fmt++;
889                 spacer = "";
890                 while (len >= sizeof(quad_t)) {
891                         if(*fmt == 'U') {
892                                 printf("%s%ju",
893                                        spacer, (uintmax_t)*(u_quad_t *)p);
894                         } else {
895                                 printf("%s%jd",
896                                        spacer, (intmax_t)*(quad_t *)p);
897                         }
898                         spacer = " ";
899                         len -= sizeof(int64_t);
900                         p += sizeof(int64_t);
901                 }
902                 goto done;
903
904         case 'T':
905         case 'S':
906                 if (fmt[0] == 'S' && fmt[1] != ',') {
907                         if (!nflag)
908                                 printf("%s%s", name, sep);
909                         fmt++;
910                         spacer = "";
911                         while (len >= sizeof(short)) {
912                                 if(*fmt == 'U')
913                                         printf("%s%hu", spacer,
914                                             *(unsigned short *)p);
915                                 else
916                                         printf("%s%hd", spacer, *(short *)p);
917                                 spacer = " ";
918                                 len -= sizeof(short);
919                                 p += sizeof(short);
920                         }
921                         goto done;
922                 }
923                         
924                 if (!oflag && !xflag) {
925                         i = 0;
926                         if (strcmp(fmt, "S,clockinfo") == 0)
927                                 func = S_clockinfo;
928                         else if (strcmp(fmt, "S,timespec") == 0)
929                                 func = S_timespec;
930                         else if (strcmp(fmt, "S,timeval") == 0)
931                                 func = S_timeval;
932                         else if (strcmp(fmt, "S,loadavg") == 0)
933                                 func = S_loadavg;
934                         else if (strcmp(fmt, "S,sensor") == 0)
935                                 func = S_sensor;
936 #ifdef __x86_64__
937                         else if (strcmp(fmt, "S,efi_map_header") == 0)
938                                 func = S_efi_map;
939 #endif
940                         else if (strcmp(fmt, "T,dev_t") == 0)
941                                 func = T_dev_t;
942                         else if (strcmp(fmt, "T,udev_t") == 0)
943                                 func = T_dev_t;
944                         else
945                                 func = NULL;
946                         if (func) {
947                                 if (!nflag)
948                                         printf("%s%s", name, sep);
949                                 error = (*func)(len, p);
950                                 goto done;
951                         }
952                 }
953                 /* FALL THROUGH */
954         default:
955                 if (!oflag && !xflag) {
956                         error = 1;
957                         goto done;
958                 }
959                 if (!nflag)
960                         printf("%s%s", name, sep);
961                 printf("Format:%s Length:%zu Dump:0x", fmt, len);
962                 while (len-- && (xflag || p < val + 16))
963                         printf("%02x", *p++);
964                 if (!xflag && len > 16)
965                         printf("...");
966                 goto done;
967         }
968
969 done:
970         if (val != NULL)
971                 free(val);
972         return (error);
973 }
974
975 static int
976 sysctl_all(int *oid, size_t len)
977 {
978         int name1[22], name2[22];
979         int retval;
980         size_t i, l1, l2;
981
982         name1[0] = 0;
983         name1[1] = 2;
984         l1 = 2;
985         if (len) {
986                 memcpy(name1+2, oid, len * sizeof(int));
987                 l1 += len;
988         } else {
989                 name1[2] = 1;
990                 l1++;
991         }
992         for (;;) {
993                 l2 = sizeof(name2);
994                 retval = sysctl(name1, l1, name2, &l2, 0, 0);
995                 if (retval < 0) {
996                         if (errno == ENOENT)
997                                 return 0;
998                         else
999                                 err(1, "sysctl(getnext) %d %zu", retval, l2);
1000                 }
1001
1002                 l2 /= sizeof(int);
1003
1004                 if (l2 < len)
1005                         return 0;
1006
1007                 for (i = 0; i < len; i++)
1008                         if (name2[i] != oid[i])
1009                                 return 0;
1010
1011                 retval = show_var(name2, l2);
1012                 if (retval == 0 && !bflag)
1013                         putchar('\n');
1014
1015                 memcpy(name1+2, name2, l2 * sizeof(int));
1016                 l1 = 2 + l2;
1017         }
1018 }