w.c revision 9987
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
35static 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
41static 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 <unistd.h>
76#include <utmp.h>
77#include <vis.h>
78
79#include <arpa/nameser.h>
80#include <resolv.h>
81
82#include "extern.h"
83
84struct timeval	boottime;
85struct utmp	utmp;
86struct winsize	ws;
87kvm_t	       *kd;
88time_t		now;		/* the current time of day */
89time_t		uptime;		/* time of last reboot & elapsed time since */
90int		ttywidth;	/* width of tty */
91int		argwidth;	/* width of tty */
92int		header = 1;	/* true if -h flag: don't print heading */
93int		nflag;		/* true if -n flag: don't convert addrs */
94int		sortidle;	/* sort bu idle time */
95char	       *sel_user;	/* login of particular user selected */
96char		domain[MAXHOSTNAMELEN];
97
98/*
99 * One of these per active utmp entry.
100 */
101struct	entry {
102	struct	entry *next;
103	struct	utmp utmp;
104	dev_t	tdev;		/* dev_t of terminal */
105	time_t	idle;		/* idle time of terminal in seconds */
106	struct	kinfo_proc *kp;	/* `most interesting' proc */
107	char	*args;		/* arg list of interesting process */
108} *ep, *ehead = NULL, **nextp = &ehead;
109
110static void	 pr_header __P((time_t *, int));
111static struct stat
112		*ttystat __P((char *));
113static void	 usage __P((int));
114
115char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
116
117int
118main(argc, argv)
119	int argc;
120	char **argv;
121{
122	extern char *__progname;
123	struct kinfo_proc *kp;
124	struct hostent *hp;
125	struct stat *stp;
126	FILE *ut;
127	u_long l;
128	size_t arglen;
129	int ch, i, nentries, nusers, wcmd;
130	char *memf, *nlistf, *p, *vis_args, *x;
131	char buf[MAXHOSTNAMELEN], errbuf[256];
132
133	/* Are we w(1) or uptime(1)? */
134	p = __progname;
135	if (*p == '-')
136		p++;
137	if (*p == 'u') {
138		wcmd = 0;
139		p = "";
140	} else {
141		wcmd = 1;
142		p = "hiflM:N:nsuw";
143	}
144
145	memf = nlistf = NULL;
146	while ((ch = getopt(argc, argv, p)) != EOF)
147		switch (ch) {
148		case 'h':
149			header = 0;
150			break;
151		case 'i':
152			sortidle = 1;
153			break;
154		case 'M':
155			header = 0;
156			memf = optarg;
157			break;
158		case 'N':
159			nlistf = optarg;
160			break;
161		case 'n':
162			nflag = 1;
163			break;
164		case 'f': case 'l': case 's': case 'u': case 'w':
165			warnx("[-flsuw] no longer supported");
166			/* FALLTHROUGH */
167		case '?':
168		default:
169			usage(wcmd);
170		}
171	argc -= optind;
172	argv += optind;
173
174	if (!(_res.options & RES_INIT))
175		res_init();
176	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
177	_res.retry = 1;		/* only try once.. */
178
179	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
180		errx(1, "%s", errbuf);
181
182	(void)time(&now);
183	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
184		err(1, "%s", _PATH_UTMP);
185
186	if (*argv)
187		sel_user = *argv;
188
189	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
190		if (utmp.ut_name[0] == '\0')
191			continue;
192		++nusers;
193		if (wcmd == 0 || (sel_user &&
194		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
195			continue;
196		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
197			err(1, NULL);
198		*nextp = ep;
199		nextp = &(ep->next);
200		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
201		stp = ttystat(ep->utmp.ut_line);
202		ep->tdev = stp->st_rdev;
203#ifdef CPU_CONSDEV
204		/*
205		 * If this is the console device, attempt to ascertain
206		 * the true console device dev_t.
207		 */
208		if (ep->tdev == 0) {
209			int mib[2];
210			size_t size;
211
212			mib[0] = CTL_MACHDEP;
213			mib[1] = CPU_CONSDEV;
214			size = sizeof(dev_t);
215			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
216		}
217#endif
218		if ((ep->idle = now - stp->st_atime) < 0)
219			ep->idle = 0;
220	}
221	(void)fclose(ut);
222
223	if (header || wcmd == 0) {
224		pr_header(&now, nusers);
225		if (wcmd == 0)
226			exit (0);
227
228#define HEADER	"USER    TTY FROM              LOGIN@  IDLE WHAT\n"
229#define WUSED	(sizeof (HEADER) - sizeof ("WHAT\n"))
230		(void)printf(HEADER);
231	}
232
233	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
234		err(1, "%s", kvm_geterr(kd));
235	for (i = 0; i < nentries; i++, kp++) {
236		struct proc *p = &kp->kp_proc;
237		struct eproc *e;
238
239		if (p->p_stat == SIDL || p->p_stat == SZOMB)
240			continue;
241		e = &kp->kp_eproc;
242		for (ep = ehead; ep != NULL; ep = ep->next) {
243			if (ep->tdev == e->e_tdev && e->e_pgid == e->e_tpgid) {
244				/*
245				 * Proc is in foreground of this terminal
246				 */
247				if (proc_compare(&ep->kp->kp_proc, p))
248					ep->kp = kp;
249				break;
250			}
251		}
252	}
253	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
254	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
255	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
256	       ttywidth = 79;
257        else
258	       ttywidth = ws.ws_col - 1;
259	argwidth = ttywidth - WUSED;
260	if (argwidth < 4)
261		argwidth = 8;
262	for (ep = ehead; ep != NULL; ep = ep->next) {
263		if (ep->kp == NULL) {
264			ep->args = "-";
265			continue;
266		}
267		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
268		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
269		if (ep->args == NULL)
270			err(1, NULL);
271	}
272	/* sort by idle time */
273	if (sortidle && ehead != NULL) {
274		struct entry *from = ehead, *save;
275
276		ehead = NULL;
277		while (from != NULL) {
278			for (nextp = &ehead;
279			    (*nextp) && from->idle >= (*nextp)->idle;
280			    nextp = &(*nextp)->next)
281				continue;
282			save = from;
283			from = from->next;
284			save->next = *nextp;
285			*nextp = save;
286		}
287	}
288
289	if (!nflag)
290		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
291		    (p = strchr(domain, '.')) == 0)
292			domain[0] = '\0';
293		else {
294			domain[sizeof(domain) - 1] = '\0';
295			memmove(domain, p, strlen(p) + 1);
296		}
297
298	if ((vis_args = malloc(argwidth * 4 + 1)) == NULL)
299		err(1, NULL);
300	for (ep = ehead; ep != NULL; ep = ep->next) {
301		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
302		if ((x = strchr(p, ':')) != NULL)
303			*x++ = '\0';
304		if (!nflag && isdigit(*p) &&
305		    (long)(l = inet_addr(p)) != -1 &&
306		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
307			if (domain[0] != '\0') {
308				p = hp->h_name;
309				p += strlen(hp->h_name);
310				p -= strlen(domain);
311				if (p > hp->h_name && strcmp(p, domain) == 0)
312					*p = '\0';
313			}
314			p = hp->h_name;
315		}
316		if (x) {
317			(void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
318			    ep->utmp.ut_host + UT_HOSTSIZE - x, x);
319			p = buf;
320		}
321		(void)printf("%-*.*s %-2.2s %-*.*s ",
322		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
323		    strncmp(ep->utmp.ut_line, "tty", 3) &&
324		    strncmp(ep->utmp.ut_line, "cua", 3) ?
325		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
326		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
327		pr_attime(&ep->utmp.ut_time, &now);
328		pr_idle(ep->idle);
329		if (ep->args != NULL) {
330			arglen = strlen(ep->args);
331			strvisx(vis_args, ep->args,
332			    arglen > argwidth ? argwidth : arglen,
333			    VIS_TAB | VIS_NL | VIS_NOSLASH);
334		}
335		(void)printf("%.*s\n", argwidth, ep->args);
336	}
337	exit(0);
338}
339
340static void
341pr_header(nowp, nusers)
342	time_t *nowp;
343	int nusers;
344{
345	double avenrun[3];
346	time_t uptime;
347	int days, hrs, i, mins;
348	int mib[2];
349	size_t size;
350	char buf[256];
351
352	/*
353	 * Print time of day.
354	 *
355	 * SCCS forces the string manipulation below, as it replaces
356	 * %, M, and % in a character string with the file name.
357	 */
358	(void)strftime(buf, sizeof(buf),
359	    __CONCAT("%l:%","M%p"), localtime(nowp));
360	(void)printf("%s ", buf);
361
362	/*
363	 * Print how long system has been up.
364	 * (Found by looking getting "boottime" from the kernel)
365	 */
366	mib[0] = CTL_KERN;
367	mib[1] = KERN_BOOTTIME;
368	size = sizeof(boottime);
369	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
370	    boottime.tv_sec != 0) {
371		uptime = now - boottime.tv_sec;
372		uptime += 30;
373		days = uptime / 86400;
374		uptime %= 86400;
375		hrs = uptime / 3600;
376		uptime %= 3600;
377		mins = uptime / 60;
378		(void)printf(" up");
379		if (days > 0)
380			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
381		if (hrs > 0 && mins > 0)
382			(void)printf(" %2d:%02d,", hrs, mins);
383		else {
384			if (hrs > 0)
385				(void)printf(" %d hr%s,",
386				    hrs, hrs > 1 ? "s" : "");
387			if (mins > 0)
388				(void)printf(" %d min%s,",
389				    mins, mins > 1 ? "s" : "");
390		}
391	}
392
393	/* Print number of users logged in to system */
394	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
395
396	/*
397	 * Print 1, 5, and 15 minute load averages.
398	 */
399	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
400		(void)printf(", no load average information available\n");
401	else {
402		(void)printf(", load averages:");
403		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
404			if (i > 0)
405				(void)printf(",");
406			(void)printf(" %.2f", avenrun[i]);
407		}
408		(void)printf("\n");
409	}
410}
411
412static struct stat *
413ttystat(line)
414	char *line;
415{
416	static struct stat sb;
417	char ttybuf[MAXPATHLEN];
418
419	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
420	if (stat(ttybuf, &sb))
421		err(1, "%s", ttybuf);
422	return (&sb);
423}
424
425static void
426usage(wcmd)
427	int wcmd;
428{
429	if (wcmd)
430		(void)fprintf(stderr,
431		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
432	else
433		(void)fprintf(stderr, "uptime\n");
434	exit (1);
435}
436