Home | History | Annotate | Line # | Download | only in w
w.c revision 1.27
      1 /*	$NetBSD: w.c,v 1.27 1997/10/20 03:08:45 lukem 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.27 1997/10/20 03:08:45 lukem 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/time.h>
     58 #include <sys/stat.h>
     59 #include <sys/sysctl.h>
     60 #include <sys/proc.h>
     61 #include <sys/user.h>
     62 #include <sys/ioctl.h>
     63 #include <sys/socket.h>
     64 #include <sys/tty.h>
     65 
     66 #include <machine/cpu.h>
     67 #include <netinet/in.h>
     68 #include <arpa/inet.h>
     69 
     70 #include <ctype.h>
     71 #include <err.h>
     72 #include <errno.h>
     73 #include <fcntl.h>
     74 #include <kvm.h>
     75 #include <limits.h>
     76 #include <netdb.h>
     77 #include <nlist.h>
     78 #include <paths.h>
     79 #include <stdio.h>
     80 #include <stdlib.h>
     81 #include <string.h>
     82 #include <tzfile.h>
     83 #include <unistd.h>
     84 #include <utmp.h>
     85 #include <vis.h>
     86 
     87 #include "extern.h"
     88 
     89 struct timeval	boottime;
     90 struct utmp	utmp;
     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 */
     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];
    102 
    103 /*
    104  * One of these per active utmp entry.
    105  */
    106 struct	entry {
    107 	struct	entry *next;
    108 	struct	utmp utmp;
    109 	dev_t	tdev;		/* dev_t of terminal */
    110 	time_t	idle;		/* idle time of terminal in seconds */
    111 	struct	kinfo_proc *kp;	/* `most interesting' proc */
    112 } *ep, *ehead = NULL, **nextp = &ehead;
    113 
    114 static void	 pr_args __P((struct kinfo_proc *));
    115 static void	 pr_header __P((time_t *, int));
    116 static struct stat
    117 		*ttystat __P((char *));
    118 static void	 usage __P((int));
    119 int	main __P((int, char **));
    120 
    121 int
    122 main(argc, argv)
    123 	int argc;
    124 	char **argv;
    125 {
    126 	extern char *__progname;
    127 	struct kinfo_proc *kp;
    128 	struct hostent *hp;
    129 	struct stat *stp;
    130 	FILE *ut;
    131 	struct in_addr l;
    132 	int ch, i, nentries, nusers, wcmd;
    133 	char *memf, *nlistf, *p, *x;
    134 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
    135 
    136 	/* Are we w(1) or uptime(1)? */
    137 	p = __progname;
    138 	if (*p == '-')
    139 		p++;
    140 	if (*p == 'u') {
    141 		wcmd = 0;
    142 		p = "";
    143 	} else {
    144 		wcmd = 1;
    145 		p = "hiflM:N:nsuw";
    146 	}
    147 
    148 	memf = nlistf = NULL;
    149 	while ((ch = getopt(argc, argv, p)) != -1)
    150 		switch (ch) {
    151 		case 'h':
    152 			header = 0;
    153 			break;
    154 		case 'i':
    155 			sortidle = 1;
    156 			break;
    157 		case 'M':
    158 			header = 0;
    159 			memf = optarg;
    160 			break;
    161 		case 'N':
    162 			nlistf = optarg;
    163 			break;
    164 		case 'n':
    165 			nflag = 1;
    166 			break;
    167 		case 'f': case 'l': case 's': case 'u': case 'w':
    168 			warnx("[-flsuw] no longer supported");
    169 			/* FALLTHROUGH */
    170 		case '?':
    171 		default:
    172 			usage(wcmd);
    173 		}
    174 	argc -= optind;
    175 	argv += optind;
    176 
    177 	/*
    178 	 * Discard setgid privelidges if not the running kernel so that
    179 	 * bad guys can't print interesting stuff from kernel memory.
    180 	 */
    181 	if (nlistf != NULL || memf != NULL)
    182 		setgid(getgid());
    183 
    184 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
    185 		errx(1, "%s", errbuf);
    186 
    187 	(void)time(&now);
    188 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
    189 		err(1, "%s", _PATH_UTMP);
    190 
    191 	if (*argv)
    192 		sel_user = *argv;
    193 
    194 	for (nusers = 0; 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, "%s", "");
    203 		*nextp = ep;
    204 		nextp = &(ep->next);
    205 		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
    206 		if (!(stp = ttystat(ep->utmp.ut_line)))
    207 			continue;
    208 		ep->tdev = stp->st_rdev;
    209 #ifdef CPU_CONSDEV
    210 		/*
    211 		 * If this is the console device, attempt to ascertain
    212 		 * the true console device dev_t.
    213 		 */
    214 		if (ep->tdev == 0) {
    215 			int mib[2];
    216 			size_t size;
    217 
    218 			mib[0] = CTL_MACHDEP;
    219 			mib[1] = CPU_CONSDEV;
    220 			size = sizeof(dev_t);
    221 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
    222 		}
    223 #endif
    224 		if ((ep->idle = now - stp->st_atime) < 0)
    225 			ep->idle = 0;
    226 	}
    227 	(void)fclose(ut);
    228 
    229 	if (header || wcmd == 0) {
    230 		pr_header(&now, nusers);
    231 		if (wcmd == 0)
    232 			exit (0);
    233 	}
    234 
    235 #define HEADER	"USER    TTY FROM              LOGIN@  IDLE WHAT\n"
    236 #define WUSED	(sizeof (HEADER) - sizeof ("WHAT\n"))
    237 	(void)printf(HEADER);
    238 
    239 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
    240 		errx(1, "%s", kvm_geterr(kd));
    241 	for (i = 0; i < nentries; i++, kp++) {
    242 		struct proc *p = &kp->kp_proc;
    243 		struct eproc *e;
    244 
    245 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
    246 			continue;
    247 		e = &kp->kp_eproc;
    248 		for (ep = ehead; ep != NULL; ep = ep->next) {
    249 			if (ep->tdev == e->e_tdev && e->e_pgid == e->e_tpgid) {
    250 				/*
    251 				 * Proc is in foreground of this terminal
    252 				 */
    253 				if (proc_compare(&ep->kp->kp_proc, p))
    254 					ep->kp = kp;
    255 				break;
    256 			}
    257 		}
    258 	}
    259 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
    260 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
    261 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
    262 	       ttywidth = 79;
    263         else
    264 	       ttywidth = ws.ws_col - 1;
    265 	argwidth = ttywidth - WUSED;
    266 	if (argwidth < 4)
    267 		argwidth = 8;
    268 	/* sort by idle time */
    269 	if (sortidle && ehead != NULL) {
    270 		struct entry *from = ehead, *save;
    271 
    272 		ehead = NULL;
    273 		while (from != NULL) {
    274 			for (nextp = &ehead;
    275 			    (*nextp) && from->idle >= (*nextp)->idle;
    276 			    nextp = &(*nextp)->next)
    277 				continue;
    278 			save = from;
    279 			from = from->next;
    280 			save->next = *nextp;
    281 			*nextp = save;
    282 		}
    283 	}
    284 
    285 	if (!nflag)
    286 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
    287 		    (p = strchr(domain, '.')) == 0)
    288 			domain[0] = '\0';
    289 		else {
    290 			domain[sizeof(domain) - 1] = '\0';
    291 			memmove(domain, p, strlen(p) + 1);
    292 		}
    293 
    294 	for (ep = ehead; ep != NULL; ep = ep->next) {
    295 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
    296 		for (x = p; x < p + UT_HOSTSIZE; x++)
    297 			if (*x == '\0' || *x == ':')
    298 				break;
    299 		if (x == p + UT_HOSTSIZE || *x != ':')
    300 			x = NULL;
    301 		else
    302 			*x++ = '\0';
    303 
    304 		if (!nflag && inet_aton(p, &l) &&
    305 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
    306 			if (domain[0] != '\0') {
    307 				p = hp->h_name;
    308 				p += strlen(hp->h_name);
    309 				p -= strlen(domain);
    310 				if (p > hp->h_name && strcmp(p, domain) == 0)
    311 					*p = '\0';
    312 			}
    313 			p = hp->h_name;
    314 		}
    315 		if (x) {
    316 			(void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
    317 			    (int)(ep->utmp.ut_host + UT_HOSTSIZE - x), x);
    318 			p = buf;
    319 		}
    320 		(void)printf("%-*.*s %-2.2s %-*.*s ",
    321 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
    322 		    strncmp(ep->utmp.ut_line, "tty", 3) ?
    323 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
    324 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
    325 		pr_attime(&ep->utmp.ut_time, &now);
    326 		pr_idle(ep->idle);
    327 		pr_args(ep->kp);
    328 		printf("\n");
    329 	}
    330 	exit(0);
    331 }
    332 
    333 static void
    334 pr_args(kp)
    335 	struct kinfo_proc *kp;
    336 {
    337 	char **argv;
    338 	int left;
    339 
    340 	if (kp == 0)
    341 		goto nothing;
    342 	left = argwidth;
    343 	argv = kvm_getargv(kd, kp, argwidth);
    344 	if (argv == 0)
    345 		goto nothing;
    346 	while (*argv) {
    347 		fmt_puts(*argv, &left);
    348 		argv++;
    349 		fmt_putc(' ', &left);
    350 	}
    351 	return;
    352 nothing:
    353 	putchar('-');
    354 }
    355 
    356 static void
    357 pr_header(nowp, nusers)
    358 	time_t *nowp;
    359 	int nusers;
    360 {
    361 	double avenrun[3];
    362 	time_t uptime;
    363 	int days, hrs, i, mins;
    364 	int mib[2];
    365 	size_t size;
    366 	char buf[256];
    367 
    368 	/*
    369 	 * Print time of day.
    370 	 *
    371 	 * SCCS forces the string manipulation below, as it replaces
    372 	 * %, M, and % in a character string with the file name.
    373 	 */
    374 	(void)strftime(buf, sizeof(buf),
    375 	    __CONCAT("%l:%","M%p"), localtime(nowp));
    376 	buf[sizeof(buf) - 1] = '\0';
    377 	(void)printf("%s ", buf);
    378 
    379 	/*
    380 	 * Print how long system has been up.
    381 	 * (Found by looking getting "boottime" from the kernel)
    382 	 */
    383 	mib[0] = CTL_KERN;
    384 	mib[1] = KERN_BOOTTIME;
    385 	size = sizeof(boottime);
    386 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
    387 	    boottime.tv_sec != 0) {
    388 		uptime = now - boottime.tv_sec;
    389 		uptime += 30;
    390 		if (uptime > SECSPERMIN) {
    391 			days = uptime / SECSPERDAY;
    392 			uptime %= SECSPERDAY;
    393 			hrs = uptime / SECSPERHOUR;
    394 			uptime %= SECSPERHOUR;
    395 			mins = uptime / SECSPERMIN;
    396 			(void)printf(" up");
    397 			if (days > 0)
    398 				(void)printf(" %d day%s,", days,
    399 				    days > 1 ? "s" : "");
    400 			if (hrs > 0 && mins > 0)
    401 				(void)printf(" %2d:%02d,", hrs, mins);
    402 			else {
    403 				if (hrs > 0)
    404 					(void)printf(" %d hr%s,",
    405 					    hrs, hrs > 1 ? "s" : "");
    406 				if (mins > 0)
    407 					(void)printf(" %d min%s,",
    408 					    mins, mins > 1 ? "s" : "");
    409 			}
    410 		}
    411 	}
    412 
    413 	/* Print number of users logged in to system */
    414 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
    415 
    416 	/*
    417 	 * Print 1, 5, and 15 minute load averages.
    418 	 */
    419 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
    420 		(void)printf(", no load average information available\n");
    421 	else {
    422 		(void)printf(", load averages:");
    423 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
    424 			if (i > 0)
    425 				(void)printf(",");
    426 			(void)printf(" %.2f", avenrun[i]);
    427 		}
    428 		(void)printf("\n");
    429 	}
    430 }
    431 
    432 static struct stat *
    433 ttystat(line)
    434 	char *line;
    435 {
    436 	static struct stat sb;
    437 	char ttybuf[MAXPATHLEN];
    438 
    439 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
    440 	if (stat(ttybuf, &sb))
    441 		return (NULL);
    442 	return (&sb);
    443 }
    444 
    445 static void
    446 usage(wcmd)
    447 	int wcmd;
    448 {
    449 	if (wcmd)
    450 		(void)fprintf(stderr,
    451 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
    452 	else
    453 		(void)fprintf(stderr, "uptime\n");
    454 	exit (1);
    455 }
    456