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