xref: /netbsd-src/usr.bin/w/w.c (revision 5b84b3983f71fd20a534cfa5d1556623a8aaa717)
1 /*	$NetBSD: w.c,v 1.70 2005/09/04 21:18:33 elad 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\n\
35 	The Regents of the University of California.  All rights reserved.\n");
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.70 2005/09/04 21:18:33 elad 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[65];
111 	char line[65];
112 	char host[257];
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;
139 	char *memf, *nlistf, *p, *x;
140 	time_t then;
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 buf[MAXHOSTNAMELEN], 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 		p = "";
159 	} else {
160 		wcmd = 1;
161 		p = "hiM:N:nw";
162 	}
163 
164 	memf = nlistf = NULL;
165 	while ((ch = getopt(argc, argv, p)) != -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 	if ((kd = kvm_openfiles(nlistf, memf, NULL,
194 	    memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
195 		errx(1, "%s", errbuf);
196 
197 	(void)time(&now);
198 
199 #ifdef SUPPORT_UTMPX
200 	setutxent();
201 #endif
202 #ifdef SUPPORT_UTMP
203 	setutent();
204 #endif
205 
206 	if (*argv)
207 		sel_user = *argv;
208 
209 	nusers = 0;
210 #ifdef SUPPORT_UTMPX
211 	while ((utx = getutxent()) != NULL) {
212 		if (utx->ut_type != USER_PROCESS)
213 			continue;
214 		++nusers;
215 		if (sel_user &&
216 		    strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name)) != 0)
217 			continue;
218 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
219 			err(1, NULL);
220 		(void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
221 		(void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
222 		ep->name[sizeof(utx->ut_name)] = '\0';
223 		ep->line[sizeof(utx->ut_line)] = '\0';
224 		if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
225 		    utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
226 		    NI_NUMERICHOST) != 0) {
227 			(void)memcpy(ep->host, utx->ut_host,
228 			    sizeof(utx->ut_host));
229 			ep->host[sizeof(utx->ut_host)] = '\0';
230 		}
231 		ep->type[0] = 'x';
232 		ep->tv = utx->ut_tv;
233 		ep->pid = utx->ut_pid;
234 		*nextp = ep;
235 		nextp = &(ep->next);
236 		if (wcmd != 0)
237 			process(ep);
238 	}
239 #endif
240 
241 #ifdef SUPPORT_UTMP
242 	while ((ut = getutent()) != NULL) {
243 		if (ut->ut_name[0] == '\0')
244 			continue;
245 
246 		if (sel_user &&
247 		    strncmp(ut->ut_name, sel_user, sizeof(ut->ut_name)) != 0)
248 			continue;
249 
250 		/* Don't process entries that we have utmpx for */
251 		for (ep = ehead; ep != NULL; ep = ep->next) {
252 			if (strncmp(ep->line, ut->ut_line,
253 			    sizeof(ut->ut_line)) == 0)
254 				break;
255 		}
256 		if (ep != NULL)
257 			continue;
258 
259 		++nusers;
260 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
261 			err(1, NULL);
262 		(void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
263 		(void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
264 		(void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
265 		ep->name[sizeof(ut->ut_name)] = '\0';
266 		ep->line[sizeof(ut->ut_line)] = '\0';
267 		ep->host[sizeof(ut->ut_host)] = '\0';
268 		ep->tv.tv_sec = ut->ut_time;
269 		*nextp = ep;
270 		nextp = &(ep->next);
271 		if (wcmd != 0)
272 			process(ep);
273 	}
274 #endif
275 
276 #ifdef SUPPORT_UTMPX
277 	endutxent();
278 #endif
279 #ifdef SUPPORT_UTMP
280 	endutent();
281 #endif
282 
283 	if (header || wcmd == 0) {
284 		pr_header(&now, nusers);
285 		if (wcmd == 0)
286 			exit (0);
287 	}
288 
289 	if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
290 	    sizeof(struct kinfo_proc2), &nentries)) == NULL)
291 		errx(1, "%s", kvm_geterr(kd));
292 
293 	/* Include trailing space because TTY header starts one column early. */
294 	for (i = 0; i < nentries; i++, kp++) {
295 
296 		if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
297 			continue;
298 
299 		for (ep = ehead; ep != NULL; ep = ep->next) {
300 			if (ep->tdev != 0 && ep->tdev == kp->p_tdev &&
301 			    kp->p__pgid == kp->p_tpgid) {
302 				/*
303 				 * Proc is in foreground of this
304 				 * terminal
305 				 */
306 				if (proc_compare(ep->tp, kp))
307 					ep->tp = kp;
308 				break;
309 			}
310 			if (ep->pid != 0 && ep->pid == kp->p_pid) {
311 				ep->pp = kp;
312 				break;
313 			}
314 		}
315 	}
316 
317 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
318 	    ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
319 	    ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
320 		ttywidth = 79;
321 	else
322 		ttywidth = ws.ws_col - 1;
323 
324 	if (!wflag && maxhost > (ttywidth / 3))
325 		maxhost = ttywidth / 3;
326 
327 	argwidth = printf("%-*s TTY     %-*s %*s  IDLE WHAT\n",
328 	    maxname, "USER", maxhost, "FROM",
329 	    7 /* "dddhhXm" */, "LOGIN@");
330 	argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
331 	argwidth = ttywidth - argwidth;
332 	if (argwidth < 4)
333 		argwidth = 8;
334 	if (wflag)
335 		argwidth = -1;
336 
337 	/* sort by idle time */
338 	if (sortidle && ehead != NULL) {
339 		struct entry *from = ehead, *save;
340 
341 		ehead = NULL;
342 		while (from != NULL) {
343 			for (nextp = &ehead;
344 			    (*nextp) && from->idle >= (*nextp)->idle;
345 			    nextp = &(*nextp)->next)
346 				continue;
347 			save = from;
348 			from = from->next;
349 			save->next = *nextp;
350 			*nextp = save;
351 		}
352 	}
353 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
354 	else if (ehead != NULL) {
355 		struct entry *from = ehead, *save;
356 
357 		ehead = NULL;
358 		while (from != NULL) {
359 			for (nextp = &ehead;
360 			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
361 			    nextp = &(*nextp)->next)
362 				continue;
363 			save = from;
364 			from = from->next;
365 			save->next = *nextp;
366 			*nextp = save;
367 		}
368 	}
369 #endif
370 
371 	if (!nflag) {
372 		int	rv;
373 
374 		rv = gethostname(domain, sizeof(domain));
375 		domain[sizeof(domain) - 1] = '\0';
376 		if (rv < 0 || (p = strchr(domain, '.')) == 0)
377 			domain[0] = '\0';
378 		else
379 			memmove(domain, p, strlen(p) + 1);
380 	}
381 
382 	for (ep = ehead; ep != NULL; ep = ep->next) {
383 		char host_buf[MAXHOSTNAMELEN + 1];
384 
385 		strlcpy(host_buf, ep->host, sizeof(host_buf));
386 		p = *host_buf ? host_buf : "-";
387 
388 		for (x = p; x < p + MAXHOSTNAMELEN; x++)
389 			if (*x == '\0' || *x == ':')
390 				break;
391 		if (x == p + MAXHOSTNAMELEN || *x != ':')
392 			x = NULL;
393 		else
394 			*x++ = '\0';
395 
396 		if (!nflag && inet_aton(p, &l) &&
397 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
398 			if (domain[0] != '\0') {
399 				p = hp->h_name;
400 				p += strlen(hp->h_name);
401 				p -= strlen(domain);
402 				if (p > hp->h_name &&
403 				    strcasecmp(p, domain) == 0)
404 					*p = '\0';
405 			}
406 			p = hp->h_name;
407 		}
408 		if (x) {
409 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
410 			p = buf;
411 		}
412 		if (ep->tp != NULL)
413 			kp = ep->tp;
414 		else if (ep->pp != NULL)
415 			kp = ep->pp;
416 		else {
417 			warnx("Stale utmp%s entry: %s %s %s",
418 			    ep->type, ep->name, ep->line, ep->host);
419 			continue;
420 		}
421 		(void)printf("%-*s %-7.7s %-*.*s ",
422 		    maxname, kp->p_login, ep->line,
423 		    maxhost, maxhost, *p ? p : "-");
424 		then = (time_t)ep->tv.tv_sec;
425 		pr_attime(&then, &now);
426 		pr_idle(ep->idle);
427 		pr_args(kp);
428 		(void)printf("\n");
429 	}
430 	exit(0);
431 }
432 
433 static void
434 pr_args(struct kinfo_proc2 *kp)
435 {
436 	char **argv;
437 	int left;
438 
439 	if (kp == 0)
440 		goto nothing;
441 	left = argwidth;
442 	argv = kvm_getargv2(kd, kp, (argwidth < 0) ? 0 : argwidth);
443 	if (argv == 0) {
444 		if (kp->p_comm == 0) {
445 			goto nothing;
446 		} else {
447 			fmt_putc('(', &left);
448 			fmt_puts((char *)kp->p_comm, &left);
449 			fmt_putc(')', &left);
450 			return;
451 		}
452 	}
453 	while (*argv) {
454 		fmt_puts(*argv, &left);
455 		argv++;
456 		fmt_putc(' ', &left);
457 	}
458 	return;
459 nothing:
460 	putchar('-');
461 }
462 
463 static void
464 pr_header(time_t *nowp, int nusers)
465 {
466 	double avenrun[3];
467 	time_t uptime;
468 	int days, hrs, i, mins;
469 	int mib[2];
470 	size_t size;
471 	char buf[256];
472 
473 	/*
474 	 * Print time of day.
475 	 *
476 	 * SCCS forces the string manipulation below, as it replaces
477 	 * %, M, and % in a character string with the file name.
478 	 */
479 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
480 	buf[sizeof(buf) - 1] = '\0';
481 	(void)printf("%s ", buf);
482 
483 	/*
484 	 * Print how long system has been up.
485 	 * (Found by looking getting "boottime" from the kernel)
486 	 */
487 	mib[0] = CTL_KERN;
488 	mib[1] = KERN_BOOTTIME;
489 	size = sizeof(boottime);
490 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
491 	    boottime.tv_sec != 0) {
492 		uptime = now - boottime.tv_sec;
493 		uptime += 30;
494 		if (uptime > SECSPERMIN) {
495 			days = uptime / SECSPERDAY;
496 			uptime %= SECSPERDAY;
497 			hrs = uptime / SECSPERHOUR;
498 			uptime %= SECSPERHOUR;
499 			mins = uptime / SECSPERMIN;
500 			(void)printf(" up");
501 			if (days > 0)
502 				(void)printf(" %d day%s,", days,
503 				    days > 1 ? "s" : "");
504 			if (hrs > 0 && mins > 0)
505 				(void)printf(" %2d:%02d,", hrs, mins);
506 			else {
507 				if (hrs > 0)
508 					(void)printf(" %d hr%s,",
509 					    hrs, hrs > 1 ? "s" : "");
510 				if (mins > 0)
511 					(void)printf(" %d min%s,",
512 					    mins, mins > 1 ? "s" : "");
513 			}
514 		}
515 	}
516 
517 	/* Print number of users logged in to system */
518 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
519 
520 	/*
521 	 * Print 1, 5, and 15 minute load averages.
522 	 */
523 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
524 		(void)printf(", no load average information available\n");
525 	else {
526 		(void)printf(", load averages:");
527 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
528 			if (i > 0)
529 				(void)printf(",");
530 			(void)printf(" %.2f", avenrun[i]);
531 		}
532 		(void)printf("\n");
533 	}
534 }
535 
536 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
537 static int
538 ttystat(const char *line, struct stat *st)
539 {
540 	char ttybuf[MAXPATHLEN];
541 
542 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
543 	return stat(ttybuf, st);
544 }
545 
546 static void
547 process(struct entry *ep)
548 {
549 	struct stat st;
550 	time_t touched;
551 	int max;
552 
553 	if ((max = strlen(ep->name)) > maxname)
554 		maxname = max;
555 	if ((max = strlen(ep->line)) > maxline)
556 		maxline = max;
557 	if ((max = strlen(ep->host)) > maxhost)
558 		maxhost = max;
559 
560 	ep->tdev = 0;
561 	ep->idle = (time_t)-1;
562 
563 #ifdef SUPPORT_UTMP
564 	/*
565 	 * Hack to recognize and correctly parse
566 	 * ut entry made by ftpd. The "tty" used
567 	 * by ftpd is not a real tty, just identifier in
568 	 * form ftpPID. Pid parsed from the "tty name"
569 	 * is used later to match corresponding process.
570 	 * NB: This is only used for utmp entries. For utmpx,
571 	 * we already have the pid.
572 	 */
573 	if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
574 		ep->pid = strtol(ep->line + 3, NULL, 10);
575 		return;
576 	}
577 #endif
578 	if (ttystat(ep->line, &st) == -1)
579 		return;
580 
581 	ep->tdev = st.st_rdev;
582 	/*
583 	 * If this is the console device, attempt to ascertain
584 	 * the true console device dev_t.
585 	 */
586 	if (ep->tdev == 0) {
587 		int mib[2];
588 		size_t size;
589 
590 		mib[0] = CTL_KERN;
591 		mib[1] = KERN_CONSDEV;
592 		size = sizeof(dev_t);
593 		(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
594 	}
595 
596 	touched = st.st_atime;
597 	if (touched < ep->tv.tv_sec) {
598 		/* tty untouched since before login */
599 		touched = ep->tv.tv_sec;
600 	}
601 	if ((ep->idle = now - touched) < 0)
602 		ep->idle = 0;
603 }
604 #endif
605 
606 static void
607 usage(int wcmd)
608 {
609 
610 	if (wcmd)
611 		(void)fprintf(stderr,
612 		    "Usage: %s [-hinw] [-M core] [-N system] [user]\n",
613 		    getprogname());
614 	else
615 		(void)fprintf(stderr, "Usage: %s\n", getprogname());
616 	exit(1);
617 }
618