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