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