xref: /netbsd/usr.bin/w/w.c (revision 6550d01e)
1 /*	$NetBSD: w.c,v 1.74 2009/04/14 07:37:31 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1991, 1993, 1994
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, 1991, 1993, 1994\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)w.c	8.6 (Berkeley) 6/30/94";
41 #else
42 __RCSID("$NetBSD: w.c,v 1.74 2009/04/14 07:37:31 lukem Exp $");
43 #endif
44 #endif /* not lint */
45 
46 /*
47  * w - print system status (who and what)
48  *
49  * This program is similar to the systat command on Tenex/Tops 10/20
50  *
51  */
52 #include <sys/param.h>
53 #include <sys/types.h>
54 #include <sys/time.h>
55 #include <sys/stat.h>
56 #include <sys/sysctl.h>
57 #include <sys/proc.h>
58 #include <sys/user.h>
59 #include <sys/ioctl.h>
60 #include <sys/socket.h>
61 
62 #include <netinet/in.h>
63 #include <arpa/inet.h>
64 
65 #include <ctype.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <fcntl.h>
69 #include <kvm.h>
70 #include <limits.h>
71 #include <netdb.h>
72 #include <nlist.h>
73 #include <paths.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <time.h>
78 #include <tzfile.h>
79 #include <unistd.h>
80 #ifdef SUPPORT_UTMP
81 #include <utmp.h>
82 #endif
83 #ifdef SUPPORT_UTMPX
84 #include <utmpx.h>
85 #endif
86 #include <vis.h>
87 
88 #include "extern.h"
89 
90 struct timeval	boottime;
91 struct winsize	ws;
92 kvm_t	       *kd;
93 time_t		now;		/* the current time of day */
94 int		ttywidth;	/* width of tty */
95 int		argwidth;	/* width of tty left to print process args */
96 int		header = 1;	/* true if -h flag: don't print heading */
97 int		nflag;		/* true if -n flag: don't convert addrs */
98 int		wflag;		/* true if -w flag: wide printout */
99 int		sortidle;	/* sort bu idle time */
100 char	       *sel_user;	/* login of particular user selected */
101 char		domain[MAXHOSTNAMELEN + 1];
102 int maxname = 8, maxline = 3, maxhost = 16;
103 
104 /*
105  * One of these per active utmp entry.
106  */
107 struct	entry {
108 	struct	entry *next;
109 	char name[UTX_USERSIZE + 1];
110 	char line[UTX_LINESIZE + 1];
111 	char host[UTX_HOSTSIZE + 1];
112 	char type[2];
113 	struct timeval tv;
114 	dev_t	tdev;			/* dev_t of terminal */
115 	time_t	idle;			/* idle time of terminal in seconds */
116 	struct	kinfo_proc2 *tp;	/* `most interesting' tty proc */
117 	struct	kinfo_proc2 *pp;	/* pid proc */
118 	pid_t	pid;			/* pid or ~0 if not known */
119 } *ehead = NULL, **nextp = &ehead;
120 
121 static void	pr_args(struct kinfo_proc2 *);
122 static void	pr_header(time_t *, int);
123 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
124 static int	ttystat(const char *, struct stat *);
125 static void	process(struct entry *);
126 #endif
127 static void	usage(int);
128 
129 int	main(int, char **);
130 
131 int
132 main(int argc, char **argv)
133 {
134 	struct kinfo_proc2 *kp;
135 	struct hostent *hp;
136 	struct in_addr l;
137 	struct entry *ep;
138 	int ch, i, nentries, nusers, wcmd, curtain, use_sysctl;
139 	char *memf, *nlistf, *p, *x, *usrnp;
140 	const char *options;
141 	time_t then;
142 	size_t len;
143 #ifdef SUPPORT_UTMP
144 	struct utmp *ut;
145 #endif
146 #ifdef SUPPORT_UTMPX
147 	struct utmpx *utx;
148 #endif
149 	const char *progname;
150 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
151 
152 	setprogname(argv[0]);
153 
154 	/* Are we w(1) or uptime(1)? */
155 	progname = getprogname();
156 	if (*progname == '-')
157 		progname++;
158 	if (*progname == 'u') {
159 		wcmd = 0;
160 		options = "";
161 	} else {
162 		wcmd = 1;
163 		options = "hiM:N:nw";
164 	}
165 
166 	memf = nlistf = NULL;
167 	while ((ch = getopt(argc, argv, options)) != -1)
168 		switch (ch) {
169 		case 'h':
170 			header = 0;
171 			break;
172 		case 'i':
173 			sortidle = 1;
174 			break;
175 		case 'M':
176 			header = 0;
177 			memf = optarg;
178 			break;
179 		case 'N':
180 			nlistf = optarg;
181 			break;
182 		case 'n':
183 			nflag = 1;
184 			break;
185 		case 'w':
186 			wflag = 1;
187 			break;
188 		case '?':
189 		default:
190 			usage(wcmd);
191 		}
192 	argc -= optind;
193 	argv += optind;
194 
195 	use_sysctl = (memf == NULL && nlistf == NULL);
196 
197 	if ((kd = kvm_openfiles(nlistf, memf, NULL,
198 	    memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
199 		errx(1, "%s", errbuf);
200 
201 	(void)time(&now);
202 
203 	if (use_sysctl) {
204 		len = sizeof(curtain);
205 		if (sysctlbyname("security.curtain", &curtain, &len,
206 		    NULL, 0) == -1)
207 			curtain = 0;
208 	}
209 
210 #ifdef SUPPORT_UTMPX
211 	setutxent();
212 #endif
213 #ifdef SUPPORT_UTMP
214 	setutent();
215 #endif
216 
217 	if (*argv)
218 		sel_user = *argv;
219 
220 	nusers = 0;
221 #ifdef SUPPORT_UTMPX
222 	while ((utx = getutxent()) != NULL) {
223 		if (utx->ut_type != USER_PROCESS)
224 			continue;
225 		++nusers;
226 		if (sel_user &&
227 		    strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name)) != 0)
228 			continue;
229 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
230 			err(1, NULL);
231 		(void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
232 		(void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
233 		ep->name[sizeof(utx->ut_name)] = '\0';
234 		ep->line[sizeof(utx->ut_line)] = '\0';
235 		if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
236 		    utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
237 		    NI_NUMERICHOST) != 0) {
238 			(void)memcpy(ep->host, utx->ut_host,
239 			    sizeof(utx->ut_host));
240 			ep->host[sizeof(utx->ut_host)] = '\0';
241 		}
242 		ep->type[0] = 'x';
243 		ep->tv = utx->ut_tv;
244 		ep->pid = utx->ut_pid;
245 		*nextp = ep;
246 		nextp = &(ep->next);
247 		if (wcmd != 0)
248 			process(ep);
249 	}
250 #endif
251 
252 #ifdef SUPPORT_UTMP
253 	while ((ut = getutent()) != NULL) {
254 		if (ut->ut_name[0] == '\0')
255 			continue;
256 
257 		if (sel_user &&
258 		    strncmp(ut->ut_name, sel_user, sizeof(ut->ut_name)) != 0)
259 			continue;
260 
261 		/* Don't process entries that we have utmpx for */
262 		for (ep = ehead; ep != NULL; ep = ep->next) {
263 			if (strncmp(ep->line, ut->ut_line,
264 			    sizeof(ut->ut_line)) == 0)
265 				break;
266 		}
267 		if (ep != NULL)
268 			continue;
269 
270 		++nusers;
271 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
272 			err(1, NULL);
273 		(void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
274 		(void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
275 		(void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
276 		ep->name[sizeof(ut->ut_name)] = '\0';
277 		ep->line[sizeof(ut->ut_line)] = '\0';
278 		ep->host[sizeof(ut->ut_host)] = '\0';
279 		ep->tv.tv_sec = ut->ut_time;
280 		*nextp = ep;
281 		nextp = &(ep->next);
282 		if (wcmd != 0)
283 			process(ep);
284 	}
285 #endif
286 
287 #ifdef SUPPORT_UTMPX
288 	endutxent();
289 #endif
290 #ifdef SUPPORT_UTMP
291 	endutent();
292 #endif
293 
294 	if (header || wcmd == 0) {
295 		pr_header(&now, nusers);
296 		if (wcmd == 0)
297 			exit (0);
298 	}
299 
300 	if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
301 	    sizeof(struct kinfo_proc2), &nentries)) == NULL)
302 		errx(1, "%s", kvm_geterr(kd));
303 
304 	/* Include trailing space because TTY header starts one column early. */
305 	for (i = 0; i < nentries; i++, kp++) {
306 
307 		if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
308 			continue;
309 
310 		for (ep = ehead; ep != NULL; ep = ep->next) {
311 			if (ep->tdev != 0 && ep->tdev == kp->p_tdev &&
312 			    kp->p__pgid == kp->p_tpgid) {
313 				/*
314 				 * Proc is in foreground of this
315 				 * terminal
316 				 */
317 				if (proc_compare(ep->tp, kp))
318 					ep->tp = kp;
319 				break;
320 			}
321 			if (ep->pid != 0 && ep->pid == kp->p_pid) {
322 				ep->pp = kp;
323 				break;
324 			}
325 		}
326 	}
327 
328 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
329 	    ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
330 	    ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
331 		ttywidth = 79;
332 	else
333 		ttywidth = ws.ws_col - 1;
334 
335 	if (!wflag && maxhost > (ttywidth / 3))
336 		maxhost = ttywidth / 3;
337 
338 	argwidth = printf("%-*s TTY     %-*s %*s  IDLE WHAT\n",
339 	    maxname, "USER", maxhost, "FROM",
340 	    7 /* "dddhhXm" */, "LOGIN@");
341 	argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
342 	argwidth = ttywidth - argwidth;
343 	if (argwidth < 4)
344 		argwidth = 8;
345 	if (wflag)
346 		argwidth = -1;
347 
348 	/* sort by idle time */
349 	if (sortidle && ehead != NULL) {
350 		struct entry *from = ehead, *save;
351 
352 		ehead = NULL;
353 		while (from != NULL) {
354 			for (nextp = &ehead;
355 			    (*nextp) && from->idle >= (*nextp)->idle;
356 			    nextp = &(*nextp)->next)
357 				continue;
358 			save = from;
359 			from = from->next;
360 			save->next = *nextp;
361 			*nextp = save;
362 		}
363 	}
364 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
365 	else if (ehead != NULL) {
366 		struct entry *from = ehead, *save;
367 
368 		ehead = NULL;
369 		while (from != NULL) {
370 			for (nextp = &ehead;
371 			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
372 			    nextp = &(*nextp)->next)
373 				continue;
374 			save = from;
375 			from = from->next;
376 			save->next = *nextp;
377 			*nextp = save;
378 		}
379 	}
380 #endif
381 
382 	if (!nflag) {
383 		int	rv;
384 
385 		rv = gethostname(domain, sizeof(domain));
386 		domain[sizeof(domain) - 1] = '\0';
387 		if (rv < 0 || (p = strchr(domain, '.')) == 0)
388 			domain[0] = '\0';
389 		else
390 			memmove(domain, p, strlen(p) + 1);
391 	}
392 
393 	for (ep = ehead; ep != NULL; ep = ep->next) {
394 		char host_buf[MAXHOSTNAMELEN + 1];
395 
396 		strlcpy(host_buf, *ep->host ? ep->host : "-", sizeof(host_buf));
397 		p = host_buf;
398 
399 		for (x = p; x < p + MAXHOSTNAMELEN; x++)
400 			if (*x == '\0' || *x == ':')
401 				break;
402 		if (x == p + MAXHOSTNAMELEN || *x != ':')
403 			x = NULL;
404 		else
405 			*x++ = '\0';
406 
407 		if (!nflag && inet_aton(p, &l) &&
408 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
409 			if (domain[0] != '\0') {
410 				p = hp->h_name;
411 				p += strlen(hp->h_name);
412 				p -= strlen(domain);
413 				if (p > hp->h_name &&
414 				    strcasecmp(p, domain) == 0)
415 					*p = '\0';
416 			}
417 			p = hp->h_name;
418 		}
419 		if (x) {
420 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
421 			p = buf;
422 		}
423 
424 		if (ep->tp != NULL)
425 			kp = ep->tp;
426 		else if (ep->pp != NULL)
427 			kp = ep->pp;
428 		else if (ep->pid != 0) {
429 			if (curtain)
430 				kp = NULL;
431 			else {
432 				warnx("Stale utmp%s entry: %s %s %s",
433 				    ep->type, ep->name, ep->line, ep->host);
434 				continue;
435 			}
436 		}
437 		usrnp = (kp == NULL) ? ep->name : kp->p_login;
438 		(void)printf("%-*s %-7.7s %-*.*s ",
439 		    maxname, usrnp, ep->line,
440 		    maxhost, maxhost, *p ? p : "-");
441 		then = (time_t)ep->tv.tv_sec;
442 		pr_attime(&then, &now);
443 		pr_idle(ep->idle);
444 		pr_args(kp);
445 		(void)printf("\n");
446 	}
447 	exit(0);
448 }
449 
450 static void
451 pr_args(struct kinfo_proc2 *kp)
452 {
453 	char **argv;
454 	int left;
455 
456 	if (kp == 0)
457 		goto nothing;
458 	left = argwidth;
459 	argv = kvm_getargv2(kd, kp, (argwidth < 0) ? 0 : argwidth);
460 	if (argv == 0) {
461 		if (kp->p_comm == 0) {
462 			goto nothing;
463 		} else {
464 			fmt_putc('(', &left);
465 			fmt_puts((char *)kp->p_comm, &left);
466 			fmt_putc(')', &left);
467 			return;
468 		}
469 	}
470 	while (*argv) {
471 		fmt_puts(*argv, &left);
472 		argv++;
473 		fmt_putc(' ', &left);
474 	}
475 	return;
476 nothing:
477 	putchar('-');
478 }
479 
480 static void
481 pr_header(time_t *nowp, int nusers)
482 {
483 	double avenrun[3];
484 	time_t uptime;
485 	int days, hrs, mins;
486 	int mib[2];
487 	size_t size, i;
488 	char buf[256];
489 
490 	/*
491 	 * Print time of day.
492 	 *
493 	 * SCCS forces the string manipulation below, as it replaces
494 	 * %, M, and % in a character string with the file name.
495 	 */
496 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
497 	buf[sizeof(buf) - 1] = '\0';
498 	(void)printf("%s ", buf);
499 
500 	/*
501 	 * Print how long system has been up.
502 	 * (Found by looking getting "boottime" from the kernel)
503 	 */
504 	mib[0] = CTL_KERN;
505 	mib[1] = KERN_BOOTTIME;
506 	size = sizeof(boottime);
507 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
508 	    boottime.tv_sec != 0) {
509 		uptime = now - boottime.tv_sec;
510 		uptime += 30;
511 		if (uptime > SECSPERMIN) {
512 			days = uptime / SECSPERDAY;
513 			uptime %= SECSPERDAY;
514 			hrs = uptime / SECSPERHOUR;
515 			uptime %= SECSPERHOUR;
516 			mins = uptime / SECSPERMIN;
517 			(void)printf(" up");
518 			if (days > 0)
519 				(void)printf(" %d day%s,", days,
520 				    days > 1 ? "s" : "");
521 			if (hrs > 0 && mins > 0)
522 				(void)printf(" %2d:%02d,", hrs, mins);
523 			else {
524 				if (hrs > 0)
525 					(void)printf(" %d hr%s,",
526 					    hrs, hrs > 1 ? "s" : "");
527 				if (mins > 0)
528 					(void)printf(" %d min%s,",
529 					    mins, mins > 1 ? "s" : "");
530 			}
531 		}
532 	}
533 
534 	/* Print number of users logged in to system */
535 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
536 
537 	/*
538 	 * Print 1, 5, and 15 minute load averages.
539 	 */
540 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
541 		(void)printf(", no load average information available\n");
542 	else {
543 		(void)printf(", load averages:");
544 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
545 			if (i > 0)
546 				(void)printf(",");
547 			(void)printf(" %.2f", avenrun[i]);
548 		}
549 		(void)printf("\n");
550 	}
551 }
552 
553 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
554 static int
555 ttystat(const char *line, struct stat *st)
556 {
557 	char ttybuf[MAXPATHLEN];
558 
559 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
560 	return stat(ttybuf, st);
561 }
562 
563 static void
564 process(struct entry *ep)
565 {
566 	struct stat st;
567 	time_t touched;
568 	int max;
569 
570 	if ((max = strlen(ep->name)) > maxname)
571 		maxname = max;
572 	if ((max = strlen(ep->line)) > maxline)
573 		maxline = max;
574 	if ((max = strlen(ep->host)) > maxhost)
575 		maxhost = max;
576 
577 	ep->tdev = 0;
578 	ep->idle = (time_t)-1;
579 
580 #ifdef SUPPORT_UTMP
581 	/*
582 	 * Hack to recognize and correctly parse
583 	 * ut entry made by ftpd. The "tty" used
584 	 * by ftpd is not a real tty, just identifier in
585 	 * form ftpPID. Pid parsed from the "tty name"
586 	 * is used later to match corresponding process.
587 	 * NB: This is only used for utmp entries. For utmpx,
588 	 * we already have the pid.
589 	 */
590 	if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
591 		ep->pid = strtol(ep->line + 3, NULL, 10);
592 		return;
593 	}
594 #endif
595 	if (ttystat(ep->line, &st) == -1)
596 		return;
597 
598 	ep->tdev = st.st_rdev;
599 	/*
600 	 * If this is the console device, attempt to ascertain
601 	 * the true console device dev_t.
602 	 */
603 	if (ep->tdev == 0) {
604 		int mib[2];
605 		size_t size;
606 
607 		mib[0] = CTL_KERN;
608 		mib[1] = KERN_CONSDEV;
609 		size = sizeof(dev_t);
610 		(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
611 	}
612 
613 	touched = st.st_atime;
614 	if (touched < ep->tv.tv_sec) {
615 		/* tty untouched since before login */
616 		touched = ep->tv.tv_sec;
617 	}
618 	if ((ep->idle = now - touched) < 0)
619 		ep->idle = 0;
620 }
621 #endif
622 
623 static void
624 usage(int wcmd)
625 {
626 
627 	if (wcmd)
628 		(void)fprintf(stderr,
629 		    "Usage: %s [-hinw] [-M core] [-N system] [user]\n",
630 		    getprogname());
631 	else
632 		(void)fprintf(stderr, "Usage: %s\n", getprogname());
633 	exit(1);
634 }
635