8bffb6fe518ff87b9bd34cbbd4dedaa5ba25541b
[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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)from: sysctl.c   8.1 (Berkeley) 6/6/93
35  * $FreeBSD: src/sbin/sysctl/sysctl.c,v 1.25.2.11 2003/05/01 22:48:08 trhodes Exp $
36  * $DragonFly: src/sbin/sysctl/sysctl.c,v 1.10 2005/01/18 03:13:52 cpressey Exp $
37  */
38
39 #ifdef __i386__
40 #include <sys/diskslice.h>      /* used for bootdev parsing */
41 #include <sys/reboot.h>         /* used for bootdev parsing */
42 #endif
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <sys/sysctl.h>
46 #include <sys/resource.h>
47 #include <sys/param.h>
48
49 #include <machine/inttypes.h>
50
51 #include <ctype.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58
59 static int      aflag, bflag, dflag, eflag, Nflag, nflag, oflag, xflag;
60
61 static int      oidfmt(int *, size_t, char *, u_int *);
62 static void     parse(const char *);
63 static int      show_var(int *, size_t);
64 static int      sysctl_all(int *, size_t);
65 static void     set_T_dev_t(const char *, void **, int *);
66
67 static void
68 usage(void)
69 {
70
71         fprintf(stderr, "%s\n%s\n",
72             "usage: sysctl [-bdeNnox] variable[=value] ...",
73             "       sysctl [-bdeNnox] -a");
74         exit(1);
75 }
76
77 int
78 main(int argc, char **argv)
79 {
80         int ch;
81         setbuf(stdout,0);
82         setbuf(stderr,0);
83
84         while ((ch = getopt(argc, argv, "AabdeNnowxX")) != -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 'N':
103                         Nflag = 1;
104                         break;
105                 case 'n':
106                         nflag = 1;
107                         break;
108                 case 'o':
109                         oflag = 1;
110                         break;
111                 case 'w':
112                         /* compatibility */
113                         /* ignored */
114                         break;
115                 case 'X':
116                         /* compatibility */
117                         aflag = xflag = 1;
118                         break;
119                 case 'x':
120                         xflag = 1;
121                         break;
122                 default:
123                         usage();
124                 }
125         }
126         argc -= optind;
127         argv += optind;
128
129         if (Nflag && nflag)
130                 usage();
131         if (aflag && argc == 0)
132                 exit(sysctl_all(0, 0));
133         if (argc == 0)
134                 usage();
135         while (argc-- > 0)
136                 parse(*argv++);
137         exit(0);
138 }
139
140 /*
141  * Parse a name into a MIB entry.
142  * Lookup and print out the MIB entry if it exists.
143  * Set a new value if requested.
144  */
145 static void
146 parse(const char *string)
147 {
148         size_t len;
149         int i, j;
150         void *newval = NULL;
151         int intval;
152         unsigned int uintval;
153         long longval;
154         unsigned long ulongval;
155         size_t newsize = 0;
156         quad_t quadval;
157         int mib[CTL_MAXNAME];
158         char *cp, fmt[BUFSIZ];
159         const char *name;
160         char *name_allocated = NULL;
161         u_int kind;
162
163         if ((cp = strchr(string, '=')) != NULL) {
164                 if ((name_allocated = malloc(cp - string + 1)) == NULL)
165                         err(1, "malloc failed");
166                 strlcpy(name_allocated, string, cp - string + 1);
167                 name = name_allocated;
168                 
169                 while (isspace(*++cp))
170                         ;
171
172                 newval = cp;
173                 newsize = strlen(cp);
174         } else {
175                 name = string;
176         }
177
178         len = CTL_MAXNAME;
179         if (sysctlnametomib(name, mib, &len) < 0) {
180                 if (errno == ENOENT) {
181                         errx(1, "unknown oid '%s'", name);
182                 } else {
183                         err(1, "sysctlnametomib(\"%s\")", name);
184                 }
185         }
186
187         if (oidfmt(mib, len, fmt, &kind))
188                 err(1, "couldn't find format of oid '%s'", name);
189
190         if (newval == NULL) {
191                 if ((kind & CTLTYPE) == CTLTYPE_NODE) {
192                         sysctl_all(mib, len);
193                 } else {
194                         i = show_var(mib, len);
195                         if (!i && !bflag)
196                                 putchar('\n');
197                 }
198         } else {
199                 if ((kind & CTLTYPE) == CTLTYPE_NODE)
200                         errx(1, "oid '%s' isn't a leaf node", name);
201
202                 if (!(kind&CTLFLAG_WR))
203                         errx(1, "oid '%s' is read only", name);
204         
205                 switch (kind & CTLTYPE) {
206                         case CTLTYPE_INT:
207                                 intval = (int) strtol(newval, NULL, 0);
208                                 newval = &intval;
209                                 newsize = sizeof(intval);
210                                 break;
211                         case CTLTYPE_UINT:
212                                 uintval = (int) strtoul(newval, NULL, 0);
213                                 newval = &uintval;
214                                 newsize = sizeof uintval;
215                                 break;
216                         case CTLTYPE_LONG:
217                                 longval = strtol(newval, NULL, 0);
218                                 newval = &longval;
219                                 newsize = sizeof longval;
220                                 break;
221                         case CTLTYPE_ULONG:
222                                 ulongval = strtoul(newval, NULL, 0);
223                                 newval = &ulongval;
224                                 newsize = sizeof ulongval;
225                                 break;
226                         case CTLTYPE_STRING:
227                                 break;
228                         case CTLTYPE_QUAD:
229                                 sscanf(newval, "%qd", &quadval);
230                                 newval = &quadval;
231                                 newsize = sizeof(quadval);
232                                 break;
233                         case CTLTYPE_OPAQUE:
234                                 if (strcmp(fmt, "T,dev_t") == 0) {
235                                         set_T_dev_t ((char*)newval, &newval, &newsize);
236                                         break;
237                                 }
238                                 /* FALLTHROUGH */
239                         default:
240                                 errx(1, "oid '%s' is type %d,"
241                                         " cannot set that", name,
242                                         kind & CTLTYPE);
243                 }
244
245                 i = show_var(mib, len);
246                 if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
247                         if (!i && !bflag)
248                                 putchar('\n');
249                         switch (errno) {
250                         case EOPNOTSUPP:
251                                 errx(1, "%s: value is not available", 
252                                         string);
253                         case ENOTDIR:
254                                 errx(1, "%s: specification is incomplete", 
255                                         string);
256                         case ENOMEM:
257                                 errx(1, "%s: type is unknown to this program", 
258                                         string);
259                         default:
260                                 warn("%s", string);
261                                 return;
262                         }
263                 }
264                 if (!bflag)
265                         printf(" -> ");
266                 i = nflag;
267                 nflag = 1;
268                 j = show_var(mib, len);
269                 if (!j && !bflag)
270                         putchar('\n');
271                 nflag = i;
272         }
273
274         if (name_allocated != NULL)
275                 free(name_allocated);
276 }
277
278 /* These functions will dump out various interesting structures. */
279
280 static int
281 S_clockinfo(int l2, void *p)
282 {
283         struct clockinfo *ci = (struct clockinfo*)p;
284         if (l2 != sizeof(*ci))
285                 err(1, "S_clockinfo %d != %d", l2, sizeof(*ci));
286         printf("{ hz = %d, tick = %d, tickadj = %d, profhz = %d, stathz = %d }",
287                 ci->hz, ci->tick, ci->tickadj, ci->profhz, ci->stathz);
288         return (0);
289 }
290
291 static int
292 S_loadavg(int l2, void *p)
293 {
294         struct loadavg *tv = (struct loadavg*)p;
295
296         if (l2 != sizeof(*tv))
297                 err(1, "S_loadavg %d != %d", l2, sizeof(*tv));
298
299         printf("{ %.2f %.2f %.2f }",
300                 (double)tv->ldavg[0]/(double)tv->fscale,
301                 (double)tv->ldavg[1]/(double)tv->fscale,
302                 (double)tv->ldavg[2]/(double)tv->fscale);
303         return (0);
304 }
305
306 static int
307 S_timeval(int l2, void *p)
308 {
309         struct timeval *tv = (struct timeval*)p;
310         time_t tv_sec;
311         char *p1, *p2;
312
313         if (l2 != sizeof(*tv))
314                 err(1, "S_timeval %d != %d", l2, sizeof(*tv));
315         printf("{ sec = %ld, usec = %ld } ",
316                 tv->tv_sec, tv->tv_usec);
317         tv_sec = tv->tv_sec;
318         p1 = strdup(ctime(&tv_sec));
319         for (p2=p1; *p2 ; p2++)
320                 if (*p2 == '\n')
321                         *p2 = '\0';
322         fputs(p1, stdout);
323         return (0);
324 }
325
326 static int
327 T_dev_t(int l2, void *p)
328 {
329         dev_t *d = (dev_t *)p;
330         if (l2 != sizeof(*d))
331                 err(1, "T_dev_T %d != %d", l2, sizeof(*d));
332         if ((int)(*d) != -1) {
333                 if (minor(*d) > 255 || minor(*d) < 0)
334                         printf("{ major = %d, minor = 0x%x }",
335                                 major(*d), minor(*d));
336                 else
337                         printf("{ major = %d, minor = %d }",
338                                 major(*d), minor(*d));
339         }
340         return (0);
341 }
342
343 static void
344 set_T_dev_t(const char *path, void **val, int *size)
345 {
346         static struct stat statb;
347
348         if (strcmp(path, "none") && strcmp(path, "off")) {
349                 int rc = stat (path, &statb);
350                 if (rc) {
351                         err(1, "cannot stat %s", path);
352                 }
353
354                 if (!S_ISCHR(statb.st_mode)) {
355                         errx(1, "must specify a device special file.");
356                 }
357         } else {
358                 statb.st_rdev = NODEV;
359         }
360         *val = (char*) &statb.st_rdev;
361         *size = sizeof statb.st_rdev;
362 }
363
364 /*
365  * These functions uses a presently undocumented interface to the kernel
366  * to walk the tree and get the type so it can print the value.
367  * This interface is under work and consideration, and should probably
368  * be killed with a big axe by the first person who can find the time.
369  * (be aware though, that the proper interface isn't as obvious as it
370  * may seem, there are various conflicting requirements.
371  */
372
373 static int
374 oidfmt(int *oid, size_t len, char *fmt, u_int *kind)
375 {
376         int qoid[CTL_MAXNAME+2];
377         u_char buf[BUFSIZ];
378         int i;
379         size_t j;
380
381         qoid[0] = 0;
382         qoid[1] = 4;
383         memcpy(qoid + 2, oid, len * sizeof(int));
384
385         j = sizeof(buf);
386         i = sysctl(qoid, len + 2, buf, &j, 0, 0);
387         if (i)
388                 err(1, "sysctl fmt %d %d %d", i, j, errno);
389
390         if (kind)
391                 *kind = *(u_int *)buf;
392
393         if (fmt)
394                 strcpy(fmt, (char *)(buf + sizeof(u_int)));
395         return 0;
396 }
397
398 #ifdef __i386__
399 /*
400  * Code to map a bootdev major number into a suitable device name.
401  * Major numbers are mapped into names as in boot2.c
402  */
403 struct _foo {
404         int majdev;
405         const char *name;
406 } maj2name[] = {
407         { 30,   "ad" },
408         { 0,    "wd" },
409         { 1,    "wfd" },
410         { 2,    "fd" },
411         { 4,    "da" },
412         { -1,   NULL }  /* terminator */
413 };
414
415 static int
416 machdep_bootdev(u_long value)
417 {
418         int majdev, unit, slice, part;
419         struct _foo *p;
420
421         if ((value & B_MAGICMASK) != B_DEVMAGIC) {
422                 printf("invalid (0x%08lx)", value);
423                 return 0;
424         }
425         majdev = B_TYPE(value);
426         unit = B_UNIT(value);
427         slice = B_SLICE(value);
428         part = B_PARTITION(value);
429         if (majdev == 2) {      /* floppy, as known to the boot block... */
430                 printf("/dev/fd%d", unit);
431                 return 0;
432         }
433         for (p = maj2name; p->name != NULL && p->majdev != majdev ; p++) ;
434         if (p->name != NULL) {  /* found */
435                 if (slice == WHOLE_DISK_SLICE)
436                         printf("/dev/%s%d%c", p->name, unit, part);
437                 else
438                         printf("/dev/%s%ds%d%c",
439                             p->name, unit, slice - BASE_SLICE + 1, part + 'a');
440         } else
441                 printf("unknown (major %d unit %d slice %d part %d)",
442                         majdev, unit, slice, part);
443         return 0;
444 }
445 #endif
446
447 /*
448  * This formats and outputs the value of one variable
449  *
450  * Returns zero if anything was actually output.
451  * Returns one if didn't know what to do with this.
452  * Return minus one if we had errors.
453  */
454
455 static int
456 show_var(int *oid, size_t nlen)
457 {
458         u_char buf[BUFSIZ], *val, *p;
459         char name[BUFSIZ], *fmt;
460         const char *sep, *spacer;
461         int qoid[CTL_MAXNAME+2];
462         int i;
463         size_t j, len;
464         u_int kind;
465         int (*func)(int, void *);
466
467         qoid[0] = 0;
468         memcpy(qoid + 2, oid, nlen * sizeof(int));
469
470         qoid[1] = 1;
471         j = sizeof(name);
472         i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
473         if (i || !j)
474                 err(1, "sysctl name %d %d %d", i, j, errno);
475
476         if (Nflag) {
477                 printf("%s", name);
478                 return (0);
479         }
480
481         if (eflag)
482                 sep = "=";
483         else
484                 sep = ": ";
485
486         if (dflag) {    /* just print description */
487                 qoid[1] = 5;
488                 j = sizeof(buf);
489                 i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
490                 if (!nflag)
491                         printf("%s%s", name, sep);
492                 printf("%s", buf);
493                 return(0);
494         }
495         /* find an estimate of how much we need for this var */
496         j = 0;
497         i = sysctl(oid, nlen, 0, &j, 0, 0);
498         j += j; /* we want to be sure :-) */
499
500         val = alloca(j + 1);
501         len = j;
502         i = sysctl(oid, nlen, val, &len, 0, 0);
503         if (i || !len)
504                 return (1);
505
506         if (bflag) {
507                 fwrite(val, 1, len, stdout);
508                 return (0);
509         }
510
511         val[len] = '\0';
512         fmt = buf;
513         oidfmt(oid, nlen, fmt, &kind);
514         p = val;
515         switch (*fmt) {
516         case 'A':
517                 if (!nflag)
518                         printf("%s%s", name, sep);
519                 for (j = 0; j < len; j++) {
520                         if (p[j] == '\0')
521                                 break;
522                 }
523                 fwrite(p, j, 1, stdout);
524                 return (0);
525                 
526         case 'I':
527                 if (!nflag)
528                         printf("%s%s", name, sep);
529                 fmt++;
530                 spacer = "";
531                 while (len >= sizeof(int)) {
532                         if(*fmt == 'U')
533                                 printf("%s%u", spacer, *(unsigned int *)p);
534                         else
535                                 printf("%s%d", spacer, *(int *)p);
536                         spacer = " ";
537                         len -= sizeof(int);
538                         p += sizeof(int);
539                 }
540                 return (0);
541
542         case 'L':
543                 if (!nflag)
544                         printf("%s%s", name, sep);
545                 fmt++;
546 #ifdef __i386__
547                 if (!strcmp(name, "machdep.guessed_bootdev"))
548                         return machdep_bootdev(*(unsigned long *)p);
549 #endif
550                 spacer = "";
551                 while (len >= sizeof(long)) {
552                         if(*fmt == 'U')
553                                 printf("%s%lu", spacer, *(unsigned long *)p);
554                         else
555                                 printf("%s%ld", spacer, *(long *)p);
556                         spacer = " ";
557                         len -= sizeof(long);
558                         p += sizeof(long);
559                 }
560                 return (0);
561
562         case 'P':
563                 if (!nflag)
564                         printf("%s%s", name, sep);
565                 printf("%p", *(void **)p);
566                 return (0);
567
568         case 'Q':
569                 if (!nflag)
570                         printf("%s%s", name, sep);
571                 fmt++;
572                 spacer = "";
573                 while (len >= sizeof(int64_t)) {
574                         if(*fmt == 'U')
575                                 printf("%s%"PRIu64, spacer, *(uint64_t *)p);
576                         else
577                                 printf("%s%"PRId64, spacer, *(int64_t *)p);
578                         spacer = " ";
579                         len -= sizeof(int64_t);
580                         p += sizeof(int64_t);
581                 }
582                 return (0);
583
584         case 'T':
585         case 'S':
586                 if (!oflag && !xflag) {
587                         i = 0;
588                         if (strcmp(fmt, "S,clockinfo") == 0)
589                                 func = S_clockinfo;
590                         else if (strcmp(fmt, "S,timeval") == 0)
591                                 func = S_timeval;
592                         else if (strcmp(fmt, "S,loadavg") == 0)
593                                 func = S_loadavg;
594                         else if (strcmp(fmt, "T,dev_t") == 0)
595                                 func = T_dev_t;
596                         else
597                                 func = NULL;
598                         if (func) {
599                                 if (!nflag)
600                                         printf("%s%s", name, sep);
601                                 return ((*func)(len, p));
602                         }
603                 }
604                 /* FALL THROUGH */
605         default:
606                 if (!oflag && !xflag)
607                         return (1);
608                 if (!nflag)
609                         printf("%s%s", name, sep);
610                 printf("Format:%s Length:%d Dump:0x", fmt, len);
611                 while (len-- && (xflag || p < val + 16))
612                         printf("%02x", *p++);
613                 if (!xflag && len > 16)
614                         printf("...");
615                 return (0);
616         }
617         return (1);
618 }
619
620 static int
621 sysctl_all(int *oid, size_t len)
622 {
623         int name1[22], name2[22];
624         int retval;
625         size_t i, l1, l2;
626
627         name1[0] = 0;
628         name1[1] = 2;
629         l1 = 2;
630         if (len) {
631                 memcpy(name1+2, oid, len * sizeof(int));
632                 l1 += len;
633         } else {
634                 name1[2] = 1;
635                 l1++;
636         }
637         for (;;) {
638                 l2 = sizeof(name2);
639                 retval = sysctl(name1, l1, name2, &l2, 0, 0);
640                 if (retval < 0) {
641                         if (errno == ENOENT)
642                                 return 0;
643                         else
644                                 err(1, "sysctl(getnext) %d %d", retval, l2);
645                 }
646
647                 l2 /= sizeof(int);
648
649                 if (l2 < len)
650                         return 0;
651
652                 for (i = 0; i < len; i++)
653                         if (name2[i] != oid[i])
654                                 return 0;
655
656                 retval = show_var(name2, l2);
657                 if (retval == 0 && !bflag)
658                         putchar('\n');
659
660                 memcpy(name1+2, name2, l2 * sizeof(int));
661                 l1 = 2 + l2;
662         }
663 }