Home | History | Annotate | Line # | Download | only in w
w.c revision 1.12
      1 /*-
      2  * Copyright (c) 1980, 1991, 1993, 1994
      3  *	The Regents of the University of California.  All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  * 1. Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  * 2. Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in the
     12  *    documentation and/or other materials provided with the distribution.
     13  * 3. All advertising materials mentioning features or use of this software
     14  *    must display the following acknowledgement:
     15  *	This product includes software developed by the University of
     16  *	California, Berkeley and its contributors.
     17  * 4. Neither the name of the University nor the names of its contributors
     18  *    may be used to endorse or promote products derived from this software
     19  *    without specific prior written permission.
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     31  * SUCH DAMAGE.
     32  */
     33 
     34 #ifndef lint
     35 static char copyright[] =
     36 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
     37 	The Regents of the University of California.  All rights reserved.\n";
     38 #endif /* not lint */
     39 
     40 #ifndef lint
     41 static char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
     42 #endif /* not lint */
     43 
     44 /*
     45  * w - print system status (who and what)
     46  *
     47  * This program is similar to the systat command on Tenex/Tops 10/20
     48  *
     49  */
     50 #include <sys/param.h>
     51 #include <sys/time.h>
     52 #include <sys/stat.h>
     53 #include <sys/sysctl.h>
     54 #include <sys/proc.h>
     55 #include <sys/user.h>
     56 #include <sys/ioctl.h>
     57 #include <sys/socket.h>
     58 #include <sys/tty.h>
     59 
     60 #include <machine/cpu.h>
     61 #include <netinet/in.h>
     62 #include <arpa/inet.h>
     63 
     64 #include <ctype.h>
     65 #include <err.h>
     66 #include <errno.h>
     67 #include <fcntl.h>
     68 #include <kvm.h>
     69 #include <netdb.h>
     70 #include <nlist.h>
     71 #include <paths.h>
     72 #include <stdio.h>
     73 #include <stdlib.h>
     74 #include <string.h>
     75 #include <tzfile.h>
     76 #include <unistd.h>
     77 #include <utmp.h>
     78 #include <vis.h>
     79 
     80 #include "extern.h"
     81 
     82 struct timeval	boottime;
     83 struct utmp	utmp;
     84 struct winsize	ws;
     85 kvm_t	       *kd;
     86 time_t		now;		/* the current time of day */
     87 time_t		uptime;		/* time of last reboot & elapsed time since */
     88 int		ttywidth;	/* width of tty */
     89 int		argwidth;	/* width of tty */
     90 int		header = 1;	/* true if -h flag: don't print heading */
     91 int		nflag;		/* true if -n flag: don't convert addrs */
     92 int		sortidle;	/* sort bu idle time */
     93 char	       *sel_user;	/* login of particular user selected */
     94 char		domain[MAXHOSTNAMELEN];
     95 
     96 /*
     97  * One of these per active utmp entry.
     98  */
     99 struct	entry {
    100 	struct	entry *next;
    101 	struct	utmp utmp;
    102 	dev_t	tdev;		/* dev_t of terminal */
    103 	time_t	idle;		/* idle time of terminal in seconds */
    104 	struct	kinfo_proc *kp;	/* `most interesting' proc */
    105 	char	*args;		/* arg list of interesting process */
    106 } *ep, *ehead = NULL, **nextp = &ehead;
    107 
    108 static void	 pr_header __P((time_t *, int));
    109 static struct stat
    110 		*ttystat __P((char *));
    111 static void	 usage __P((int));
    112 
    113 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
    114 
    115 int
    116 main(argc, argv)
    117 	int argc;
    118 	char **argv;
    119 {
    120 	extern char *__progname;
    121 	struct kinfo_proc *kp;
    122 	struct hostent *hp;
    123 	struct stat *stp;
    124 	FILE *ut;
    125 	u_long l;
    126 	size_t arglen;
    127 	int ch, i, nentries, nusers, wcmd;
    128 	char *memf, *nlistf, *p, *vis_args, *x;
    129 	char buf[MAXHOSTNAMELEN], errbuf[256];
    130 
    131 	/* Are we w(1) or uptime(1)? */
    132 	p = __progname;
    133 	if (*p == '-')
    134 		p++;
    135 	if (*p == 'u') {
    136 		wcmd = 0;
    137 		p = "";
    138 	} else {
    139 		wcmd = 1;
    140 		p = "hiflM:N:nsuw";
    141 	}
    142 
    143 	memf = nlistf = NULL;
    144 	while ((ch = getopt(argc, argv, p)) != EOF)
    145 		switch (ch) {
    146 		case 'h':
    147 			header = 0;
    148 			break;
    149 		case 'i':
    150 			sortidle = 1;
    151 			break;
    152 		case 'M':
    153 			header = 0;
    154 			memf = optarg;
    155 			break;
    156 		case 'N':
    157 			nlistf = optarg;
    158 			break;
    159 		case 'n':
    160 			nflag = 1;
    161 			break;
    162 		case 'f': case 'l': case 's': case 'u': case 'w':
    163 			warnx("[-flsuw] no longer supported");
    164 			/* FALLTHROUGH */
    165 		case '?':
    166 		default:
    167 			usage(wcmd);
    168 		}
    169 	argc -= optind;
    170 	argv += optind;
    171 
    172 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
    173 		errx(1, "%s", errbuf);
    174 
    175 	(void)time(&now);
    176 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
    177 		err(1, "%s", _PATH_UTMP);
    178 
    179 	if (*argv)
    180 		sel_user = *argv;
    181 
    182 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
    183 		if (utmp.ut_name[0] == '\0')
    184 			continue;
    185 		++nusers;
    186 		if (wcmd == 0 || (sel_user &&
    187 		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
    188 			continue;
    189 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
    190 			err(1, NULL);
    191 		*nextp = ep;
    192 		nextp = &(ep->next);
    193 		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
    194 		stp = ttystat(ep->utmp.ut_line);
    195 		ep->tdev = stp->st_rdev;
    196 #ifdef CPU_CONSDEV
    197 		/*
    198 		 * If this is the console device, attempt to ascertain
    199 		 * the true console device dev_t.
    200 		 */
    201 		if (ep->tdev == 0) {
    202 			int mib[2];
    203 			size_t size;
    204 
    205 			mib[0] = CTL_MACHDEP;
    206 			mib[1] = CPU_CONSDEV;
    207 			size = sizeof(dev_t);
    208 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
    209 		}
    210 #endif
    211 		if ((ep->idle = now - stp->st_atime) < 0)
    212 			ep->idle = 0;
    213 	}
    214 	(void)fclose(ut);
    215 
    216 	if (header || wcmd == 0) {
    217 		pr_header(&now, nusers);
    218 		if (wcmd == 0)
    219 			exit (0);
    220 	}
    221 
    222 #define HEADER	"USER    TTY FROM              LOGIN@  IDLE WHAT\n"
    223 #define WUSED	(sizeof (HEADER) - sizeof ("WHAT\n"))
    224 	(void)printf(HEADER);
    225 
    226 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
    227 		err(1, "%s", kvm_geterr(kd));
    228 	for (i = 0; i < nentries; i++, kp++) {
    229 		struct proc *p = &kp->kp_proc;
    230 		struct eproc *e;
    231 
    232 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
    233 			continue;
    234 		e = &kp->kp_eproc;
    235 		for (ep = ehead; ep != NULL; ep = ep->next) {
    236 			if (ep->tdev == e->e_tdev && e->e_pgid == e->e_tpgid) {
    237 				/*
    238 				 * Proc is in foreground of this terminal
    239 				 */
    240 				if (proc_compare(&ep->kp->kp_proc, p))
    241 					ep->kp = kp;
    242 				break;
    243 			}
    244 		}
    245 	}
    246 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
    247 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
    248 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
    249 	       ttywidth = 79;
    250         else
    251 	       ttywidth = ws.ws_col - 1;
    252 	argwidth = ttywidth - WUSED;
    253 	if (argwidth < 4)
    254 		argwidth = 8;
    255 	for (ep = ehead; ep != NULL; ep = ep->next) {
    256 		if (ep->kp == NULL) {
    257 			ep->args = "-";
    258 			continue;
    259 		}
    260 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
    261 		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
    262 		if (ep->args == NULL)
    263 			err(1, NULL);
    264 	}
    265 	/* sort by idle time */
    266 	if (sortidle && ehead != NULL) {
    267 		struct entry *from = ehead, *save;
    268 
    269 		ehead = NULL;
    270 		while (from != NULL) {
    271 			for (nextp = &ehead;
    272 			    (*nextp) && from->idle >= (*nextp)->idle;
    273 			    nextp = &(*nextp)->next)
    274 				continue;
    275 			save = from;
    276 			from = from->next;
    277 			save->next = *nextp;
    278 			*nextp = save;
    279 		}
    280 	}
    281 
    282 	if (!nflag)
    283 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
    284 		    (p = strchr(domain, '.')) == 0)
    285 			domain[0] = '\0';
    286 		else {
    287 			domain[sizeof(domain) - 1] = '\0';
    288 			memmove(domain, p, strlen(p) + 1);
    289 		}
    290 
    291 	if ((vis_args = malloc(argwidth * 4 + 1)) == NULL)
    292 		err(1, NULL);
    293 	for (ep = ehead; ep != NULL; ep = ep->next) {
    294 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
    295 		if ((x = strchr(p, ':')) != NULL)
    296 			*x++ = '\0';
    297 		if (!nflag && isdigit(*p) &&
    298 		    (long)(l = inet_addr(p)) != -1 &&
    299 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
    300 			if (domain[0] != '\0') {
    301 				p = hp->h_name;
    302 				p += strlen(hp->h_name);
    303 				p -= strlen(domain);
    304 				if (p > hp->h_name && strcmp(p, domain) == 0)
    305 					*p = '\0';
    306 			}
    307 			p = hp->h_name;
    308 		}
    309 		if (x) {
    310 			(void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
    311 			    ep->utmp.ut_host + UT_HOSTSIZE - x, x);
    312 			p = buf;
    313 		}
    314 		(void)printf("%-*.*s %-2.2s %-*.*s ",
    315 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
    316 		    strncmp(ep->utmp.ut_line, "tty", 3) ?
    317 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
    318 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
    319 		pr_attime(&ep->utmp.ut_time, &now);
    320 		pr_idle(ep->idle);
    321 		if (ep->args != NULL) {
    322 			arglen = strlen(ep->args);
    323 			strvisx(vis_args, ep->args,
    324 			    arglen > argwidth ? argwidth : arglen,
    325 			    VIS_TAB | VIS_NL | VIS_NOSLASH);
    326 		}
    327 		(void)printf("%.*s\n", argwidth, ep->args);
    328 	}
    329 	exit(0);
    330 }
    331 
    332 static void
    333 pr_header(nowp, nusers)
    334 	time_t *nowp;
    335 	int nusers;
    336 {
    337 	double avenrun[3];
    338 	time_t uptime;
    339 	int days, hrs, i, mins;
    340 	int mib[2];
    341 	size_t size;
    342 	char buf[256];
    343 
    344 	/*
    345 	 * Print time of day.
    346 	 *
    347 	 * SCCS forces the string manipulation below, as it replaces
    348 	 * %, M, and % in a character string with the file name.
    349 	 */
    350 	(void)strftime(buf, sizeof(buf),
    351 	    __CONCAT("%l:%","M%p"), localtime(nowp));
    352 	(void)printf("%s ", buf);
    353 
    354 	/*
    355 	 * Print how long system has been up.
    356 	 * (Found by looking getting "boottime" from the kernel)
    357 	 */
    358 	mib[0] = CTL_KERN;
    359 	mib[1] = KERN_BOOTTIME;
    360 	size = sizeof(boottime);
    361 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
    362 	    boottime.tv_sec != 0) {
    363 		uptime = now - boottime.tv_sec;
    364 		uptime += 30;
    365 		days = uptime / SECSPERDAY;
    366 		uptime %= SECSPERDAY;
    367 		hrs = uptime / SECSPERHOUR;
    368 		uptime %= SECSPERHOUR;
    369 		mins = uptime / SECSPERMIN;
    370 		(void)printf(" up");
    371 		if (days > 0)
    372 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
    373 		if (hrs > 0 && mins > 0)
    374 			(void)printf(" %2d:%02d,", hrs, mins);
    375 		else {
    376 			if (hrs > 0)
    377 				(void)printf(" %d hr%s,",
    378 				    hrs, hrs > 1 ? "s" : "");
    379 			if (mins > 0)
    380 				(void)printf(" %d min%s,",
    381 				    mins, mins > 1 ? "s" : "");
    382 		}
    383 	}
    384 
    385 	/* Print number of users logged in to system */
    386 	(void)printf(" %d user%s", nusers, nusers > 1 ? "s" : "");
    387 
    388 	/*
    389 	 * Print 1, 5, and 15 minute load averages.
    390 	 */
    391 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
    392 		(void)printf(", no load average information available\n");
    393 	else {
    394 		(void)printf(", load averages:");
    395 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
    396 			if (i > 0)
    397 				(void)printf(",");
    398 			(void)printf(" %.2f", avenrun[i]);
    399 		}
    400 		(void)printf("\n");
    401 	}
    402 }
    403 
    404 static struct stat *
    405 ttystat(line)
    406 	char *line;
    407 {
    408 	static struct stat sb;
    409 	char ttybuf[MAXPATHLEN];
    410 
    411 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
    412 	if (stat(ttybuf, &sb))
    413 		err(1, "%s", ttybuf);
    414 	return (&sb);
    415 }
    416 
    417 static void
    418 usage(wcmd)
    419 	int wcmd;
    420 {
    421 	if (wcmd)
    422 		(void)fprintf(stderr,
    423 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
    424 	else
    425 		(void)fprintf(stderr, "uptime\n");
    426 	exit (1);
    427 }
    428