xref: /netbsd-src/usr.bin/systat/main.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: main.c,v 1.53 2017/11/22 02:52:42 snj 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.53 2017/11/22 02:52:42 snj 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 double	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 
82 static	WINDOW *wload;			/* one line window for load average */
83 
84 static void (*sv_stop_handler)(int);
85 
86 static void stop(int);
87 __dead static void usage(void);
88 
89 gid_t egid; /* XXX needed by initiostat() and initkre() */
90 
91 int
92 main(int argc, char **argv)
93 {
94 	int ch;
95 	char errbuf[_POSIX2_LINE_MAX];
96 	const char *all;
97 	struct clockinfo clk;
98 	size_t len;
99 	int bflag = 0;
100 
101 	all = "all";
102 	egid = getegid();
103 	(void)setegid(getgid());
104 
105 	while ((ch = getopt(argc, argv, "M:N:bnw:t:")) != -1)
106 		switch(ch) {
107 		case 'M':
108 			memf = optarg;
109 			break;
110 		case 'N':
111 			nlistf = optarg;
112 			break;
113 		case 'b':
114 			bflag = !bflag;
115 			break;
116 		case 'n':
117 			nflag = !nflag;
118 			break;
119 		case 't':
120 			if ((turns = atoi(optarg)) <= 0)
121 				errx(1, "turns <= 0.");
122 			break;
123 		case 'w':
124 			if ((naptime = strtod(optarg, NULL)) <= 0)
125 				errx(1, "interval <= 0.");
126 			break;
127 		case '?':
128 		default:
129 			usage();
130 		}
131 	argc -= optind;
132 	argv += optind;
133 
134 
135 	for ( ; argc > 0; argc--, argv++) {
136 		struct mode *p;
137 		int modefound = 0;
138 
139 		if (isdigit((unsigned char)argv[0][0])) {
140 			naptime = strtod(argv[0], NULL);
141 			if (naptime <= 0)
142 				naptime = 5;
143 			continue;
144 		}
145 
146 		for (p = modes; p->c_name ; p++) {
147 			if (strstr(p->c_name, argv[0]) == p->c_name) {
148 				curmode = p;
149 				modefound++;
150 				break;
151 			}
152 
153 			if (strstr(all, argv[0]) == all) {
154 				allcounter=0;
155 				allflag=1;
156 			}
157 		}
158 
159 
160 		if (!modefound && !allflag)
161 			error("%s: Unknown command.", argv[0]);
162 	}
163 
164 	/*
165 	 * Discard setgid privileges.  If not the running kernel, we toss
166 	 * them away totally so that bad guys can't print interesting stuff
167 	 * from kernel memory, otherwise switch back to kmem for the
168 	 * duration of the kvm_openfiles() call.
169 	 */
170 	if (nlistf != NULL || memf != NULL)
171 		(void)setgid(getgid());
172 	else
173 		(void)setegid(egid);
174 
175 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
176 	if (kd == NULL) {
177 		error("%s", errbuf);
178 		exit(1);
179 	}
180 
181 	/* Get rid of privs for now. */
182 	if (nlistf == NULL && memf == NULL)
183 		(void)setegid(getgid());
184 
185 	signal(SIGINT, die);
186 	signal(SIGQUIT, die);
187 	signal(SIGTERM, die);
188 	sv_stop_handler = signal(SIGTSTP, stop);
189 
190 	/*
191 	 * Initialize display.  Load average appears in a one line
192 	 * window of its own.  Current command's display appears in
193 	 * an overlapping sub-window of stdscr configured by the display
194 	 * routines to minimize update work by curses.
195 	 */
196 	if (initscr() == NULL)
197 	{
198 		warnx("couldn't initialize screen");
199 		exit(0);
200 	}
201 
202 	CMDLINE = LINES - 1;
203 	wnd = (*curmode->c_open)();
204 	if (wnd == NULL) {
205 		warnx("couldn't initialize display");
206 		die(0);
207 	}
208 	wload = newwin(1, 0, 3, 20);
209 	if (wload == NULL) {
210 		warnx("couldn't set up load average window");
211 		die(0);
212 	}
213 	gethostname(hostname, sizeof (hostname));
214 	hostname[sizeof(hostname) - 1] = '\0';
215 
216 	len = sizeof(clk);
217 	if (sysctlbyname("kern.clockrate", &clk, &len, NULL, 0))
218 		error("can't get \"kern.clockrate\": %s", strerror(errno));
219 	hz = clk.hz;
220 	stathz = clk.stathz;
221 
222 	len = sizeof(maxslp);
223 	if (sysctlbyname("vm.maxslp", &maxslp, &len, NULL, 0))
224 		error("can't get \"vm.maxslp\": %s", strerror(errno));
225 
226 	(*curmode->c_init)();
227 	curmode->c_flags |= CF_INIT;
228 	labels();
229 
230 	dellave = 0.0;
231 
232 	display(0);
233 	if (!bflag) {
234 		noecho();
235 		cbreak();
236 		keyboard();
237 	} else
238 		die(0);
239 	/*NOTREACHED*/
240 }
241 
242 static void
243 usage(void)
244 {
245 	fprintf(stderr, "usage: systat [-bn] [-M core] [-N system] [-w wait] "
246 		"[-t turns]\n\t\t[display] [refresh-interval]\n");
247 	exit(1);
248 }
249 
250 
251 void
252 labels(void)
253 {
254 	if (curmode->c_flags & CF_LOADAV) {
255 		mvaddstr(2, 20,
256 		    "/0   /1   /2   /3   /4   /5   /6   /7   /8   /9   /10");
257 		mvaddstr(3, 5, "Load Average");
258 	}
259 	(*curmode->c_label)();
260 #ifdef notdef
261 	mvprintw(21, 25, "CPU usage on %s", hostname);
262 #endif
263 	refresh();
264 }
265 
266 void
267 display(int signo)
268 {
269 	static int skip;
270 	int j;
271 	struct mode *p;
272 	int ms_delay;
273 
274 	if (signo == SIGALRM && skip-- > 0)
275 		/* Don't display on this timeout */
276 		return;
277 
278 	/* Get the load average over the last minute. */
279 	(void)getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0]));
280 	(*curmode->c_fetch)();
281 	if (curmode->c_flags & CF_LOADAV) {
282 		j = 5.0*avenrun[0] + 0.5;
283 		dellave -= avenrun[0];
284 		if (dellave >= 0.0)
285 			c = '<';
286 		else {
287 			c = '>';
288 			dellave = -dellave;
289 		}
290 		if (dellave < 0.1)
291 			c = '|';
292 		dellave = avenrun[0];
293 		wmove(wload, 0, 0);
294 		wclrtoeol(wload);
295 		whline(wload, c, (j > 50) ? 50 : j);
296 		if (j > 50)
297 			wprintw(wload, " %4.1f", avenrun[0]);
298 	}
299 	(*curmode->c_refresh)();
300 	if (curmode->c_flags & CF_LOADAV)
301 		wrefresh(wload);
302 	wrefresh(wnd);
303 	move(CMDLINE, col);
304 	refresh();
305 
306 	if (allflag && signo==SIGALRM) {
307 		if (allcounter >= turns){
308 			p = curmode;
309 			p++;
310 			if (p->c_name == NULL)
311 				p = modes;
312 			switch_mode(p);
313 			allcounter=0;
314 		} else
315 			allcounter++;
316 	}
317 
318 	/* curses timeout() uses VTIME, limited to 255 1/10th secs */
319 	ms_delay = naptime * 1000;
320 	if (ms_delay < 25500) {
321 		timeout(ms_delay);
322 		skip = 0;
323 	} else {
324 		skip = ms_delay / 25500;
325 		timeout(ms_delay / (skip + 1));
326 	}
327 }
328 
329 void
330 redraw(void)
331 {
332 	resizeterm(LINES, COLS);
333 	CMDLINE = LINES - 1;
334 	labels();
335 
336 	display(0);
337 	needsredraw = 0;
338 }
339 
340 static void
341 stop(int signo)
342 {
343 	sigset_t set;
344 
345 	signal(SIGTSTP, sv_stop_handler);
346 	/* unblock SIGTSTP */
347 	sigemptyset(&set);
348 	sigaddset(&set, SIGTSTP);
349 	sigprocmask(SIG_UNBLOCK, &set, NULL);
350 	/* stop ourselves */
351 	kill(0, SIGTSTP);
352 	/* must have been restarted */
353 	signal(SIGTSTP, stop);
354 	needsredraw = signo;
355 }
356 
357 void
358 die(int signo)
359 {
360 	move(CMDLINE, 0);
361 	clrtoeol();
362 	refresh();
363 	endwin();
364 	exit(0);
365 }
366 
367 void
368 error(const char *fmt, ...)
369 {
370 	va_list ap;
371 	char buf[255];
372 	int oy, ox;
373 
374 	va_start(ap, fmt);
375 
376 	if (wnd) {
377 		getyx(stdscr, oy, ox);
378 		(void) vsnprintf(buf, sizeof(buf), fmt, ap);
379 		clrtoeol();
380 		standout();
381 		mvaddstr(CMDLINE, 0, buf);
382 		standend();
383 		move(oy, ox);
384 		refresh();
385 	} else {
386 		(void) vfprintf(stderr, fmt, ap);
387 		fprintf(stderr, "\n");
388 	}
389 	va_end(ap);
390 }
391 
392 void
393 clearerror(void)
394 {
395 
396 	error("%s", "");
397 }
398 
399 void
400 nlisterr(struct nlist name_list[])
401 {
402 	int i, n;
403 
404 	n = 0;
405 	clear();
406 	mvprintw(2, 10, "systat: nlist: can't find following symbols:");
407 	for (i = 0;
408 	    name_list[i].n_name != NULL && *name_list[i].n_name != '\0'; i++)
409 		if (name_list[i].n_value == 0)
410 			mvprintw(2 + ++n, 10, "%s", name_list[i].n_name);
411 	move(CMDLINE, 0);
412 	clrtoeol();
413 	refresh();
414 	sleep(5);
415 	endwin();
416 	exit(1);
417 }
418