xref: /netbsd-src/usr.bin/w/w.c (revision 28c37e673e4d9b6cbdc7483062b915cc61d1ccf5)
1 /*	$NetBSD: w.c,v 1.52 2002/09/16 04:02:21 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. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)w.c	8.6 (Berkeley) 6/30/94";
45 #else
46 __RCSID("$NetBSD: w.c,v 1.52 2002/09/16 04:02:21 christos Exp $");
47 #endif
48 #endif /* not lint */
49 
50 /*
51  * w - print system status (who and what)
52  *
53  * This program is similar to the systat command on Tenex/Tops 10/20
54  *
55  */
56 #include <sys/param.h>
57 #include <sys/types.h>
58 #include <sys/time.h>
59 #include <sys/stat.h>
60 #include <sys/sysctl.h>
61 #include <sys/proc.h>
62 #include <sys/user.h>
63 #include <sys/ioctl.h>
64 #include <sys/socket.h>
65 
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 
69 #include <ctype.h>
70 #include <err.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <kvm.h>
74 #include <limits.h>
75 #include <netdb.h>
76 #include <nlist.h>
77 #include <paths.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <time.h>
82 #include <tzfile.h>
83 #include <unistd.h>
84 #ifdef SUPPORT_UTMP
85 #include <utmp.h>
86 #endif
87 #ifdef SUPPORT_UTMPX
88 #include <utmpx.h>
89 #endif
90 #include <vis.h>
91 
92 #include "extern.h"
93 
94 #define	max(a,b)	(((a)>(b))?(a):(b))
95 
96 struct timeval	boottime;
97 struct winsize	ws;
98 kvm_t	       *kd;
99 time_t		now;		/* the current time of day */
100 time_t		uptime;		/* time of last reboot & elapsed time since */
101 int		ttywidth;	/* width of tty */
102 int		argwidth;	/* width of tty left to print process args */
103 int		header = 1;	/* true if -h flag: don't print heading */
104 int		nflag;		/* true if -n flag: don't convert addrs */
105 int		sortidle;	/* sort bu idle time */
106 char	       *sel_user;	/* login of particular user selected */
107 char		domain[MAXHOSTNAMELEN + 1];
108 int maxname = 8, maxline = 3, maxhost = 16;
109 
110 /*
111  * One of these per active utmp entry.
112  */
113 struct	entry {
114 	struct	entry *next;
115 	char name[65];
116 	char line[65];
117 	char host[257];
118 	struct timeval tv;
119 	dev_t	tdev;			/* dev_t of terminal */
120 	time_t	idle;			/* idle time of terminal in seconds */
121 	struct	kinfo_proc2 *kp;	/* `most interesting' proc */
122 #ifdef SUPPORT_FTPD_UTMP
123 	pid_t	ftpd_pid;		/* pid as extracted from ftpd's entry */
124 #endif
125 } *ep, *ehead = NULL, **nextp = &ehead;
126 
127 static void	 pr_args(struct kinfo_proc2 *);
128 static void	 pr_header(time_t *, int);
129 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
130 static struct stat *ttystat(char *);
131 static void	process(struct entry *);
132 #endif
133 static void	 usage(int);
134 int	main(int, char **);
135 
136 int
137 main(int argc, char **argv)
138 {
139 	struct kinfo_proc2 *kp;
140 	struct hostent *hp;
141 	struct in_addr l;
142 	int ch, i, nentries, nusers, wcmd;
143 	char *memf, *nlistf, *p, *x;
144 	time_t then;
145 #ifdef SUPPORT_UTMP
146 	struct utmp *ut;
147 #endif
148 #ifdef SUPPORT_UTMPX
149 	struct utmpx *utx;
150 #endif
151 	const char *progname;
152 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
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 		p = "";
161 	} else {
162 		wcmd = 1;
163 		p = "hiflM:N:nsuw";
164 	}
165 
166 	memf = nlistf = NULL;
167 	while ((ch = getopt(argc, argv, p)) != -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 'f': case 'l': case 's': case 'u': case 'w':
186 			warnx("[-flsuw] no longer supported");
187 			/* FALLTHROUGH */
188 		case '?':
189 		default:
190 			usage(wcmd);
191 		}
192 	argc -= optind;
193 	argv += optind;
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 #ifdef SUPPORT_UTMPX
202 	setutxent();
203 #endif
204 #ifdef SUPPORT_UTMP
205 	setutent();
206 #endif
207 
208 	if (*argv)
209 		sel_user = *argv;
210 
211 	nusers = 0;
212 #ifdef SUPPORT_UTMPX
213 	while ((utx = getutxent()) != NULL) {
214 		if (utx->ut_type != USER_PROCESS)
215 			continue;
216 		++nusers;
217 		if (sel_user &&
218 		    strncmp(utx->ut_name, sel_user, sizeof(utx->ut_name) != 0))
219 			continue;
220 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
221 			err(1, NULL);
222 		(void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
223 		(void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
224 		(void)memcpy(ep->host, utx->ut_host, sizeof(utx->ut_host));
225 		ep->name[sizeof(utx->ut_name)] = '\0';
226 		ep->line[sizeof(utx->ut_line)] = '\0';
227 		ep->host[sizeof(utx->ut_host)] = '\0';
228 		ep->tv = utx->ut_tv;
229 		*nextp = ep;
230 		nextp = &(ep->next);
231 		if (wcmd != 0)
232 			process(ep);
233 	}
234 #endif
235 
236 #ifdef SUPPORT_UTMP
237 	while ((ut = getutent()) != NULL) {
238 		if (ut->ut_name[0] == '\0')
239 			continue;
240 
241 		if (sel_user &&
242 		    strncmp(ut->ut_name, sel_user, sizeof(ut->ut_name) != 0))
243 			continue;
244 
245 		/* Don't process entries that we have utmpx for */
246 		for (ep = ehead; ep != NULL; ep = ep->next) {
247 			if (strncmp(ep->line, ut->ut_line,
248 			    sizeof(ut->ut_line)) == 0)
249 				break;
250 		}
251 		if (ep != NULL)
252 			continue;
253 
254 		++nusers;
255 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
256 			err(1, NULL);
257 		(void)memcpy(ep->name, ut->ut_name, sizeof(ut->ut_name));
258 		(void)memcpy(ep->line, ut->ut_line, sizeof(ut->ut_line));
259 		(void)memcpy(ep->host, ut->ut_host, sizeof(ut->ut_host));
260 		ep->name[sizeof(ut->ut_name)] = '\0';
261 		ep->line[sizeof(ut->ut_line)] = '\0';
262 		ep->host[sizeof(ut->ut_host)] = '\0';
263 		ep->tv.tv_sec = ut->ut_time;
264 		ep->tv.tv_usec = 0;
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 == kp->p_tdev &&
297 			    kp->p__pgid == kp->p_tpgid) {
298 				/*
299 				 * Proc is in foreground of this terminal
300 				 */
301 				if (proc_compare(ep->kp, kp)) {
302 					ep->kp = kp;
303 				}
304 				break;
305 			}
306 #ifdef SUPPORT_FTPD_UTMP
307 			/*
308 			 * Hack to match process to ftp utmp entry.
309 			 */
310 			else if (ep->tdev == 0 && kp->p_tdev == NODEV &&
311 			    ep->ftpd_pid == kp->p_pid) {
312 				ep->kp = kp;
313 			}
314 #endif /* SUPPORT_FTPD_UTMP */
315 		}
316 	}
317 
318 	argwidth = printf("%-*sTTY %-*s %*s  IDLE WHAT\n",
319 	    maxname, "USER", maxhost, "FROM",
320 	    7 /* "dddhhXm" */, "LOGIN@");
321 	argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
322 
323 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
324 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
325 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
326 		ttywidth = 79;
327 	else
328 		ttywidth = ws.ws_col - 1;
329 	argwidth = ttywidth - argwidth;
330 	if (argwidth < 4)
331 		argwidth = 8;
332 	/* sort by idle time */
333 	if (sortidle && ehead != NULL) {
334 		struct entry *from = ehead, *save;
335 
336 		ehead = NULL;
337 		while (from != NULL) {
338 			for (nextp = &ehead;
339 			    (*nextp) && from->idle >= (*nextp)->idle;
340 			    nextp = &(*nextp)->next)
341 				continue;
342 			save = from;
343 			from = from->next;
344 			save->next = *nextp;
345 			*nextp = save;
346 		}
347 	}
348 #if defined(SUPPORT_UTMP) && defined(SUPPORT_UTMPX)
349 	else if (ehead != NULL) {
350 		struct entry *from = ehead, *save;
351 
352 		ehead = NULL;
353 		while (from != NULL) {
354 			for (nextp = &ehead;
355 			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
356 			    nextp = &(*nextp)->next)
357 				continue;
358 			save = from;
359 			from = from->next;
360 			save->next = *nextp;
361 			*nextp = save;
362 		}
363 	}
364 #endif
365 
366 	if (!nflag) {
367 		int	rv;
368 
369 		rv = gethostname(domain, sizeof(domain));
370 		domain[sizeof(domain) - 1] = '\0';
371 		if (rv < 0 || (p = strchr(domain, '.')) == 0)
372 			domain[0] = '\0';
373 		else
374 			memmove(domain, p, strlen(p) + 1);
375 	}
376 
377 	for (ep = ehead; ep != NULL; ep = ep->next) {
378 		char host_buf[MAXHOSTNAMELEN + 1];
379 
380 		host_buf[MAXHOSTNAMELEN] = '\0';
381 		strncpy(host_buf, ep->host, MAXHOSTNAMELEN);
382 		p = *host_buf ? host_buf : "-";
383 
384 		for (x = p; x < p + MAXHOSTNAMELEN; x++)
385 			if (*x == '\0' || *x == ':')
386 				break;
387 		if (x == p + MAXHOSTNAMELEN || *x != ':')
388 			x = NULL;
389 		else
390 			*x++ = '\0';
391 
392 		if (!nflag && inet_aton(p, &l) &&
393 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
394 			if (domain[0] != '\0') {
395 				p = hp->h_name;
396 				p += strlen(hp->h_name);
397 				p -= strlen(domain);
398 				if (p > hp->h_name &&
399 				    strcasecmp(p, domain) == 0)
400 					*p = '\0';
401 			}
402 			p = hp->h_name;
403 		}
404 		if (x) {
405 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
406 			p = buf;
407 		}
408 		if (ep->kp == NULL) {
409 			warnx("Stale utmp entry: %s %s %s",
410 			    ep->name, ep->line, ep->host);
411 			continue;
412 		}
413 		(void)printf("%-*s %-2.2s %-*.*s ",
414 		    maxname, ep->kp->p_login,
415 		    (strncmp(ep->line, "tty", 3) &&
416 		    strncmp(ep->line, "dty", 3)) ?
417 		    ep->line : ep->line + 3,
418 		    maxhost, maxhost, *p ? p : "-");
419 		then = (time_t)ep->tv.tv_sec;
420 		pr_attime(&then, &now);
421 		pr_idle(ep->idle);
422 		pr_args(ep->kp);
423 		(void)printf("\n");
424 	}
425 	exit(0);
426 }
427 
428 static void
429 pr_args(struct kinfo_proc2 *kp)
430 {
431 	char **argv;
432 	int left;
433 
434 	if (kp == 0)
435 		goto nothing;
436 	left = argwidth;
437 	argv = kvm_getargv2(kd, kp, argwidth);
438 	if (argv == 0)
439 		goto nothing;
440 	while (*argv) {
441 		fmt_puts(*argv, &left);
442 		argv++;
443 		fmt_putc(' ', &left);
444 	}
445 	return;
446 nothing:
447 	putchar('-');
448 }
449 
450 static void
451 pr_header(time_t *nowp, int nusers)
452 {
453 	double avenrun[3];
454 	time_t uptime;
455 	int days, hrs, i, mins;
456 	int mib[2];
457 	size_t size;
458 	char buf[256];
459 
460 	/*
461 	 * Print time of day.
462 	 *
463 	 * SCCS forces the string manipulation below, as it replaces
464 	 * %, M, and % in a character string with the file name.
465 	 */
466 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
467 	buf[sizeof(buf) - 1] = '\0';
468 	(void)printf("%s ", buf);
469 
470 	/*
471 	 * Print how long system has been up.
472 	 * (Found by looking getting "boottime" from the kernel)
473 	 */
474 	mib[0] = CTL_KERN;
475 	mib[1] = KERN_BOOTTIME;
476 	size = sizeof(boottime);
477 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
478 	    boottime.tv_sec != 0) {
479 		uptime = now - boottime.tv_sec;
480 		uptime += 30;
481 		if (uptime > SECSPERMIN) {
482 			days = uptime / SECSPERDAY;
483 			uptime %= SECSPERDAY;
484 			hrs = uptime / SECSPERHOUR;
485 			uptime %= SECSPERHOUR;
486 			mins = uptime / SECSPERMIN;
487 			(void)printf(" up");
488 			if (days > 0)
489 				(void)printf(" %d day%s,", days,
490 				    days > 1 ? "s" : "");
491 			if (hrs > 0 && mins > 0)
492 				(void)printf(" %2d:%02d,", hrs, mins);
493 			else {
494 				if (hrs > 0)
495 					(void)printf(" %d hr%s,",
496 					    hrs, hrs > 1 ? "s" : "");
497 				if (mins > 0)
498 					(void)printf(" %d min%s,",
499 					    mins, mins > 1 ? "s" : "");
500 			}
501 		}
502 	}
503 
504 	/* Print number of users logged in to system */
505 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
506 
507 	/*
508 	 * Print 1, 5, and 15 minute load averages.
509 	 */
510 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
511 		(void)printf(", no load average information available\n");
512 	else {
513 		(void)printf(", load averages:");
514 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
515 			if (i > 0)
516 				(void)printf(",");
517 			(void)printf(" %.2f", avenrun[i]);
518 		}
519 		(void)printf("\n");
520 	}
521 }
522 
523 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
524 static struct stat *
525 ttystat(char *line)
526 {
527 	static struct stat sb;
528 	char ttybuf[MAXPATHLEN];
529 
530 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
531 	if (stat(ttybuf, &sb))
532 		return (NULL);
533 	return (&sb);
534 }
535 
536 static void
537 process(struct entry *ep)
538 {
539 	struct stat *stp;
540 	time_t touched;
541 	int max;
542 
543 	if ((max = strlen(ep->name)) > maxname)
544 		maxname = max;
545 	if ((max = strlen(ep->line)) > maxline)
546 		maxline = max;
547 	if ((max = strlen(ep->host)) > maxhost)
548 		maxhost = max;
549 
550 	if ((stp = ttystat(ep->line)) == NULL)
551 		return;
552 
553 #ifdef SUPPORT_FTPD_UTMP
554 	/*
555 	 * Hack to recognize and correctly parse
556 	 * ut entry made by ftpd. The "tty" used
557 	 * by ftpd is not a real tty, just identifier in
558 	 * form ftpSUPPORT_ID. Pid parsed from the "tty name"
559 	 * is used later to match corresponding process.
560 	 */
561 	if (strncmp(ep->line, "ftp", 3) == 0) {
562 		ep->ftpd_pid = strtol(ep->line + 3, NULL, 10);
563 
564 		return;
565 	}
566 #endif /* SUPPORT_FTPD_UTMP */
567 
568 	ep->tdev = stp->st_rdev;
569 	/*
570 	 * If this is the console device, attempt to ascertain
571 	 * the true console device dev_t.
572 	 */
573 	if (ep->tdev == 0) {
574 		int mib[2];
575 		size_t size;
576 
577 		mib[0] = CTL_KERN;
578 		mib[1] = KERN_CONSDEV;
579 		size = sizeof(dev_t);
580 		(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
581 	}
582 
583 	touched = stp->st_atime;
584 	if (touched < ep->tv.tv_sec) {
585 		/* tty untouched since before login */
586 		touched = ep->tv.tv_sec;
587 	}
588 	if ((ep->idle = now - touched) < 0)
589 		ep->idle = 0;
590 }
591 #endif
592 
593 static void
594 usage(int wcmd)
595 {
596 
597 	if (wcmd)
598 		(void)fprintf(stderr,
599 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
600 	else
601 		(void)fprintf(stderr, "uptime\n");
602 	exit(1);
603 }
604