xref: /netbsd-src/usr.bin/systat/main.c (revision ba65fde2d7fefa7d39838fa5fa855e62bd606b5e)
1 /*	$NetBSD: main.c,v 1.47 2012/11/23 03:47:36 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1980, 1992, 1993\
35  The Regents of the University of California.  All rights reserved.");
36 #if 0
37 static char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
38 #endif
39 __RCSID("$NetBSD: main.c,v 1.47 2012/11/23 03:47:36 christos Exp $");
40 #endif /* not lint */
41 
42 #include <sys/param.h>
43 #include <sys/sysctl.h>
44 #include <sys/ioctl.h>
45 
46 #include <ctype.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <limits.h>
50 #include <signal.h>
51 #include <stdarg.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 #include <termios.h>
57 
58 #include "systat.h"
59 #include "extern.h"
60 
61 static int     dellave;
62 
63 kvm_t *kd;
64 char	*memf = NULL;
65 char	*nlistf = NULL;
66 sig_t	sigtstpdfl;
67 double avenrun[3];
68 int     col;
69 int	naptime = 5;
70 int     verbose = 1;                    /* to report kvm read errs */
71 int     hz, stathz, maxslp;
72 char    c;
73 char    *namp;
74 char    hostname[MAXHOSTNAMELEN + 1];
75 WINDOW  *wnd;
76 int     CMDLINE;
77 int     turns = 2;	/* stay how many refresh-turns in 'all' mode? */
78 int     allflag;
79 int     allcounter;
80 sig_atomic_t needsredraw = 0;
81 int	use_sysctl = 1;
82 
83 static	WINDOW *wload;			/* one line window for load average */
84 
85 static void (*sv_stop_handler)(int);
86 
87 static void stop(int);
88 __dead static void usage(void);
89 
90 gid_t egid; /* XXX needed by initiostat() and initkre() */
91 
92 int
93 main(int argc, char **argv)
94 {
95 	int ch;
96 	char errbuf[_POSIX2_LINE_MAX];
97 	const char *all;
98 	struct clockinfo clk;
99 	size_t len;
100 
101 	all = "all";
102 	egid = getegid();
103 	(void)setegid(getgid());
104 
105 	while ((ch = getopt(argc, argv, "M:N:nw:t:")) != -1)
106 		switch(ch) {
107 		case 'M':
108 			memf = optarg;
109 			use_sysctl = 0;
110 			break;
111 		case 'N':
112 			nlistf = optarg;
113 			break;
114 		case 'n':
115 			nflag = !nflag;
116 			break;
117 		case 'w':
118 			if ((naptime = atoi(optarg)) <= 0)
119 				errx(1, "interval <= 0.");
120 			break;
121 		case 't':
122 			if ((turns = atoi(optarg)) <= 0)
123 				errx(1, "turns <= 0.");
124 			break;
125 		case '?':
126 		default:
127 			usage();
128 		}
129 	argc -= optind;
130 	argv += optind;
131 
132 
133 	for ( ; argc > 0; argc--, argv++) {
134 		struct mode *p;
135 		int modefound = 0;
136 
137 		if (isdigit((unsigned char)argv[0][0])) {
138 			naptime = atoi(argv[0]);
139 			if (naptime <= 0)
140 				naptime = 5;
141 			continue;
142 		}
143 
144 		for (p = modes; p->c_name ; p++) {
145 			if (strstr(p->c_name, argv[0]) == p->c_name) {
146 				curmode = p;
147 				modefound++;
148 				break;
149 			}
150 
151 			if (strstr(all, argv[0]) == all) {
152 				allcounter=0;
153 				allflag=1;
154 			}
155 		}
156 
157 
158 		if (!modefound && !allflag)
159 			error("%s: Unknown command.", argv[0]);
160 	}
161 
162 	/*
163 	 * Discard setgid privileges.  If not the running kernel, we toss
164 	 * them away totally so that bad guys can't print interesting stuff
165 	 * from kernel memory, otherwise switch back to kmem for the
166 	 * duration of the kvm_openfiles() call.
167 	 */
168 	if (nlistf != NULL || memf != NULL)
169 		(void)setgid(getgid());
170 	else
171 		(void)setegid(egid);
172 
173 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
174 	if (kd == NULL) {
175 		error("%s", errbuf);
176 		exit(1);
177 	}
178 
179 	/* Get rid of privs for now. */
180 	if (nlistf == NULL && memf == NULL)
181 		(void)setegid(getgid());
182 
183 	signal(SIGINT, die);
184 	signal(SIGQUIT, die);
185 	signal(SIGTERM, die);
186 	sv_stop_handler = signal(SIGTSTP, stop);
187 
188 	/*
189 	 * Initialize display.  Load average appears in a one line
190 	 * window of its own.  Current command's display appears in
191 	 * an overlapping sub-window of stdscr configured by the display
192 	 * routines to minimize update work by curses.
193 	 */
194 	if (initscr() == NULL)
195 	{
196 		warnx("couldn't initialize screen");
197 		exit(0);
198 	}
199 
200 	CMDLINE = LINES - 1;
201 	wnd = (*curmode->c_open)();
202 	if (wnd == NULL) {
203 		warnx("couldn't initialize display");
204 		die(0);
205 	}
206 	wload = newwin(1, 0, 3, 20);
207 	if (wload == NULL) {
208 		warnx("couldn't set up load average window");
209 		die(0);
210 	}
211 	gethostname(hostname, sizeof (hostname));
212 	hostname[sizeof(hostname) - 1] = '\0';
213 
214 	len = sizeof(clk);
215 	if (sysctlbyname("kern.clockrate", &clk, &len, NULL, 0))
216 		error("can't get \"kern.clockrate\": %s", strerror(errno));
217 	hz = clk.hz;
218 	stathz = clk.stathz;
219 
220 	len = sizeof(maxslp);
221 	if (sysctlbyname("vm.maxslp", &maxslp, &len, NULL, 0))
222 		error("can't get \"vm.maxslp\": %s", strerror(errno));
223 
224 	(*curmode->c_init)();
225 	curmode->c_flags |= CF_INIT;
226 	labels();
227 
228 	dellave = 0.0;
229 
230 	display(0);
231 	noecho();
232 	cbreak();
233 	keyboard();
234 	/*NOTREACHED*/
235 }
236 
237 static void
238 usage(void)
239 {
240 	fprintf(stderr, "usage: systat [-n] [-M core] [-N system] [-w wait] "
241 		"[-t turns]\n\t\t[display] [refresh-interval]\n");
242 	exit(1);
243 }
244 
245 
246 void
247 labels(void)
248 {
249 	if (curmode->c_flags & CF_LOADAV) {
250 		mvaddstr(2, 20,
251 		    "/0   /1   /2   /3   /4   /5   /6   /7   /8   /9   /10");
252 		mvaddstr(3, 5, "Load Average");
253 	}
254 	(*curmode->c_label)();
255 #ifdef notdef
256 	mvprintw(21, 25, "CPU usage on %s", hostname);
257 #endif
258 	refresh();
259 }
260 
261 void
262 display(int signo)
263 {
264 	static int skip;
265 	int j;
266 	struct mode *p;
267 	int ms_delay;
268 
269 	if (signo == SIGALRM && skip-- > 0)
270 		/* Don't display on this timeout */
271 		return;
272 
273 	/* Get the load average over the last minute. */
274 	(void)getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0]));
275 	(*curmode->c_fetch)();
276 	if (curmode->c_flags & CF_LOADAV) {
277 		j = 5.0*avenrun[0] + 0.5;
278 		dellave -= avenrun[0];
279 		if (dellave >= 0.0)
280 			c = '<';
281 		else {
282 			c = '>';
283 			dellave = -dellave;
284 		}
285 		if (dellave < 0.1)
286 			c = '|';
287 		dellave = avenrun[0];
288 		wmove(wload, 0, 0);
289 		wclrtoeol(wload);
290 		whline(wload, c, (j > 50) ? 50 : j);
291 		if (j > 50)
292 			wprintw(wload, " %4.1f", avenrun[0]);
293 	}
294 	(*curmode->c_refresh)();
295 	if (curmode->c_flags & CF_LOADAV)
296 		wrefresh(wload);
297 	wrefresh(wnd);
298 	move(CMDLINE, col);
299 	refresh();
300 
301 	if (allflag && signo==SIGALRM) {
302 		if (allcounter >= turns){
303 			p = curmode;
304 			p++;
305 			if (p->c_name == NULL)
306 				p = modes;
307 			switch_mode(p);
308 			allcounter=0;
309 		} else
310 			allcounter++;
311 	}
312 
313 	/* curses timeout() uses VTIME, limited to 255 1/10th secs */
314 	ms_delay = naptime * 1000;
315 	if (ms_delay < 25500) {
316 		timeout(ms_delay);
317 		skip = 0;
318 	} else {
319 		skip = ms_delay / 25500;
320 		timeout(ms_delay / (skip + 1));
321 	}
322 }
323 
324 void
325 redraw(void)
326 {
327 	resizeterm(LINES, COLS);
328 	CMDLINE = LINES - 1;
329 	labels();
330 
331 	display(0);
332 	needsredraw = 0;
333 }
334 
335 static void
336 stop(int signo)
337 {
338 	sigset_t set;
339 
340 	signal(SIGTSTP, sv_stop_handler);
341 	/* unblock SIGTSTP */
342 	sigemptyset(&set);
343 	sigaddset(&set, SIGTSTP);
344 	sigprocmask(SIG_UNBLOCK, &set, NULL);
345 	/* stop ourselves */
346 	kill(0, SIGTSTP);
347 	/* must have been restarted */
348 	signal(SIGTSTP, stop);
349 	needsredraw = signo;
350 }
351 
352 void
353 die(int signo)
354 {
355 	move(CMDLINE, 0);
356 	clrtoeol();
357 	refresh();
358 	endwin();
359 	exit(0);
360 }
361 
362 void
363 error(const char *fmt, ...)
364 {
365 	va_list ap;
366 	char buf[255];
367 	int oy, ox;
368 
369 	va_start(ap, fmt);
370 
371 	if (wnd) {
372 		getyx(stdscr, oy, ox);
373 		(void) vsnprintf(buf, sizeof(buf), fmt, ap);
374 		clrtoeol();
375 		standout();
376 		mvaddstr(CMDLINE, 0, buf);
377 		standend();
378 		move(oy, ox);
379 		refresh();
380 	} else {
381 		(void) vfprintf(stderr, fmt, ap);
382 		fprintf(stderr, "\n");
383 	}
384 	va_end(ap);
385 }
386 
387 void
388 nlisterr(struct nlist name_list[])
389 {
390 	int i, n;
391 
392 	n = 0;
393 	clear();
394 	mvprintw(2, 10, "systat: nlist: can't find following symbols:");
395 	for (i = 0;
396 	    name_list[i].n_name != NULL && *name_list[i].n_name != '\0'; i++)
397 		if (name_list[i].n_value == 0)
398 			mvprintw(2 + ++n, 10, "%s", name_list[i].n_name);
399 	move(CMDLINE, 0);
400 	clrtoeol();
401 	refresh();
402 	sleep(5);
403 	endwin();
404 	exit(1);
405 }
406