Home | History | Annotate | Line # | Download | only in w
w.c revision 1.44
      1 /*	$NetBSD: w.c,v 1.44 2001/01/05 04:54:53 mjl 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.44 2001/01/05 04:54:53 mjl 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 #include <utmp.h>
     85 #include <vis.h>
     86 
     87 #include "extern.h"
     88 
     89 #define	max(a,b)	(((a)>(b))?(a):(b))
     90 
     91 struct timeval	boottime;
     92 struct utmp	utmp;
     93 struct winsize	ws;
     94 kvm_t	       *kd;
     95 time_t		now;		/* the current time of day */
     96 time_t		uptime;		/* time of last reboot & elapsed time since */
     97 int		ttywidth;	/* width of tty */
     98 int		argwidth;	/* width of tty left to print process args */
     99 int		header = 1;	/* true if -h flag: don't print heading */
    100 int		nflag;		/* true if -n flag: don't convert addrs */
    101 int		sortidle;	/* sort bu idle time */
    102 char	       *sel_user;	/* login of particular user selected */
    103 char		domain[MAXHOSTNAMELEN + 1];
    104 
    105 /*
    106  * One of these per active utmp entry.
    107  */
    108 struct	entry {
    109 	struct	entry *next;
    110 	struct	utmp utmp;
    111 	dev_t	tdev;			/* dev_t of terminal */
    112 	time_t	idle;			/* idle time of terminal in seconds */
    113 	struct	kinfo_proc2 *kp;	/* `most interesting' proc */
    114 #ifdef SUPPORT_FTPD_UTMP
    115 	pid_t	ftpd_pid;		/* pid as extracted from ftpd's entry */
    116 #endif
    117 } *ep, *ehead = NULL, **nextp = &ehead;
    118 
    119 static void	 pr_args __P((struct kinfo_proc2 *));
    120 static void	 pr_header __P((time_t *, int));
    121 static struct stat
    122 		*ttystat __P((char *, size_t));
    123 static void	 usage __P((int));
    124 int	main __P((int, char **));
    125 
    126 int
    127 main(argc, argv)
    128 	int argc;
    129 	char **argv;
    130 {
    131 	extern char *__progname;
    132 	struct kinfo_proc2 *kp;
    133 	struct hostent *hp;
    134 	struct stat *stp;
    135 	FILE *ut;
    136 	struct in_addr l;
    137 	time_t touched;
    138 	int ch, i, nentries, nusers, wcmd, lognamelen;
    139 	char *memf, *nlistf, *p, *x;
    140 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
    141 
    142 	/* Are we w(1) or uptime(1)? */
    143 	p = __progname;
    144 	if (*p == '-')
    145 		p++;
    146 	if (*p == 'u') {
    147 		wcmd = 0;
    148 		p = "";
    149 	} else {
    150 		wcmd = 1;
    151 		p = "hiflM:N:nsuw";
    152 	}
    153 
    154 	memf = nlistf = NULL;
    155 	while ((ch = getopt(argc, argv, p)) != -1)
    156 		switch (ch) {
    157 		case 'h':
    158 			header = 0;
    159 			break;
    160 		case 'i':
    161 			sortidle = 1;
    162 			break;
    163 		case 'M':
    164 			header = 0;
    165 			memf = optarg;
    166 			break;
    167 		case 'N':
    168 			nlistf = optarg;
    169 			break;
    170 		case 'n':
    171 			nflag = 1;
    172 			break;
    173 		case 'f': case 'l': case 's': case 'u': case 'w':
    174 			warnx("[-flsuw] no longer supported");
    175 			/* FALLTHROUGH */
    176 		case '?':
    177 		default:
    178 			usage(wcmd);
    179 		}
    180 	argc -= optind;
    181 	argv += optind;
    182 
    183 	if ((kd = kvm_openfiles(nlistf, memf, NULL,
    184 	    memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
    185 		errx(1, "%s", errbuf);
    186 
    187 	(void)time(&now);
    188 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL && wcmd)
    189 		err(1, "%s", _PATH_UTMP);
    190 
    191 	if (*argv)
    192 		sel_user = *argv;
    193 
    194 	for (nusers = 0; ut && fread(&utmp, sizeof(utmp), 1, ut);) {
    195 		if (utmp.ut_name[0] == '\0')
    196 			continue;
    197 		++nusers;
    198 		if (wcmd == 0 || (sel_user &&
    199 		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
    200 			continue;
    201 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
    202 			err(1, NULL);
    203 		*nextp = ep;
    204 		nextp = &(ep->next);
    205 		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
    206 		if (!(stp = ttystat(ep->utmp.ut_line, UT_LINESIZE))) {
    207 #ifdef SUPPORT_FTPD_UTMP
    208 			/*
    209 			 * Hack to recognize and correctly parse
    210 			 * utmp entry made by ftpd. The "tty" used
    211 			 * by ftpd is not a real tty, just identifier in
    212 			 * form ftpPROCESS_ID. Pid parsed from the "tty name"
    213 			 * is used later to match corresponding process.
    214 			 */
    215 			if (strncmp(ep->utmp.ut_line, "ftp", 3) == 0)
    216 				ep->ftpd_pid =
    217 					strtol(ep->utmp.ut_line + 3, NULL, 10);
    218 #endif /* SUPPORT_FTPD_UTMP */
    219 
    220 			continue;
    221 		}
    222 		ep->tdev = stp->st_rdev;
    223 		/*
    224 		 * If this is the console device, attempt to ascertain
    225 		 * the true console device dev_t.
    226 		 */
    227 		if (ep->tdev == 0) {
    228 			int mib[2];
    229 			size_t size;
    230 
    231 			mib[0] = CTL_KERN;
    232 			mib[1] = KERN_CONSDEV;
    233 			size = sizeof(dev_t);
    234 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
    235 		}
    236 
    237 		touched = stp->st_atime;
    238 		if (touched < ep->utmp.ut_time) {
    239 				/* tty untouched since before login */
    240 				touched = ep->utmp.ut_time;
    241 			}
    242 	if ((ep->idle = now - touched) < 0)
    243 			ep->idle = 0;
    244 	}
    245 	if (ut)
    246 		(void)fclose(ut);
    247 	else
    248 		nusers = 1;
    249 
    250 	if (header || wcmd == 0) {
    251 		pr_header(&now, nusers);
    252 		if (wcmd == 0)
    253 			exit (0);
    254 	}
    255 
    256 	if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
    257 	    sizeof(struct kinfo_proc2), &nentries)) == NULL)
    258 		errx(1, "%s", kvm_geterr(kd));
    259 
    260 	/* Include trailing space because TTY header starts one column early. */
    261 	lognamelen = sizeof("USER ") - 1 /* NUL */;
    262 	for (i = 0; i < nentries; i++, kp++) {
    263 
    264 		if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
    265 			continue;
    266 
    267 		for (ep = ehead; ep != NULL; ep = ep->next) {
    268 			if (ep->tdev == kp->p_tdev
    269 				&& kp->p__pgid == kp->p_tpgid) {
    270 				/*
    271 				 * Proc is in foreground of this terminal
    272 				 */
    273 				if (proc_compare(ep->kp, kp)) {
    274 					ep->kp = kp;
    275 					lognamelen = max(lognamelen,
    276 					    strlen(kp->p_login));
    277 				}
    278 				break;
    279 			}
    280 #ifdef SUPPORT_FTPD_UTMP
    281 			/*
    282 			 * Hack to match process to ftp utmp entry.
    283 			 */
    284 			else if (ep->tdev == 0 && kp->p_tdev == NODEV
    285 				 && ep->ftpd_pid == kp->p_pid) {
    286 				ep->kp = kp;
    287 				lognamelen = max(lognamelen,
    288 					    strlen(kp->p_login));
    289 			}
    290 #endif /* SUPPORT_FTPD_UTMP */
    291 		}
    292 	}
    293 
    294 	argwidth = printf("%-*sTTY %-*s %*s  IDLE WHAT\n",
    295 	    lognamelen, "USER", UT_HOSTSIZE, "FROM",
    296 	    7 /* "dddhhXm" */, "LOGIN@");
    297 	argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
    298 
    299 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
    300 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
    301 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
    302 	       ttywidth = 79;
    303         else
    304 	       ttywidth = ws.ws_col - 1;
    305 	argwidth = ttywidth - argwidth;
    306 	if (argwidth < 4)
    307 		argwidth = 8;
    308 	/* sort by idle time */
    309 	if (sortidle && ehead != NULL) {
    310 		struct entry *from = ehead, *save;
    311 
    312 		ehead = NULL;
    313 		while (from != NULL) {
    314 			for (nextp = &ehead;
    315 			    (*nextp) && from->idle >= (*nextp)->idle;
    316 			    nextp = &(*nextp)->next)
    317 				continue;
    318 			save = from;
    319 			from = from->next;
    320 			save->next = *nextp;
    321 			*nextp = save;
    322 		}
    323 	}
    324 
    325 	if (!nflag) {
    326 		int	rv;
    327 
    328 		rv = gethostname(domain, sizeof(domain));
    329 		domain[sizeof(domain) - 1] = '\0';
    330 		if (rv < 0 || (p = strchr(domain, '.')) == 0)
    331 			domain[0] = '\0';
    332 		else
    333 			memmove(domain, p, strlen(p) + 1);
    334 	}
    335 
    336 	for (ep = ehead; ep != NULL; ep = ep->next) {
    337 		char host_buf[UT_HOSTSIZE + 1];
    338 
    339 		host_buf[UT_HOSTSIZE] = '\0';
    340 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
    341 		p = *host_buf ? host_buf : "-";
    342 
    343 		for (x = p; x < p + UT_HOSTSIZE; x++)
    344 			if (*x == '\0' || *x == ':')
    345 				break;
    346 		if (x == p + UT_HOSTSIZE || *x != ':')
    347 			x = NULL;
    348 		else
    349 			*x++ = '\0';
    350 
    351 		if (!nflag && inet_aton(p, &l) &&
    352 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
    353 			if (domain[0] != '\0') {
    354 				p = hp->h_name;
    355 				p += strlen(hp->h_name);
    356 				p -= strlen(domain);
    357 				if (p > hp->h_name && strcasecmp(p, domain) == 0)
    358 					*p = '\0';
    359 			}
    360 			p = hp->h_name;
    361 		}
    362 		if (x) {
    363 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
    364 			p = buf;
    365 		}
    366 		if (ep->kp == NULL) {
    367 		    warnx("Stale utmp entry: %.*s %.*s %.*s",
    368 			UT_NAMESIZE, ep->utmp.ut_name,
    369 			UT_LINESIZE, ep->utmp.ut_line,
    370 			UT_HOSTSIZE, ep->utmp.ut_host);
    371 		    continue;
    372 		}
    373 		(void)printf("%-*s %-2.2s %-*.*s ",
    374 		    lognamelen, ep->kp->p_login,
    375 		    (strncmp(ep->utmp.ut_line, "tty", 3) &&
    376 		    strncmp(ep->utmp.ut_line, "dty", 3)) ?
    377 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
    378 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
    379 		pr_attime(&ep->utmp.ut_time, &now);
    380 		pr_idle(ep->idle);
    381 		pr_args(ep->kp);
    382 		(void)printf("\n");
    383 	}
    384 	exit(0);
    385 }
    386 
    387 static void
    388 pr_args(kp)
    389 	struct kinfo_proc2 *kp;
    390 {
    391 	char **argv;
    392 	int left;
    393 
    394 	if (kp == 0)
    395 		goto nothing;
    396 	left = argwidth;
    397 	argv = kvm_getargv2(kd, kp, argwidth);
    398 	if (argv == 0)
    399 		goto nothing;
    400 	while (*argv) {
    401 		fmt_puts(*argv, &left);
    402 		argv++;
    403 		fmt_putc(' ', &left);
    404 	}
    405 	return;
    406 nothing:
    407 	putchar('-');
    408 }
    409 
    410 static void
    411 pr_header(nowp, nusers)
    412 	time_t *nowp;
    413 	int nusers;
    414 {
    415 	double avenrun[3];
    416 	time_t uptime;
    417 	int days, hrs, i, mins;
    418 	int mib[2];
    419 	size_t size;
    420 	char buf[256];
    421 
    422 	/*
    423 	 * Print time of day.
    424 	 *
    425 	 * SCCS forces the string manipulation below, as it replaces
    426 	 * %, M, and % in a character string with the file name.
    427 	 */
    428 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
    429 	buf[sizeof(buf) - 1] = '\0';
    430 	(void)printf("%s ", buf);
    431 
    432 	/*
    433 	 * Print how long system has been up.
    434 	 * (Found by looking getting "boottime" from the kernel)
    435 	 */
    436 	mib[0] = CTL_KERN;
    437 	mib[1] = KERN_BOOTTIME;
    438 	size = sizeof(boottime);
    439 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
    440 	    boottime.tv_sec != 0) {
    441 		uptime = now - boottime.tv_sec;
    442 		uptime += 30;
    443 		if (uptime > SECSPERMIN) {
    444 			days = uptime / SECSPERDAY;
    445 			uptime %= SECSPERDAY;
    446 			hrs = uptime / SECSPERHOUR;
    447 			uptime %= SECSPERHOUR;
    448 			mins = uptime / SECSPERMIN;
    449 			(void)printf(" up");
    450 			if (days > 0)
    451 				(void)printf(" %d day%s,", days,
    452 				    days > 1 ? "s" : "");
    453 			if (hrs > 0 && mins > 0)
    454 				(void)printf(" %2d:%02d,", hrs, mins);
    455 			else {
    456 				if (hrs > 0)
    457 					(void)printf(" %d hr%s,",
    458 					    hrs, hrs > 1 ? "s" : "");
    459 				if (mins > 0)
    460 					(void)printf(" %d min%s,",
    461 					    mins, mins > 1 ? "s" : "");
    462 			}
    463 		}
    464 	}
    465 
    466 	/* Print number of users logged in to system */
    467 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
    468 
    469 	/*
    470 	 * Print 1, 5, and 15 minute load averages.
    471 	 */
    472 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
    473 		(void)printf(", no load average information available\n");
    474 	else {
    475 		(void)printf(", load averages:");
    476 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
    477 			if (i > 0)
    478 				(void)printf(",");
    479 			(void)printf(" %.2f", avenrun[i]);
    480 		}
    481 		(void)printf("\n");
    482 	}
    483 }
    484 
    485 static struct stat *
    486 ttystat(line, sz)
    487 	char *line;
    488 	size_t sz;
    489 {
    490 	static struct stat sb;
    491 	char ttybuf[MAXPATHLEN];
    492 
    493 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, (int) sz, line);
    494 	if (stat(ttybuf, &sb))
    495 		return (NULL);
    496 	return (&sb);
    497 }
    498 
    499 static void
    500 usage(wcmd)
    501 	int wcmd;
    502 {
    503 	if (wcmd)
    504 		(void)fprintf(stderr,
    505 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
    506 	else
    507 		(void)fprintf(stderr, "uptime\n");
    508 	exit(1);
    509 }
    510