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