xref: /netbsd-src/usr.bin/w/w.c (revision a4ddc2c8fb9af816efe3b1c375a5530aef0e89e9)
1 /*	$NetBSD: w.c,v 1.76 2011/10/21 02:26:09 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.76 2011/10/21 02:26:09 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 __dead static void	usage(int);
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 		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 
382 		rv = gethostname(domain, sizeof(domain));
383 		domain[sizeof(domain) - 1] = '\0';
384 		if (rv < 0 || (p = strchr(domain, '.')) == 0)
385 			domain[0] = '\0';
386 		else
387 			memmove(domain, p, strlen(p) + 1);
388 	}
389 
390 	for (ep = ehead; ep != NULL; ep = ep->next) {
391 		char host_buf[MAXHOSTNAMELEN + 1];
392 
393 		strlcpy(host_buf, *ep->host ? ep->host : "-", sizeof(host_buf));
394 		p = host_buf;
395 
396 		for (x = p; x < p + MAXHOSTNAMELEN; x++)
397 			if (*x == '\0' || *x == ':')
398 				break;
399 		if (x == p + MAXHOSTNAMELEN || *x != ':')
400 			x = NULL;
401 		else
402 			*x++ = '\0';
403 
404 		if (!nflag && inet_aton(p, &l) &&
405 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
406 			if (domain[0] != '\0') {
407 				p = hp->h_name;
408 				p += strlen(hp->h_name);
409 				p -= strlen(domain);
410 				if (p > hp->h_name &&
411 				    strcasecmp(p, domain) == 0)
412 					*p = '\0';
413 			}
414 			p = hp->h_name;
415 		}
416 		if (x) {
417 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
418 			p = buf;
419 		}
420 
421 		if (ep->tp != NULL)
422 			kp = ep->tp;
423 		else if (ep->pp != NULL)
424 			kp = ep->pp;
425 		else if (ep->pid != 0) {
426 			if (curtain)
427 				kp = NULL;
428 			else {
429 				warnx("Stale utmp%s entry: %s %s %s",
430 				    ep->type, ep->name, ep->line, ep->host);
431 				continue;
432 			}
433 		}
434 		usrnp = (kp == NULL) ? ep->name : kp->p_login;
435 		(void)printf("%-*s %-7.7s %-*.*s ",
436 		    maxname, usrnp, ep->line,
437 		    maxhost, maxhost, *p ? p : "-");
438 		then = (time_t)ep->tv.tv_sec;
439 		pr_attime(&then, &now);
440 		pr_idle(ep->idle);
441 		pr_args(kp);
442 		(void)printf("\n");
443 	}
444 	exit(0);
445 }
446 
447 static void
448 pr_args(struct kinfo_proc2 *kp)
449 {
450 	char **argv;
451 	int left;
452 
453 	if (kp == 0)
454 		goto nothing;
455 	left = argwidth;
456 	argv = kvm_getargv2(kd, kp, (argwidth < 0) ? 0 : argwidth);
457 	if (argv == 0) {
458 		if (kp->p_comm == 0) {
459 			goto nothing;
460 		} else {
461 			fmt_putc('(', &left);
462 			fmt_puts((char *)kp->p_comm, &left);
463 			fmt_putc(')', &left);
464 			return;
465 		}
466 	}
467 	while (*argv) {
468 		fmt_puts(*argv, &left);
469 		argv++;
470 		fmt_putc(' ', &left);
471 	}
472 	return;
473 nothing:
474 	putchar('-');
475 }
476 
477 static void
478 pr_header(time_t *nowp, int nusers)
479 {
480 	double avenrun[3];
481 	time_t uptime;
482 	int days, hrs, mins;
483 	int mib[2];
484 	size_t size, i;
485 	char buf[256];
486 
487 	/*
488 	 * Print time of day.
489 	 *
490 	 * SCCS forces the string manipulation below, as it replaces
491 	 * %, M, and % in a character string with the file name.
492 	 */
493 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
494 	buf[sizeof(buf) - 1] = '\0';
495 	(void)printf("%s ", buf);
496 
497 	/*
498 	 * Print how long system has been up.
499 	 * (Found by looking getting "boottime" from the kernel)
500 	 */
501 	mib[0] = CTL_KERN;
502 	mib[1] = KERN_BOOTTIME;
503 	size = sizeof(boottime);
504 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
505 	    boottime.tv_sec != 0) {
506 		uptime = now - boottime.tv_sec;
507 		uptime += 30;
508 		if (uptime > SECSPERMIN) {
509 			days = uptime / SECSPERDAY;
510 			uptime %= SECSPERDAY;
511 			hrs = uptime / SECSPERHOUR;
512 			uptime %= SECSPERHOUR;
513 			mins = uptime / SECSPERMIN;
514 			(void)printf(" up");
515 			if (days > 0)
516 				(void)printf(" %d day%s,", days,
517 				    days > 1 ? "s" : "");
518 			if (hrs > 0 && mins > 0)
519 				(void)printf(" %2d:%02d,", hrs, mins);
520 			else {
521 				if (hrs > 0)
522 					(void)printf(" %d hr%s,",
523 					    hrs, hrs > 1 ? "s" : "");
524 				if (mins > 0)
525 					(void)printf(" %d min%s,",
526 					    mins, mins > 1 ? "s" : "");
527 			}
528 		}
529 	}
530 
531 	/* Print number of users logged in to system */
532 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
533 
534 	/*
535 	 * Print 1, 5, and 15 minute load averages.
536 	 */
537 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
538 		(void)printf(", no load average information available\n");
539 	else {
540 		(void)printf(", load averages:");
541 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
542 			if (i > 0)
543 				(void)printf(",");
544 			(void)printf(" %.2f", avenrun[i]);
545 		}
546 		(void)printf("\n");
547 	}
548 }
549 
550 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
551 static int
552 ttystat(const char *line, struct stat *st)
553 {
554 	char ttybuf[MAXPATHLEN];
555 
556 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
557 	return stat(ttybuf, st);
558 }
559 
560 static void
561 process(struct entry *ep)
562 {
563 	struct stat st;
564 	time_t touched;
565 	int max;
566 
567 	if ((max = strlen(ep->name)) > maxname)
568 		maxname = max;
569 	if ((max = strlen(ep->line)) > maxline)
570 		maxline = max;
571 	if ((max = strlen(ep->host)) > maxhost)
572 		maxhost = max;
573 
574 	ep->tdev = 0;
575 	ep->idle = (time_t)-1;
576 
577 #ifdef SUPPORT_UTMP
578 	/*
579 	 * Hack to recognize and correctly parse
580 	 * ut entry made by ftpd. The "tty" used
581 	 * by ftpd is not a real tty, just identifier in
582 	 * form ftpPID. Pid parsed from the "tty name"
583 	 * is used later to match corresponding process.
584 	 * NB: This is only used for utmp entries. For utmpx,
585 	 * we already have the pid.
586 	 */
587 	if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
588 		ep->pid = strtol(ep->line + 3, NULL, 10);
589 		return;
590 	}
591 #endif
592 	if (ttystat(ep->line, &st) == -1)
593 		return;
594 
595 	ep->tdev = st.st_rdev;
596 	/*
597 	 * If this is the console device, attempt to ascertain
598 	 * the true console device dev_t.
599 	 */
600 	if (ep->tdev == 0) {
601 		int mib[2];
602 		size_t size;
603 
604 		mib[0] = CTL_KERN;
605 		mib[1] = KERN_CONSDEV;
606 		size = sizeof(dev_t);
607 		(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
608 	}
609 
610 	touched = st.st_atime;
611 	if (touched < ep->tv.tv_sec) {
612 		/* tty untouched since before login */
613 		touched = ep->tv.tv_sec;
614 	}
615 	if ((ep->idle = now - touched) < 0)
616 		ep->idle = 0;
617 }
618 #endif
619 
620 static int
621 proc_compare_wrapper(const struct kinfo_proc2 *p1,
622     const struct kinfo_proc2 *p2)
623 {
624 	struct kinfo_lwp *l1, *l2;
625 	int cnt;
626 
627 	if (p1 == NULL)
628 		return 1;
629 
630 	l1 = kvm_getlwps(kd, p1->p_pid, 0, sizeof(*l1), &cnt);
631 	if (l1 == NULL || cnt == 0)
632 		return 1;
633 
634 	l2 = kvm_getlwps(kd, p2->p_pid, 0, sizeof(*l1), &cnt);
635 	if (l2 == NULL || cnt == 0)
636 		return 0;
637 
638 	return proc_compare(p1, l1, p2, l2);
639 }
640 
641 static void
642 usage(int wcmd)
643 {
644 
645 	if (wcmd)
646 		(void)fprintf(stderr,
647 		    "Usage: %s [-hinw] [-M core] [-N system] [user]\n",
648 		    getprogname());
649 	else
650 		(void)fprintf(stderr, "Usage: %s\n", getprogname());
651 	exit(1);
652 }
653