xref: /netbsd-src/usr.bin/w/w.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: w.c,v 1.73 2008/07/21 14:19:27 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.73 2008/07/21 14:19:27 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 time_t		uptime;		/* time of last reboot & elapsed time since */
95 int		ttywidth;	/* width of tty */
96 int		argwidth;	/* width of tty left to print process args */
97 int		header = 1;	/* true if -h flag: don't print heading */
98 int		nflag;		/* true if -n flag: don't convert addrs */
99 int		wflag;		/* true if -w flag: wide printout */
100 int		sortidle;	/* sort bu idle time */
101 char	       *sel_user;	/* login of particular user selected */
102 char		domain[MAXHOSTNAMELEN + 1];
103 int maxname = 8, maxline = 3, maxhost = 16;
104 
105 /*
106  * One of these per active utmp entry.
107  */
108 struct	entry {
109 	struct	entry *next;
110 	char name[UTX_USERSIZE + 1];
111 	char line[UTX_LINESIZE + 1];
112 	char host[UTX_HOSTSIZE + 1];
113 	char type[2];
114 	struct timeval tv;
115 	dev_t	tdev;			/* dev_t of terminal */
116 	time_t	idle;			/* idle time of terminal in seconds */
117 	struct	kinfo_proc2 *tp;	/* `most interesting' tty proc */
118 	struct	kinfo_proc2 *pp;	/* pid proc */
119 	pid_t	pid;			/* pid or ~0 if not known */
120 } *ep, *ehead = NULL, **nextp = &ehead;
121 
122 static void	pr_args(struct kinfo_proc2 *);
123 static void	pr_header(time_t *, int);
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	usage(int);
129 
130 int	main(int, char **);
131 
132 int
133 main(int argc, char **argv)
134 {
135 	struct kinfo_proc2 *kp;
136 	struct hostent *hp;
137 	struct in_addr l;
138 	int ch, i, nentries, nusers, wcmd, curtain, use_sysctl;
139 	char *memf, *nlistf, *p, *x, *usrnp;
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 buf[MAXHOSTNAMELEN], 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 		p = "";
160 	} else {
161 		wcmd = 1;
162 		p = "hiM:N:nw";
163 	}
164 
165 	memf = nlistf = NULL;
166 	while ((ch = getopt(argc, argv, p)) != -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 		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 		ep->tv.tv_sec = ut->ut_time;
279 		*nextp = ep;
280 		nextp = &(ep->next);
281 		if (wcmd != 0)
282 			process(ep);
283 	}
284 #endif
285 
286 #ifdef SUPPORT_UTMPX
287 	endutxent();
288 #endif
289 #ifdef SUPPORT_UTMP
290 	endutent();
291 #endif
292 
293 	if (header || wcmd == 0) {
294 		pr_header(&now, nusers);
295 		if (wcmd == 0)
296 			exit (0);
297 	}
298 
299 	if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
300 	    sizeof(struct kinfo_proc2), &nentries)) == NULL)
301 		errx(1, "%s", kvm_geterr(kd));
302 
303 	/* Include trailing space because TTY header starts one column early. */
304 	for (i = 0; i < nentries; i++, kp++) {
305 
306 		if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
307 			continue;
308 
309 		for (ep = ehead; ep != NULL; ep = ep->next) {
310 			if (ep->tdev != 0 && ep->tdev == kp->p_tdev &&
311 			    kp->p__pgid == kp->p_tpgid) {
312 				/*
313 				 * Proc is in foreground of this
314 				 * terminal
315 				 */
316 				if (proc_compare(ep->tp, kp))
317 					ep->tp = kp;
318 				break;
319 			}
320 			if (ep->pid != 0 && ep->pid == kp->p_pid) {
321 				ep->pp = kp;
322 				break;
323 			}
324 		}
325 	}
326 
327 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
328 	    ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
329 	    ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
330 		ttywidth = 79;
331 	else
332 		ttywidth = ws.ws_col - 1;
333 
334 	if (!wflag && maxhost > (ttywidth / 3))
335 		maxhost = ttywidth / 3;
336 
337 	argwidth = printf("%-*s TTY     %-*s %*s  IDLE WHAT\n",
338 	    maxname, "USER", maxhost, "FROM",
339 	    7 /* "dddhhXm" */, "LOGIN@");
340 	argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
341 	argwidth = ttywidth - argwidth;
342 	if (argwidth < 4)
343 		argwidth = 8;
344 	if (wflag)
345 		argwidth = -1;
346 
347 	/* sort by idle time */
348 	if (sortidle && ehead != NULL) {
349 		struct entry *from = ehead, *save;
350 
351 		ehead = NULL;
352 		while (from != NULL) {
353 			for (nextp = &ehead;
354 			    (*nextp) && from->idle >= (*nextp)->idle;
355 			    nextp = &(*nextp)->next)
356 				continue;
357 			save = from;
358 			from = from->next;
359 			save->next = *nextp;
360 			*nextp = save;
361 		}
362 	}
363 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
364 	else if (ehead != NULL) {
365 		struct entry *from = ehead, *save;
366 
367 		ehead = NULL;
368 		while (from != NULL) {
369 			for (nextp = &ehead;
370 			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
371 			    nextp = &(*nextp)->next)
372 				continue;
373 			save = from;
374 			from = from->next;
375 			save->next = *nextp;
376 			*nextp = save;
377 		}
378 	}
379 #endif
380 
381 	if (!nflag) {
382 		int	rv;
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 		char host_buf[MAXHOSTNAMELEN + 1];
394 
395 		strlcpy(host_buf, ep->host, sizeof(host_buf));
396 		p = *host_buf ? host_buf : "-";
397 
398 		for (x = p; x < p + MAXHOSTNAMELEN; x++)
399 			if (*x == '\0' || *x == ':')
400 				break;
401 		if (x == p + MAXHOSTNAMELEN || *x != ':')
402 			x = NULL;
403 		else
404 			*x++ = '\0';
405 
406 		if (!nflag && inet_aton(p, &l) &&
407 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
408 			if (domain[0] != '\0') {
409 				p = hp->h_name;
410 				p += strlen(hp->h_name);
411 				p -= strlen(domain);
412 				if (p > hp->h_name &&
413 				    strcasecmp(p, domain) == 0)
414 					*p = '\0';
415 			}
416 			p = hp->h_name;
417 		}
418 		if (x) {
419 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
420 			p = buf;
421 		}
422 
423 		if (ep->tp != NULL)
424 			kp = ep->tp;
425 		else if (ep->pp != NULL)
426 			kp = ep->pp;
427 		else if (ep->pid != 0) {
428 			if (curtain)
429 				kp = NULL;
430 			else {
431 				warnx("Stale utmp%s entry: %s %s %s",
432 				    ep->type, ep->name, ep->line, ep->host);
433 				continue;
434 			}
435 		}
436 		usrnp = (kp == NULL) ? ep->name : kp->p_login;
437 		(void)printf("%-*s %-7.7s %-*.*s ",
438 		    maxname, usrnp, ep->line,
439 		    maxhost, maxhost, *p ? p : "-");
440 		then = (time_t)ep->tv.tv_sec;
441 		pr_attime(&then, &now);
442 		pr_idle(ep->idle);
443 		pr_args(kp);
444 		(void)printf("\n");
445 	}
446 	exit(0);
447 }
448 
449 static void
450 pr_args(struct kinfo_proc2 *kp)
451 {
452 	char **argv;
453 	int left;
454 
455 	if (kp == 0)
456 		goto nothing;
457 	left = argwidth;
458 	argv = kvm_getargv2(kd, kp, (argwidth < 0) ? 0 : argwidth);
459 	if (argv == 0) {
460 		if (kp->p_comm == 0) {
461 			goto nothing;
462 		} else {
463 			fmt_putc('(', &left);
464 			fmt_puts((char *)kp->p_comm, &left);
465 			fmt_putc(')', &left);
466 			return;
467 		}
468 	}
469 	while (*argv) {
470 		fmt_puts(*argv, &left);
471 		argv++;
472 		fmt_putc(' ', &left);
473 	}
474 	return;
475 nothing:
476 	putchar('-');
477 }
478 
479 static void
480 pr_header(time_t *nowp, int nusers)
481 {
482 	double avenrun[3];
483 	time_t uptime;
484 	int days, hrs, i, mins;
485 	int mib[2];
486 	size_t size;
487 	char buf[256];
488 
489 	/*
490 	 * Print time of day.
491 	 *
492 	 * SCCS forces the string manipulation below, as it replaces
493 	 * %, M, and % in a character string with the file name.
494 	 */
495 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
496 	buf[sizeof(buf) - 1] = '\0';
497 	(void)printf("%s ", buf);
498 
499 	/*
500 	 * Print how long system has been up.
501 	 * (Found by looking getting "boottime" from the kernel)
502 	 */
503 	mib[0] = CTL_KERN;
504 	mib[1] = KERN_BOOTTIME;
505 	size = sizeof(boottime);
506 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
507 	    boottime.tv_sec != 0) {
508 		uptime = now - boottime.tv_sec;
509 		uptime += 30;
510 		if (uptime > SECSPERMIN) {
511 			days = uptime / SECSPERDAY;
512 			uptime %= SECSPERDAY;
513 			hrs = uptime / SECSPERHOUR;
514 			uptime %= SECSPERHOUR;
515 			mins = uptime / SECSPERMIN;
516 			(void)printf(" up");
517 			if (days > 0)
518 				(void)printf(" %d day%s,", days,
519 				    days > 1 ? "s" : "");
520 			if (hrs > 0 && mins > 0)
521 				(void)printf(" %2d:%02d,", hrs, mins);
522 			else {
523 				if (hrs > 0)
524 					(void)printf(" %d hr%s,",
525 					    hrs, hrs > 1 ? "s" : "");
526 				if (mins > 0)
527 					(void)printf(" %d min%s,",
528 					    mins, mins > 1 ? "s" : "");
529 			}
530 		}
531 	}
532 
533 	/* Print number of users logged in to system */
534 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
535 
536 	/*
537 	 * Print 1, 5, and 15 minute load averages.
538 	 */
539 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
540 		(void)printf(", no load average information available\n");
541 	else {
542 		(void)printf(", load averages:");
543 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
544 			if (i > 0)
545 				(void)printf(",");
546 			(void)printf(" %.2f", avenrun[i]);
547 		}
548 		(void)printf("\n");
549 	}
550 }
551 
552 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
553 static int
554 ttystat(const char *line, struct stat *st)
555 {
556 	char ttybuf[MAXPATHLEN];
557 
558 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
559 	return stat(ttybuf, st);
560 }
561 
562 static void
563 process(struct entry *ep)
564 {
565 	struct stat st;
566 	time_t touched;
567 	int max;
568 
569 	if ((max = strlen(ep->name)) > maxname)
570 		maxname = max;
571 	if ((max = strlen(ep->line)) > maxline)
572 		maxline = max;
573 	if ((max = strlen(ep->host)) > maxhost)
574 		maxhost = max;
575 
576 	ep->tdev = 0;
577 	ep->idle = (time_t)-1;
578 
579 #ifdef SUPPORT_UTMP
580 	/*
581 	 * Hack to recognize and correctly parse
582 	 * ut entry made by ftpd. The "tty" used
583 	 * by ftpd is not a real tty, just identifier in
584 	 * form ftpPID. Pid parsed from the "tty name"
585 	 * is used later to match corresponding process.
586 	 * NB: This is only used for utmp entries. For utmpx,
587 	 * we already have the pid.
588 	 */
589 	if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
590 		ep->pid = strtol(ep->line + 3, NULL, 10);
591 		return;
592 	}
593 #endif
594 	if (ttystat(ep->line, &st) == -1)
595 		return;
596 
597 	ep->tdev = st.st_rdev;
598 	/*
599 	 * If this is the console device, attempt to ascertain
600 	 * the true console device dev_t.
601 	 */
602 	if (ep->tdev == 0) {
603 		int mib[2];
604 		size_t size;
605 
606 		mib[0] = CTL_KERN;
607 		mib[1] = KERN_CONSDEV;
608 		size = sizeof(dev_t);
609 		(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
610 	}
611 
612 	touched = st.st_atime;
613 	if (touched < ep->tv.tv_sec) {
614 		/* tty untouched since before login */
615 		touched = ep->tv.tv_sec;
616 	}
617 	if ((ep->idle = now - touched) < 0)
618 		ep->idle = 0;
619 }
620 #endif
621 
622 static void
623 usage(int wcmd)
624 {
625 
626 	if (wcmd)
627 		(void)fprintf(stderr,
628 		    "Usage: %s [-hinw] [-M core] [-N system] [user]\n",
629 		    getprogname());
630 	else
631 		(void)fprintf(stderr, "Usage: %s\n", getprogname());
632 	exit(1);
633 }
634