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