w.c revision 70242
1193640Sariff/*-
2193640Sariff * Copyright (c) 1980, 1991, 1993, 1994
3193640Sariff *	The Regents of the University of California.  All rights reserved.
4193640Sariff *
5193640Sariff * Redistribution and use in source and binary forms, with or without
6193640Sariff * modification, are permitted provided that the following conditions
7193640Sariff * are met:
8193640Sariff * 1. Redistributions of source code must retain the above copyright
9193640Sariff *    notice, this list of conditions and the following disclaimer.
10193640Sariff * 2. Redistributions in binary form must reproduce the above copyright
11193640Sariff *    notice, this list of conditions and the following disclaimer in the
12193640Sariff *    documentation and/or other materials provided with the distribution.
13193640Sariff * 3. All advertising materials mentioning features or use of this software
14193640Sariff *    must display the following acknowledgement:
15193640Sariff *	This product includes software developed by the University of
16193640Sariff *	California, Berkeley and its contributors.
17193640Sariff * 4. Neither the name of the University nor the names of its contributors
18193640Sariff *    may be used to endorse or promote products derived from this software
19193640Sariff *    without specific prior written permission.
20193640Sariff *
21193640Sariff * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22193640Sariff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23193640Sariff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24193640Sariff * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25193640Sariff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26193640Sariff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27193640Sariff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28193640Sariff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29193640Sariff * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30193640Sariff * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31193640Sariff * SUCH DAMAGE.
32193640Sariff */
33193640Sariff
34193640Sariff#ifndef lint
35193640Sariffstatic const char copyright[] =
36193640Sariff"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
37193640Sariff	The Regents of the University of California.  All rights reserved.\n";
38193640Sariff#endif /* not lint */
39193640Sariff
40193640Sariff#ifndef lint
41193640Sariff#if 0
42193640Sariffstatic char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
43193640Sariff#endif
44193640Sariffstatic const char rcsid[] =
45193640Sariff  "$FreeBSD: head/usr.bin/w/w.c 70242 2000-12-21 01:30:47Z brian $";
46193640Sariff#endif /* not lint */
47193640Sariff
48193640Sariff/*
49193640Sariff * w - print system status (who and what)
50193640Sariff *
51193640Sariff * This program is similar to the systat command on Tenex/Tops 10/20
52193640Sariff *
53193640Sariff */
54193640Sariff#include <sys/param.h>
55193640Sariff#include <sys/time.h>
56193640Sariff#include <sys/stat.h>
57193640Sariff#include <sys/sysctl.h>
58193640Sariff#include <sys/proc.h>
59193640Sariff#include <sys/user.h>
60193640Sariff#include <sys/ioctl.h>
61193640Sariff#include <sys/socket.h>
62193640Sariff#include <sys/tty.h>
63193640Sariff
64193640Sariff#include <machine/cpu.h>
65193640Sariff#include <netinet/in.h>
66193640Sariff#include <arpa/inet.h>
67193640Sariff
68193640Sariff#include <ctype.h>
69193640Sariff#include <err.h>
70193640Sariff#include <errno.h>
71193640Sariff#include <fcntl.h>
72193640Sariff#include <kvm.h>
73193640Sariff#include <netdb.h>
74193640Sariff#include <nlist.h>
75193640Sariff#include <paths.h>
76193640Sariff#include <stdio.h>
77193640Sariff#include <stdlib.h>
78193640Sariff#include <string.h>
79193640Sariff#include <unistd.h>
80193640Sariff#include <utmp.h>
81193640Sariff#include <vis.h>
82193640Sariff#include <locale.h>
83193640Sariff
84193640Sariff#include <arpa/nameser.h>
85193640Sariff#include <resolv.h>
86193640Sariff
87193640Sariff#include "extern.h"
88193640Sariff
89193640Sariffstruct timeval	boottime;
90193640Sariffstruct utmp	utmp;
91193640Sariffstruct winsize	ws;
92193640Sariffkvm_t	       *kd;
93193640Sarifftime_t		now;		/* the current time of day */
94193640Sarifftime_t		uptime;		/* time of last reboot & elapsed time since */
95193640Sariffint		ttywidth;	/* width of tty */
96193640Sariffint		argwidth;	/* width of tty */
97193640Sariffint		header = 1;	/* true if -h flag: don't print heading */
98193640Sariffint		nflag;		/* true if -n flag: don't convert addrs */
99193640Sariffint		dflag;		/* true if -d flag: output debug info */
100193640Sariffint		sortidle;	/* sort by idle time */
101193640Sariffchar	      **sel_users;	/* login array of particular users selected */
102193640Sariffchar		domain[MAXHOSTNAMELEN];
103193640Sariff
104193640Sariff/*
105193640Sariff * One of these per active utmp entry.
106193640Sariff */
107193640Sariffstruct	entry {
108193640Sariff	struct	entry *next;
109193640Sariff	struct	utmp utmp;
110193640Sariff	dev_t	tdev;			/* dev_t of terminal */
111193640Sariff	time_t	idle;			/* idle time of terminal in seconds */
112193640Sariff	struct	kinfo_proc *kp;		/* `most interesting' proc */
113193640Sariff	char	*args;			/* arg list of interesting process */
114193640Sariff	struct	kinfo_proc *dkp;	/* debug option proc list */
115193640Sariff} *ep, *ehead = NULL, **nextp = &ehead;
116193640Sariff
117193640Sariff#define debugproc(p) *((struct kinfo_proc **)&(p)->ki_spare[0])
118193640Sariff
119193640Sariffstatic void		 pr_header __P((time_t *, int));
120193640Sariffstatic struct stat	*ttystat __P((char *, int));
121193640Sariffstatic void		 usage __P((int));
122193640Sariffstatic int		 this_is_uptime __P((const char *s));
123193640Sariff
124193640Sariffchar *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
125193640Sariff
126193640Sariffint
127193640Sariffmain(argc, argv)
128193640Sariff	int argc;
129193640Sariff	char **argv;
130193640Sariff{
131193640Sariff	struct kinfo_proc *kp;
132193640Sariff	struct kinfo_proc *dkp;
133193640Sariff	struct hostent *hp;
134193640Sariff	struct stat *stp;
135193640Sariff	FILE *ut;
136193640Sariff	u_long l;
137243138Smav	time_t touched;
138243138Smav	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
139243138Smav	char *memf, *nlistf, *p, *x;
140193640Sariff	char buf[MAXHOSTNAMELEN], errbuf[256];
141193640Sariff
142193640Sariff	(void)setlocale(LC_ALL, "");
143243138Smav
144243138Smav	/* Are we w(1) or uptime(1)? */
145193640Sariff	if (this_is_uptime(argv[0]) == 0) {
146193640Sariff		wcmd = 0;
147193640Sariff		p = "";
148243138Smav	} else {
149243138Smav		wcmd = 1;
150193640Sariff		p = "dhiflM:N:nsuw";
151193640Sariff	}
152243138Smav
153243138Smav	dropgid = 0;
154243138Smav	memf = nlistf = _PATH_DEVNULL;
155193640Sariff	while ((ch = getopt(argc, argv, p)) != -1)
156193640Sariff		switch (ch) {
157193640Sariff		case 'd':
158243138Smav			dflag = 1;
159193640Sariff			break;
160193640Sariff		case 'h':
161243138Smav			header = 0;
162193640Sariff			break;
163193640Sariff		case 'i':
164193640Sariff			sortidle = 1;
165193640Sariff			break;
166193640Sariff		case 'M':
167193640Sariff			header = 0;
168193640Sariff			memf = optarg;
169193640Sariff			dropgid = 1;
170193640Sariff			break;
171193640Sariff		case 'N':
172193640Sariff			nlistf = optarg;
173193640Sariff			dropgid = 1;
174193640Sariff			break;
175193640Sariff		case 'n':
176193640Sariff			nflag = 1;
177193640Sariff			break;
178193640Sariff		case 'f': case 'l': case 's': case 'u': case 'w':
179193640Sariff			warnx("[-flsuw] no longer supported");
180193640Sariff			/* FALLTHROUGH */
181193640Sariff		case '?':
182193640Sariff		default:
183193640Sariff			usage(wcmd);
184193640Sariff		}
185193640Sariff	argc -= optind;
186193640Sariff	argv += optind;
187193640Sariff
188193640Sariff	if (!(_res.options & RES_INIT))
189193640Sariff		res_init();
190193640Sariff	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
191193640Sariff	_res.retry = 1;		/* only try once.. */
192193640Sariff
193193640Sariff	/*
194193640Sariff	 * Discard setgid privileges if not the running kernel so that bad
195193640Sariff	 * guys can't print interesting stuff from kernel memory.
196193640Sariff	 */
197193640Sariff	if (dropgid)
198193640Sariff		setgid(getgid());
199193640Sariff
200193640Sariff	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
201193640Sariff		errx(1, "%s", errbuf);
202193640Sariff
203193640Sariff	(void)time(&now);
204193640Sariff	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
205193640Sariff		err(1, "%s", _PATH_UTMP);
206193640Sariff
207193640Sariff	if (*argv)
208193640Sariff		sel_users = argv;
209193640Sariff
210193640Sariff	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
211193640Sariff		if (utmp.ut_name[0] == '\0')
212193640Sariff			continue;
213193640Sariff		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
214193640Sariff			continue;	/* corrupted record */
215193640Sariff		++nusers;
216193640Sariff		if (wcmd == 0)
217193640Sariff			continue;
218193640Sariff		if (sel_users) {
219193640Sariff			int usermatch;
220193640Sariff			char **user;
221
222			usermatch = 0;
223			for (user = sel_users; !usermatch && *user; user++)
224				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
225					usermatch = 1;
226			if (!usermatch)
227				continue;
228		}
229		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
230			errx(1, "calloc");
231		*nextp = ep;
232		nextp = &ep->next;
233		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
234		ep->tdev = stp->st_rdev;
235#ifdef CPU_CONSDEV
236		/*
237		 * If this is the console device, attempt to ascertain
238		 * the true console device dev_t.
239		 */
240		if (ep->tdev == 0) {
241			int mib[2];
242			size_t size;
243
244			mib[0] = CTL_MACHDEP;
245			mib[1] = CPU_CONSDEV;
246			size = sizeof(dev_t);
247			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
248		}
249#endif
250		touched = stp->st_atime;
251		if (touched < ep->utmp.ut_time) {
252			/* tty untouched since before login */
253			touched = ep->utmp.ut_time;
254		}
255		if ((ep->idle = now - touched) < 0)
256			ep->idle = 0;
257	}
258	(void)fclose(ut);
259
260	if (header || wcmd == 0) {
261		pr_header(&now, nusers);
262		if (wcmd == 0)
263			exit(0);
264
265#define HEADER_USER		"USER"
266#define HEADER_TTY		"TTY"
267#define HEADER_FROM		"FROM"
268#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
269#define HEADER_WHAT		"WHAT\n"
270#define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
271		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
272		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
273				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
274				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
275				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
276				HEADER_LOGIN_IDLE HEADER_WHAT);
277	}
278
279	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
280		err(1, "%s", kvm_geterr(kd));
281	for (i = 0; i < nentries; i++, kp++) {
282		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
283			continue;
284		for (ep = ehead; ep != NULL; ep = ep->next) {
285			if (ep->tdev == kp->ki_tdev) {
286				/*
287				 * proc is associated with this terminal
288				 */
289				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
290					/*
291					 * Proc is 'most interesting'
292					 */
293					if (proc_compare(ep->kp, kp))
294						ep->kp = kp;
295				}
296				/*
297				 * Proc debug option info; add to debug
298				 * list using kinfo_proc ki_spare[0]
299				 * as next pointer; ptr to ptr avoids the
300				 * ptr = long assumption.
301				 */
302				dkp = ep->dkp;
303				ep->dkp = kp;
304				debugproc(kp) = dkp;
305			}
306		}
307	}
308	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
309	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
310	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
311	       ttywidth = 79;
312        else
313	       ttywidth = ws.ws_col - 1;
314	argwidth = ttywidth - WUSED;
315	if (argwidth < 4)
316		argwidth = 8;
317	for (ep = ehead; ep != NULL; ep = ep->next) {
318		if (ep->kp == NULL) {
319			ep->args = "-";
320			continue;
321		}
322		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
323		    ep->kp->ki_comm, MAXCOMLEN);
324		if (ep->args == NULL)
325			err(1, NULL);
326	}
327	/* sort by idle time */
328	if (sortidle && ehead != NULL) {
329		struct entry *from, *save;
330
331		from = ehead;
332		ehead = NULL;
333		while (from != NULL) {
334			for (nextp = &ehead;
335			    (*nextp) && from->idle >= (*nextp)->idle;
336			    nextp = &(*nextp)->next)
337				continue;
338			save = from;
339			from = from->next;
340			save->next = *nextp;
341			*nextp = save;
342		}
343	}
344
345	if (!nflag) {
346		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
347		    (p = strchr(domain, '.')) == NULL)
348			domain[0] = '\0';
349		else {
350			domain[sizeof(domain) - 1] = '\0';
351			memmove(domain, p, strlen(p) + 1);
352		}
353	}
354
355	for (ep = ehead; ep != NULL; ep = ep->next) {
356		char host_buf[UT_HOSTSIZE + 1];
357
358		host_buf[UT_HOSTSIZE] = '\0';
359		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
360		p = *host_buf ? host_buf : "-";
361		if ((x = strchr(p, ':')) != NULL)
362			*x++ = '\0';
363		if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 &&
364		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
365			if (domain[0] != '\0') {
366				p = hp->h_name;
367				p += strlen(hp->h_name);
368				p -= strlen(domain);
369				if (p > hp->h_name && strcmp(p, domain) == 0)
370					*p = '\0';
371			}
372			p = hp->h_name;
373		}
374		if (nflag && *p && strcmp(p, "-") &&
375		    inet_addr(p) == INADDR_NONE) {
376			hp = gethostbyname(p);
377
378			if (hp != NULL) {
379				struct in_addr in;
380
381				memmove(&in, hp->h_addr, sizeof(in));
382				p = inet_ntoa(in);
383			}
384		}
385		if (x) {
386			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
387			p = buf;
388		}
389		if (dflag) {
390			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
391				char *ptr;
392
393				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
394				    dkp->ki_comm, MAXCOMLEN);
395				if (ptr == NULL)
396					ptr = "-";
397				(void)printf("\t\t%-9d %s\n",
398				    dkp->ki_pid, ptr);
399			}
400		}
401		(void)printf("%-*.*s %-*.*s %-*.*s ",
402		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
403		    UT_LINESIZE, UT_LINESIZE,
404		    strncmp(ep->utmp.ut_line, "tty", 3) &&
405		    strncmp(ep->utmp.ut_line, "cua", 3) ?
406		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
407		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
408		pr_attime(&ep->utmp.ut_time, &now);
409		longidle = pr_idle(ep->idle);
410		(void)printf("%.*s\n", argwidth - longidle, ep->args);
411	}
412	exit(0);
413}
414
415static void
416pr_header(nowp, nusers)
417	time_t *nowp;
418	int nusers;
419{
420	double avenrun[3];
421	time_t uptime;
422	int days, hrs, i, mins, secs;
423	int mib[2];
424	size_t size;
425	char buf[256];
426
427	/*
428	 * Print time of day.
429	 */
430	(void)strftime(buf, sizeof(buf) - 1, "%l:%M%p", localtime(nowp));
431	buf[sizeof(buf) - 1] = '\0';
432	(void)printf("%s ", buf);
433
434	/*
435	 * Print how long system has been up.
436	 * (Found by looking getting "boottime" from the kernel)
437	 */
438	mib[0] = CTL_KERN;
439	mib[1] = KERN_BOOTTIME;
440	size = sizeof(boottime);
441	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
442	    boottime.tv_sec != 0) {
443		uptime = now - boottime.tv_sec;
444		uptime += 30;
445		days = uptime / 86400;
446		uptime %= 86400;
447		hrs = uptime / 3600;
448		uptime %= 3600;
449		mins = uptime / 60;
450		secs = uptime % 60;
451		(void)printf(" up");
452		if (days > 0)
453			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
454		if (hrs > 0 && mins > 0)
455			(void)printf(" %2d:%02d,", hrs, mins);
456		else if (hrs > 0)
457			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
458		else if (mins > 0)
459			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
460		else
461			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
462	}
463
464	/* Print number of users logged in to system */
465	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
466
467	/*
468	 * Print 1, 5, and 15 minute load averages.
469	 */
470	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
471		(void)printf(", no load average information available\n");
472	else {
473		(void)printf(", load averages:");
474		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++)
475			(void)printf("%s %.2f", i > 0 ? "," : "", avenrun[i]);
476		(void)printf("\n");
477	}
478}
479
480static struct stat *
481ttystat(line, sz)
482	char *line;
483	int sz;
484{
485	static struct stat sb;
486	char ttybuf[MAXPATHLEN];
487
488	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
489	if (stat(ttybuf, &sb)) {
490		warn("%s", ttybuf);
491		return (NULL);
492	}
493	return (&sb);
494}
495
496static void
497usage(wcmd)
498	int wcmd;
499{
500	if (wcmd)
501		(void)fprintf(stderr,
502		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
503	else
504		(void)fprintf(stderr, "usage: uptime\n");
505	exit(1);
506}
507
508static int
509this_is_uptime(s)
510	const char *s;
511{
512	const char *u;
513
514	if ((u = strrchr(s, '/')) != NULL)
515		++u;
516	else
517		u = s;
518	if (strcmp(u, "uptime") == 0)
519		return (0);
520	return (-1);
521}
522