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