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