xref: /netbsd-src/usr.bin/w/w.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: w.c,v 1.63 2004/11/11 00:09:07 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\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.63 2004/11/11 00:09:07 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 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("%-*s TTY     %-*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 %-7.7s %-*.*s ",
412 		    maxname, kp->p_login, ep->line,
413 		    maxhost, maxhost, *p ? p : "-");
414 		then = (time_t)ep->tv.tv_sec;
415 		pr_attime(&then, &now);
416 		pr_idle(ep->idle);
417 		pr_args(kp);
418 		(void)printf("\n");
419 	}
420 	exit(0);
421 }
422 
423 static void
424 pr_args(struct kinfo_proc2 *kp)
425 {
426 	char **argv;
427 	int left;
428 
429 	if (kp == 0)
430 		goto nothing;
431 	left = argwidth;
432 	argv = kvm_getargv2(kd, kp, argwidth);
433 	if (argv == 0) {
434 		if (kp->p_comm == 0) {
435 			goto nothing;
436 		} else {
437 			fmt_putc('(', &left);
438 			fmt_puts((char *)kp->p_comm, &left);
439 			fmt_putc(')', &left);
440 			return;
441 		}
442 	}
443 	while (*argv) {
444 		fmt_puts(*argv, &left);
445 		argv++;
446 		fmt_putc(' ', &left);
447 	}
448 	return;
449 nothing:
450 	putchar('-');
451 }
452 
453 static void
454 pr_header(time_t *nowp, int nusers)
455 {
456 	double avenrun[3];
457 	time_t uptime;
458 	int days, hrs, i, mins;
459 	int mib[2];
460 	size_t size;
461 	char buf[256];
462 
463 	/*
464 	 * Print time of day.
465 	 *
466 	 * SCCS forces the string manipulation below, as it replaces
467 	 * %, M, and % in a character string with the file name.
468 	 */
469 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
470 	buf[sizeof(buf) - 1] = '\0';
471 	(void)printf("%s ", buf);
472 
473 	/*
474 	 * Print how long system has been up.
475 	 * (Found by looking getting "boottime" from the kernel)
476 	 */
477 	mib[0] = CTL_KERN;
478 	mib[1] = KERN_BOOTTIME;
479 	size = sizeof(boottime);
480 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
481 	    boottime.tv_sec != 0) {
482 		uptime = now - boottime.tv_sec;
483 		uptime += 30;
484 		if (uptime > SECSPERMIN) {
485 			days = uptime / SECSPERDAY;
486 			uptime %= SECSPERDAY;
487 			hrs = uptime / SECSPERHOUR;
488 			uptime %= SECSPERHOUR;
489 			mins = uptime / SECSPERMIN;
490 			(void)printf(" up");
491 			if (days > 0)
492 				(void)printf(" %d day%s,", days,
493 				    days > 1 ? "s" : "");
494 			if (hrs > 0 && mins > 0)
495 				(void)printf(" %2d:%02d,", hrs, mins);
496 			else {
497 				if (hrs > 0)
498 					(void)printf(" %d hr%s,",
499 					    hrs, hrs > 1 ? "s" : "");
500 				if (mins > 0)
501 					(void)printf(" %d min%s,",
502 					    mins, mins > 1 ? "s" : "");
503 			}
504 		}
505 	}
506 
507 	/* Print number of users logged in to system */
508 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
509 
510 	/*
511 	 * Print 1, 5, and 15 minute load averages.
512 	 */
513 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
514 		(void)printf(", no load average information available\n");
515 	else {
516 		(void)printf(", load averages:");
517 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
518 			if (i > 0)
519 				(void)printf(",");
520 			(void)printf(" %.2f", avenrun[i]);
521 		}
522 		(void)printf("\n");
523 	}
524 }
525 
526 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
527 static struct stat *
528 ttystat(char *line)
529 {
530 	static struct stat sb;
531 	char ttybuf[MAXPATHLEN];
532 
533 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
534 	if (stat(ttybuf, &sb))
535 		return (NULL);
536 	return (&sb);
537 }
538 
539 static void
540 process(struct entry *ep)
541 {
542 	struct stat *stp;
543 	time_t touched;
544 	int max;
545 
546 	if ((max = strlen(ep->name)) > maxname)
547 		maxname = max;
548 	if ((max = strlen(ep->line)) > maxline)
549 		maxline = max;
550 	if ((max = strlen(ep->host)) > maxhost)
551 		maxhost = max;
552 
553 
554 #ifdef SUPPORT_UTMP
555 	/*
556 	 * Hack to recognize and correctly parse
557 	 * ut entry made by ftpd. The "tty" used
558 	 * by ftpd is not a real tty, just identifier in
559 	 * form ftpSUPPORT_ID. Pid parsed from the "tty name"
560 	 * is used later to match corresponding process.
561 	 * NB: This is only used for utmp entries. For utmpx,
562 	 * we already have the pid.
563 	 */
564 	if (ep->pid == 0 && strncmp(ep->line, "ftp", 3) == 0) {
565 		ep->pid = strtol(ep->line + 3, NULL, 10);
566 		return;
567 	}
568 #endif
569 	if ((stp = ttystat(ep->line)) == NULL)
570 		return;
571 
572 	ep->tdev = stp->st_rdev;
573 	/*
574 	 * If this is the console device, attempt to ascertain
575 	 * the true console device dev_t.
576 	 */
577 	if (ep->tdev == 0) {
578 		int mib[2];
579 		size_t size;
580 
581 		mib[0] = CTL_KERN;
582 		mib[1] = KERN_CONSDEV;
583 		size = sizeof(dev_t);
584 		(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
585 	}
586 
587 	touched = stp->st_atime;
588 	if (touched < ep->tv.tv_sec) {
589 		/* tty untouched since before login */
590 		touched = ep->tv.tv_sec;
591 	}
592 	if ((ep->idle = now - touched) < 0)
593 		ep->idle = 0;
594 }
595 #endif
596 
597 static void
598 usage(int wcmd)
599 {
600 
601 	if (wcmd)
602 		(void)fprintf(stderr,
603 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
604 	else
605 		(void)fprintf(stderr, "uptime\n");
606 	exit(1);
607 }
608