xref: /freebsd/sbin/sysctl/sysctl.c (revision ef5d438ed4bc17ad7ece3e40fe4d1f9baf3aadf7)
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 
34 #ifndef lint
35 static char copyright[] =
36 "@(#) Copyright (c) 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 /*static char sccsid[] = "From: @(#)sysctl.c	8.1 (Berkeley) 6/6/93"; */
42 static const char rcsid[] =
43 	"$Id: sysctl.c,v 1.8 1995/11/17 16:28:42 phk Exp $";
44 #endif /* not lint */
45 
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <sys/sysctl.h>
49 #include <sys/resource.h>
50 
51 #include <errno.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <err.h>
57 
58 static int	Aflag, aflag, nflag, wflag, Xflag, bflag;
59 
60 static int	oidfmt(int *, int, char *, u_int *);
61 static void	parse(char *);
62 static int	show_var(int *, int);
63 static int	sysctl_all (int *oid, int len);
64 static int	name2oid(char *, int *);
65 
66 static void
67 usage(void)
68 {
69 
70 	(void)fprintf(stderr, "usage:\n%s",
71 	    "\tsysctl [-bnX] variable ...\n"
72 	    "\tsysctl [-bnX] -w variable=value ...\n"
73 	    "\tsysctl [-bnX] -a\n"
74 	    "\tsysctl [-bnX] -A\n"
75 		);
76 	exit(1);
77 }
78 
79 int
80 main(int argc, char **argv)
81 {
82 	extern char *optarg;
83 	extern int optind;
84 	int ch;
85 	setbuf(stdout,0);
86 	setbuf(stderr,0);
87 
88 	while ((ch = getopt(argc, argv, "AabnwX")) != EOF) {
89 		switch (ch) {
90 		case 'A': Aflag = 1; break;
91 		case 'a': aflag = 1; break;
92 		case 'b': bflag = 1; break;
93 		case 'n': nflag = 1; break;
94 		case 'w': wflag = 1; break;
95 		case 'X': Xflag = Aflag = 1; break;
96 		default: usage();
97 		}
98 	}
99 	argc -= optind;
100 	argv += optind;
101 
102 	if (Aflag || aflag)
103 		exit (sysctl_all(0, 0));
104 	if (argc == 0)
105 		usage();
106 	while (argc-- > 0)
107 		parse(*argv++);
108 	exit(0);
109 }
110 
111 /*
112  * Parse a name into a MIB entry.
113  * Lookup and print out the MIB entry if it exists.
114  * Set a new value if requested.
115  */
116 static void
117 parse(char *string)
118 {
119 	int len, i, j;
120 	void *newval = 0;
121 	int intval, newsize = 0;
122 	quad_t quadval;
123 	int mib[CTL_MAXNAME];
124 	char *cp, *bufp, buf[BUFSIZ];
125 	u_int kind;
126 
127 	bufp = buf;
128 	snprintf(buf, BUFSIZ, "%s", string);
129 	if ((cp = strchr(string, '=')) != NULL) {
130 		if (!wflag) {
131 			fprintf(stderr, "Must specify -w to set variables\n");
132 			exit(2);
133 		}
134 		*strchr(buf, '=') = '\0';
135 		*cp++ = '\0';
136 		while (isspace(*cp))
137 			cp++;
138 		newval = cp;
139 		newsize = strlen(cp);
140 	}
141 	len = name2oid(bufp, mib);
142 
143 	if (len < 0)
144 		errx(1, "Unknown oid '%s'", bufp);
145 
146 	if (oidfmt(mib, len, 0, &kind))
147 		err(1, "Couldn't find format of oid '%s'", bufp);
148 
149 	if (!wflag) {
150 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
151 			sysctl_all(mib, len);
152 		} else {
153 			i = show_var(mib, len);
154 			if (!i && !bflag)
155 				putchar('\n');
156 		}
157 	} else {
158 		if ((kind & CTLTYPE) == CTLTYPE_NODE)
159 			errx(1, "oid '%s' isn't a leaf node", bufp);
160 
161 		if (!(kind&CTLFLAG_WR))
162 			errx(1, "oid '%s' is read only", bufp);
163 
164 		switch (kind & CTLTYPE) {
165 			case CTLTYPE_INT:
166 				intval = atoi(newval);
167 				newval = &intval;
168 				newsize = sizeof intval;
169 				break;
170 				break;
171 			case CTLTYPE_STRING:
172 				break;
173 			case CTLTYPE_QUAD:
174 				break;
175 				sscanf(newval, "%qd", &quadval);
176 				newval = &quadval;
177 				newsize = sizeof quadval;
178 				break;
179 			default:
180 				errx(1, "oid '%s' is type %d,"
181 					" cannot set that", bufp);
182 		}
183 
184 		i = show_var(mib, len);
185 		if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
186 			if (!i && !bflag)
187 				putchar('\n');
188 			switch (errno) {
189 			case EOPNOTSUPP:
190 				errx(1, "%s: value is not available\n",
191 					string);
192 			case ENOTDIR:
193 				errx(1, "%s: specification is incomplete\n",
194 					string);
195 			case ENOMEM:
196 				errx(1, "%s: type is unknown to this program\n",
197 					string);
198 			default:
199 				perror(string);
200 				return;
201 			}
202 		}
203 		if (!bflag)
204 			printf(" -> ");
205 		i = nflag;
206 		nflag = 1;
207 		j = show_var(mib, len);
208 		if (!j && !bflag)
209 			putchar('\n');
210 		nflag = i;
211 	}
212 }
213 
214 /* These functions will dump out various interesting structures. */
215 
216 static int
217 S_clockinfo(int l2, void *p)
218 {
219 	struct clockinfo *ci = (struct clockinfo*)p;
220 	if (l2 != sizeof *ci)
221 		err(-1, "S_clockinfo %d != %d", l2, sizeof *ci);
222 	printf("{ hz = %d, tick = %d, profhz = %d, stathz = %d }",
223 		ci->hz, ci->tick, ci->profhz, ci->stathz);
224 	return (0);
225 }
226 
227 static int
228 S_loadavg(int l2, void *p)
229 {
230 	struct loadavg *tv = (struct loadavg*)p;
231 
232 	if (l2 != sizeof *tv)
233 		err(-1, "S_loadavg %d != %d", l2, sizeof *tv);
234 
235 	printf("{ %.2f %.2f %.2f }",
236 		(double)tv->ldavg[0]/(double)tv->fscale,
237 		(double)tv->ldavg[1]/(double)tv->fscale,
238 		(double)tv->ldavg[2]/(double)tv->fscale);
239 	return (0);
240 }
241 
242 static int
243 S_timeval(int l2, void *p)
244 {
245 	struct timeval *tv = (struct timeval*)p;
246 	char *p1, *p2;
247 
248 	if (l2 != sizeof *tv)
249 		err(-1, "S_timeval %d != %d", l2, sizeof *tv);
250 	printf("{ sec = %ld, usec = %ld } ",
251 		tv->tv_sec, tv->tv_usec);
252 	p1 = strdup(ctime(&tv->tv_sec));
253 	for (p2=p1; *p2 ; p2++)
254 		if (*p2 == '\n')
255 			*p2 = '\0';
256 	fputs(p1, stdout);
257 	return (0);
258 }
259 
260 static int
261 T_dev_t(int l2, void *p)
262 {
263 	dev_t *d = (dev_t *)p;
264 	if (l2 != sizeof *d)
265 		err(-1, "T_dev_T %d != %d", l2, sizeof *d);
266 	printf("{ major = %d, minor = %d }",
267 		major(*d), minor(*d));
268 	return (0);
269 }
270 
271 /*
272  * These functions uses a presently undocumented interface to the kernel
273  * to walk the tree and get the type so it can print the value.
274  * This interface is under work and consideration, and should probably
275  * be killed with a big axe by the first person who can find the time.
276  * (be aware though, that the proper interface isn't as obvious as it
277  * may seem, there are various conflicting requirements.
278  */
279 
280 static int
281 name2oid(char *name, int *oidp)
282 {
283 	int oid[2];
284 	int i, j;
285 
286 	oid[0] = 0;
287 	oid[1] = 3;
288 
289 	j = CTL_MAXNAME * sizeof (int);
290 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
291 	if (i < 0)
292 		return i;
293 	j /= sizeof (int);
294 	return (j);
295 }
296 
297 static int
298 oidfmt(int *oid, int len, char *fmt, u_int *kind)
299 {
300 	int qoid[CTL_MAXNAME+2];
301 	u_char buf[BUFSIZ];
302 	int i, j;
303 
304 	qoid[0] = 0;
305 	qoid[1] = 4;
306 	memcpy(qoid + 2, oid, len * sizeof(int));
307 
308 	j = sizeof buf;
309 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
310 	if (i)
311 		err(-1, "sysctl fmt %d %d %d", i, j, errno);
312 
313 	if (kind)
314 		*kind = *(u_int *)buf;
315 
316 	if (fmt)
317 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
318 	return 0;
319 }
320 
321 /*
322  * This formats and outputs the value of one variable
323  *
324  * Returns zero if anything was actually output.
325  * Returns one if didn't know what to do with this.
326  * Return minus one if we had errors.
327  */
328 
329 static int
330 show_var(int *oid, int nlen)
331 {
332 	u_char buf[BUFSIZ], *val, *p;
333 	char name[BUFSIZ], *fmt;
334 	int qoid[CTL_MAXNAME+2];
335 	int i, j, len;
336 	u_int kind;
337 	int (*func)(int, void *) = 0;
338 
339 	/* find an estimate of how much we need for this var */
340 	j = 0;
341 	i = sysctl(oid, nlen, 0, &j, 0, 0);
342 	j += j; /* we want to be sure :-) */
343 
344 	val = alloca(j);
345 	len = j;
346 	i = sysctl(oid, nlen, val, &len, 0, 0);
347 	if (i || !len)
348 		return (1);
349 
350 	if (bflag) {
351 		fwrite(val, 1, len, stdout);
352 		return (0);
353 	}
354 
355 	qoid[0] = 0;
356 	qoid[1] = 4;
357 	memcpy(qoid + 2, oid, nlen * sizeof(int));
358 
359 	j = sizeof buf;
360 	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
361 	if (i || !j)
362 		err(-1, "sysctl fmt %d %d %d", i, j, errno);
363 
364 	kind = *(u_int *)buf;
365 
366 	fmt = (char *)(buf + sizeof(u_int));
367 
368 	qoid[1] = 1;
369 	j = sizeof name;
370 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
371 	if (i || !j)
372 		err(-1, "sysctl name %d %d %d", i, j, errno);
373 
374 	p = val;
375 	switch (*fmt) {
376 	case 'A':
377 		if (!nflag)
378 			printf("%s: ", name);
379 		printf("%s", p);
380 		return (0);
381 
382 	case 'I':
383 		if (!nflag)
384 			printf("%s: ", name);
385 		printf("%d", *(int *)p);
386 		return (0);
387 
388 	case 'T':
389 	case 'S':
390 		i = 0;
391 		if (!strcmp(fmt, "S,clockinfo"))	func = S_clockinfo;
392 		else if (!strcmp(fmt, "S,timeval"))	func = S_timeval;
393 		else if (!strcmp(fmt, "S,loadavg"))	func = S_loadavg;
394 		else if (!strcmp(fmt, "T,dev_t"))	func = T_dev_t;
395 		if (func) {
396 			if (!nflag)
397 				printf("%s: ", name);
398 			return ((*func)(len, p));
399 		}
400 		/* FALL THROUGH */
401 	default:
402 		if (!Aflag)
403 			return (1);
404 		if (!nflag)
405 			printf("%s: ", name);
406 		printf("Format:%s Length:%d Dump:0x", fmt, len);
407 		while (len--) {
408 			printf("%02x", *p++);
409 			if (Xflag || p < val+16)
410 				continue;
411 			printf("...");
412 			break;
413 		}
414 		return (0);
415 	}
416 	return (1);
417 }
418 
419 static int
420 sysctl_all (int *oid, int len)
421 {
422 	int name1[22], name2[22];
423 	int i, j, l1, l2;
424 
425 	name1[0] = 0;
426 	name1[1] = 2;
427 	l1 = 2;
428 	if (len) {
429 		memcpy(name1+2, oid, len*sizeof (int));
430 		l1 += len;
431 	} else {
432 		name1[2] = 1;
433 		l1++;
434 	}
435 	while (1) {
436 		l2 = sizeof name2;
437 		j = sysctl(name1, l1, name2, &l2, 0, 0);
438 		if (j < 0)
439 			if (errno == ENOENT)
440 				return 0;
441 			else
442 				err(-1, "sysctl(getnext) %d %d", j, l2);
443 
444 		l2 /= sizeof (int);
445 
446 		if (l2 < len)
447 			return 0;
448 
449 		for (i = 0; i < len; i++)
450 			if (name2[i] != oid[i])
451 				return 0;
452 
453 		i = show_var(name2, l2);
454 		if (!i && !bflag)
455 			putchar('\n');
456 
457 		memcpy(name1+2, name2, l2*sizeof (int));
458 		l1 = 2 + l2;
459 	}
460 }
461