xref: /netbsd-src/usr.bin/w/w.c (revision 6d322f2f4598f0d8a138f10ea648ec4fabe41f8b)
1 /*	$NetBSD: w.c,v 1.77 2013/09/09 19:20:38 christos 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.77 2013/09/09 19:20:38 christos 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 static int	proc_compare_wrapper(const struct kinfo_proc2 *,
124     const struct kinfo_proc2 *);
125 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
126 static int	ttystat(const char *, struct stat *);
127 static void	process(struct entry *);
128 #endif
129 static void	fixhost(struct entry *ep);
130 __dead static void	usage(int);
131 
132 int
133 main(int argc, char **argv)
134 {
135 	struct kinfo_proc2 *kp;
136 	struct entry *ep;
137 	int ch, i, nentries, nusers, wcmd, curtain, use_sysctl;
138 	char *memf, *nlistf, *usrnp;
139 	const char *options;
140 	time_t then;
141 	size_t len;
142 #ifdef SUPPORT_UTMP
143 	struct utmp *ut;
144 #endif
145 #ifdef SUPPORT_UTMPX
146 	struct utmpx *utx;
147 #endif
148 	const char *progname;
149 	char errbuf[_POSIX2_LINE_MAX];
150 
151 	setprogname(argv[0]);
152 
153 	/* Are we w(1) or uptime(1)? */
154 	progname = getprogname();
155 	if (*progname == '-')
156 		progname++;
157 	if (*progname == 'u') {
158 		wcmd = 0;
159 		options = "";
160 	} else {
161 		wcmd = 1;
162 		options = "hiM:N:nw";
163 	}
164 
165 	memf = nlistf = NULL;
166 	while ((ch = getopt(argc, argv, options)) != -1)
167 		switch (ch) {
168 		case 'h':
169 			header = 0;
170 			break;
171 		case 'i':
172 			sortidle = 1;
173 			break;
174 		case 'M':
175 			header = 0;
176 			memf = optarg;
177 			break;
178 		case 'N':
179 			nlistf = optarg;
180 			break;
181 		case 'n':
182 			nflag = 1;
183 			break;
184 		case 'w':
185 			wflag = 1;
186 			break;
187 		case '?':
188 		default:
189 			usage(wcmd);
190 		}
191 	argc -= optind;
192 	argv += optind;
193 
194 	use_sysctl = (memf == NULL && nlistf == NULL);
195 
196 	if ((kd = kvm_openfiles(nlistf, memf, NULL,
197 	    memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
198 		errx(1, "%s", errbuf);
199 
200 	(void)time(&now);
201 
202 	if (use_sysctl) {
203 		len = sizeof(curtain);
204 		if (sysctlbyname("security.curtain", &curtain, &len,
205 		    NULL, 0) == -1)
206 			curtain = 0;
207 	}
208 
209 #ifdef SUPPORT_UTMPX
210 	setutxent();
211 #endif
212 #ifdef SUPPORT_UTMP
213 	setutent();
214 #endif
215 
216 	if (*argv)
217 		sel_user = *argv;
218 
219 	nusers = 0;
220 #ifdef SUPPORT_UTMPX
221 	while ((utx = getutxent()) != NULL) {
222 		if (utx->ut_type != USER_PROCESS)
223 			continue;
224 		++nusers;
225 		if (sel_user &&
226 		    strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name)) != 0)
227 			continue;
228 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
229 			err(1, NULL);
230 		(void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
231 		(void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
232 		ep->name[sizeof(utx->ut_name)] = '\0';
233 		ep->line[sizeof(utx->ut_line)] = '\0';
234 		if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
235 		    utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
236 		    NI_NUMERICHOST) != 0) {
237 			(void)memcpy(ep->host, utx->ut_host,
238 			    sizeof(utx->ut_host));
239 			ep->host[sizeof(utx->ut_host)] = '\0';
240 		}
241 		fixhost(ep);
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 		fixhost(ep);
280 		ep->tv.tv_sec = ut->ut_time;
281 		*nextp = ep;
282 		nextp = &(ep->next);
283 		if (wcmd != 0)
284 			process(ep);
285 	}
286 #endif
287 
288 #ifdef SUPPORT_UTMPX
289 	endutxent();
290 #endif
291 #ifdef SUPPORT_UTMP
292 	endutent();
293 #endif
294 
295 	if (header || wcmd == 0) {
296 		pr_header(&now, nusers);
297 		if (wcmd == 0)
298 			exit (0);
299 	}
300 
301 	if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
302 	    sizeof(struct kinfo_proc2), &nentries)) == NULL)
303 		errx(1, "%s", kvm_geterr(kd));
304 
305 	/* Include trailing space because TTY header starts one column early. */
306 	for (i = 0; i < nentries; i++, kp++) {
307 
308 		for (ep = ehead; ep != NULL; ep = ep->next) {
309 			if (ep->tdev != 0 && ep->tdev == kp->p_tdev &&
310 			    kp->p__pgid == kp->p_tpgid) {
311 				/*
312 				 * Proc is in foreground of this
313 				 * terminal
314 				 */
315 				if (proc_compare_wrapper(ep->tp, kp))
316 					ep->tp = kp;
317 				break;
318 			}
319 			if (ep->pid != 0 && ep->pid == kp->p_pid) {
320 				ep->pp = kp;
321 				break;
322 			}
323 		}
324 	}
325 
326 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
327 	    ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
328 	    ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
329 		ttywidth = 79;
330 	else
331 		ttywidth = ws.ws_col - 1;
332 
333 	if (!wflag && maxhost > (ttywidth / 3))
334 		maxhost = ttywidth / 3;
335 
336 	argwidth = printf("%-*s TTY     %-*s %*s  IDLE WHAT\n",
337 	    maxname, "USER", maxhost, "FROM",
338 	    7 /* "dddhhXm" */, "LOGIN@");
339 	argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
340 	argwidth = ttywidth - argwidth;
341 	if (argwidth < 4)
342 		argwidth = 8;
343 	if (wflag)
344 		argwidth = -1;
345 
346 	/* sort by idle time */
347 	if (sortidle && ehead != NULL) {
348 		struct entry *from = ehead, *save;
349 
350 		ehead = NULL;
351 		while (from != NULL) {
352 			for (nextp = &ehead;
353 			    (*nextp) && from->idle >= (*nextp)->idle;
354 			    nextp = &(*nextp)->next)
355 				continue;
356 			save = from;
357 			from = from->next;
358 			save->next = *nextp;
359 			*nextp = save;
360 		}
361 	}
362 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
363 	else if (ehead != NULL) {
364 		struct entry *from = ehead, *save;
365 
366 		ehead = NULL;
367 		while (from != NULL) {
368 			for (nextp = &ehead;
369 			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
370 			    nextp = &(*nextp)->next)
371 				continue;
372 			save = from;
373 			from = from->next;
374 			save->next = *nextp;
375 			*nextp = save;
376 		}
377 	}
378 #endif
379 
380 	if (!nflag) {
381 		int	rv;
382 		char	*p;
383 
384 		rv = gethostname(domain, sizeof(domain));
385 		domain[sizeof(domain) - 1] = '\0';
386 		if (rv < 0 || (p = strchr(domain, '.')) == 0)
387 			domain[0] = '\0';
388 		else
389 			memmove(domain, p, strlen(p) + 1);
390 	}
391 
392 	for (ep = ehead; ep != NULL; ep = ep->next) {
393 		if (ep->tp != NULL)
394 			kp = ep->tp;
395 		else if (ep->pp != NULL)
396 			kp = ep->pp;
397 		else if (ep->pid != 0) {
398 			if (curtain)
399 				kp = NULL;
400 			else {
401 				warnx("Stale utmp%s entry: %s %s %s",
402 				    ep->type, ep->name, ep->line, ep->host);
403 				continue;
404 			}
405 		}
406 		usrnp = (kp == NULL) ? ep->name : kp->p_login;
407 		(void)printf("%-*s %-7.7s %-*.*s ",
408 		    maxname, usrnp, ep->line,
409 		    maxhost, maxhost, ep->host);
410 		then = (time_t)ep->tv.tv_sec;
411 		pr_attime(&then, &now);
412 		pr_idle(ep->idle);
413 		pr_args(kp);
414 		(void)printf("\n");
415 	}
416 	exit(0);
417 }
418 
419 static void
420 pr_args(struct kinfo_proc2 *kp)
421 {
422 	char **argv;
423 	int left;
424 
425 	if (kp == 0)
426 		goto nothing;
427 	left = argwidth;
428 	argv = kvm_getargv2(kd, kp, (argwidth < 0) ? 0 : argwidth);
429 	if (argv == 0) {
430 		if (kp->p_comm == 0) {
431 			goto nothing;
432 		} else {
433 			fmt_putc('(', &left);
434 			fmt_puts((char *)kp->p_comm, &left);
435 			fmt_putc(')', &left);
436 			return;
437 		}
438 	}
439 	while (*argv) {
440 		fmt_puts(*argv, &left);
441 		argv++;
442 		fmt_putc(' ', &left);
443 	}
444 	return;
445 nothing:
446 	putchar('-');
447 }
448 
449 static void
450 pr_header(time_t *nowp, int nusers)
451 {
452 	double avenrun[3];
453 	time_t uptime;
454 	int days, hrs, mins;
455 	int mib[2];
456 	size_t size, i;
457 	char buf[256];
458 
459 	/*
460 	 * Print time of day.
461 	 *
462 	 * SCCS forces the string manipulation below, as it replaces
463 	 * %, M, and % in a character string with the file name.
464 	 */
465 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
466 	buf[sizeof(buf) - 1] = '\0';
467 	(void)printf("%s ", buf);
468 
469 	/*
470 	 * Print how long system has been up.
471 	 * (Found by looking getting "boottime" from the kernel)
472 	 */
473 	mib[0] = CTL_KERN;
474 	mib[1] = KERN_BOOTTIME;
475 	size = sizeof(boottime);
476 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
477 	    boottime.tv_sec != 0) {
478 		uptime = now - boottime.tv_sec;
479 		uptime += 30;
480 		if (uptime > SECSPERMIN) {
481 			days = uptime / SECSPERDAY;
482 			uptime %= SECSPERDAY;
483 			hrs = uptime / SECSPERHOUR;
484 			uptime %= SECSPERHOUR;
485 			mins = uptime / SECSPERMIN;
486 			(void)printf(" up");
487 			if (days > 0)
488 				(void)printf(" %d day%s,", days,
489 				    days > 1 ? "s" : "");
490 			if (hrs > 0 && mins > 0)
491 				(void)printf(" %2d:%02d,", hrs, mins);
492 			else {
493 				if (hrs > 0)
494 					(void)printf(" %d hr%s,",
495 					    hrs, hrs > 1 ? "s" : "");
496 				if (mins > 0)
497 					(void)printf(" %d min%s,",
498 					    mins, mins > 1 ? "s" : "");
499 			}
500 		}
501 	}
502 
503 	/* Print number of users logged in to system */
504 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
505 
506 	/*
507 	 * Print 1, 5, and 15 minute load averages.
508 	 */
509 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
510 		(void)printf(", no load average information available\n");
511 	else {
512 		(void)printf(", load averages:");
513 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
514 			if (i > 0)
515 				(void)printf(",");
516 			(void)printf(" %.2f", avenrun[i]);
517 		}
518 		(void)printf("\n");
519 	}
520 }
521 
522 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
523 static int
524 ttystat(const char *line, struct stat *st)
525 {
526 	char ttybuf[MAXPATHLEN];
527 
528 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
529 	return stat(ttybuf, st);
530 }
531 
532 static void
533 process(struct entry *ep)
534 {
535 	struct stat st;
536 	time_t touched;
537 	int max;
538 
539 	if ((max = strlen(ep->name)) > maxname)
540 		maxname = max;
541 	if ((max = strlen(ep->line)) > maxline)
542 		maxline = max;
543 	if ((max = strlen(ep->host)) > maxhost)
544 		maxhost = max;
545 
546 	ep->tdev = 0;
547 	ep->idle = (time_t)-1;
548 
549 #ifdef SUPPORT_UTMP
550 	/*
551 	 * Hack to recognize and correctly parse
552 	 * ut entry made by ftpd. The "tty" used
553 	 * by ftpd is not a real tty, just identifier in
554 	 * form ftpPID. Pid parsed from the "tty name"
555 	 * is used later to match corresponding process.
556 	 * NB: This is only used for utmp entries. For utmpx,
557 	 * we already have the pid.
558 	 */
559 	if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
560 		ep->pid = strtol(ep->line + 3, NULL, 10);
561 		return;
562 	}
563 #endif
564 	if (ttystat(ep->line, &st) == -1)
565 		return;
566 
567 	ep->tdev = st.st_rdev;
568 	/*
569 	 * If this is the console device, attempt to ascertain
570 	 * the true console device dev_t.
571 	 */
572 	if (ep->tdev == 0) {
573 		int mib[2];
574 		size_t size;
575 
576 		mib[0] = CTL_KERN;
577 		mib[1] = KERN_CONSDEV;
578 		size = sizeof(dev_t);
579 		(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
580 	}
581 
582 	touched = st.st_atime;
583 	if (touched < ep->tv.tv_sec) {
584 		/* tty untouched since before login */
585 		touched = ep->tv.tv_sec;
586 	}
587 	if ((ep->idle = now - touched) < 0)
588 		ep->idle = 0;
589 }
590 #endif
591 
592 static int
593 proc_compare_wrapper(const struct kinfo_proc2 *p1,
594     const struct kinfo_proc2 *p2)
595 {
596 	struct kinfo_lwp *l1, *l2;
597 	int cnt;
598 
599 	if (p1 == NULL)
600 		return 1;
601 
602 	l1 = kvm_getlwps(kd, p1->p_pid, 0, sizeof(*l1), &cnt);
603 	if (l1 == NULL || cnt == 0)
604 		return 1;
605 
606 	l2 = kvm_getlwps(kd, p2->p_pid, 0, sizeof(*l1), &cnt);
607 	if (l2 == NULL || cnt == 0)
608 		return 0;
609 
610 	return proc_compare(p1, l1, p2, l2);
611 }
612 
613 static void
614 fixhost(struct entry *ep)
615 {
616 	char host_buf[sizeof(ep->host)];
617 	char *p, *x;
618 	struct hostent *hp;
619 	struct in_addr l;
620 
621 	strlcpy(host_buf, *ep->host ? ep->host : "-", sizeof(host_buf));
622 	p = host_buf;
623 
624 	/*
625 	 * XXX: Historical behavior, ':' in hostname means X display number,
626 	 * IPv6 not handled.
627 	 */
628 	for (x = p; x < &host_buf[sizeof(host_buf)]; x++)
629 		if (*x == '\0' || *x == ':')
630 			break;
631 	if (x == p + sizeof(host_buf) || *x != ':')
632 		x = NULL;
633 	else
634 		*x++ = '\0';
635 
636 	if (!nflag && inet_aton(p, &l) &&
637 	    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
638 		if (domain[0] != '\0') {
639 			p = hp->h_name;
640 			p += strlen(hp->h_name);
641 			p -= strlen(domain);
642 			if (p > hp->h_name &&
643 			    strcasecmp(p, domain) == 0)
644 				*p = '\0';
645 		}
646 		p = hp->h_name;
647 	}
648 
649 	if (x)
650 		(void)snprintf(ep->host, sizeof(ep->host), "%s:%s", p, x);
651 	else
652 
653 		strlcpy(ep->host, p, sizeof(ep->host));
654 }
655 
656 static void
657 usage(int wcmd)
658 {
659 
660 	if (wcmd)
661 		(void)fprintf(stderr,
662 		    "Usage: %s [-hinw] [-M core] [-N system] [user]\n",
663 		    getprogname());
664 	else
665 		(void)fprintf(stderr, "Usage: %s\n", getprogname());
666 	exit(1);
667 }
668