w.c revision 87674
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#include <sys/cdefs.h>
35
36__FBSDID("$FreeBSD: head/usr.bin/w/w.c 87674 2001-12-11 22:18:47Z markm $");
37
38#ifndef lint
39static const char copyright[] =
40"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
41	The Regents of the University of California.  All rights reserved.\n";
42#endif
43
44#ifndef lint
45static const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
46#endif
47
48/*
49 * w - print system status (who and what)
50 *
51 * This program is similar to the systat command on Tenex/Tops 10/20
52 *
53 */
54#include <sys/param.h>
55#include <sys/time.h>
56#include <sys/stat.h>
57#include <sys/sysctl.h>
58#include <sys/proc.h>
59#include <sys/user.h>
60#include <sys/ioctl.h>
61#include <sys/socket.h>
62#include <sys/tty.h>
63
64#include <machine/cpu.h>
65#include <netinet/in.h>
66#include <arpa/inet.h>
67#include <arpa/nameser.h>
68
69#include <ctype.h>
70#include <err.h>
71#include <errno.h>
72#include <fcntl.h>
73#include <kvm.h>
74#include <langinfo.h>
75#include <libutil.h>
76#include <limits.h>
77#include <locale.h>
78#include <netdb.h>
79#include <nlist.h>
80#include <paths.h>
81#include <resolv.h>
82#include <stdio.h>
83#include <stdlib.h>
84#include <string.h>
85#include <unistd.h>
86#include <utmp.h>
87#include <vis.h>
88
89#include "extern.h"
90
91struct timeval	boottime;
92struct utmp	utmp;
93struct winsize	ws;
94kvm_t	       *kd;
95time_t		now;		/* the current time of day */
96time_t		uptime;		/* time of last reboot & elapsed time since */
97int		ttywidth;	/* width of tty */
98int		argwidth;	/* width of tty */
99int		header = 1;	/* true if -h flag: don't print heading */
100int		nflag;		/* true if -n flag: don't convert addrs */
101int		dflag;		/* true if -d flag: output debug info */
102int		sortidle;	/* sort by idle time */
103int		use_ampm;	/* use AM/PM time */
104int             use_comma;      /* use comma as floats separator */
105char	      **sel_users;	/* login array of particular users selected */
106
107/*
108 * One of these per active utmp entry.
109 */
110struct	entry {
111	struct	entry *next;
112	struct	utmp utmp;
113	dev_t	tdev;			/* dev_t of terminal */
114	time_t	idle;			/* idle time of terminal in seconds */
115	struct	kinfo_proc *kp;		/* `most interesting' proc */
116	char	*args;			/* arg list of interesting process */
117	struct	kinfo_proc *dkp;	/* debug option proc list */
118} *ep, *ehead = NULL, **nextp = &ehead;
119
120#define debugproc(p) *((struct kinfo_proc **)&(p)->ki_spare[0])
121
122/* W_DISPHOSTSIZE should not be greater than UT_HOSTSIZE */
123#define	W_DISPHOSTSIZE	16
124
125static void		 pr_header __P((time_t *, int));
126static struct stat	*ttystat __P((char *, int));
127static void		 usage __P((int));
128static int		 this_is_uptime __P((const char *s));
129
130char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
131
132int
133main(argc, argv)
134	int argc;
135	char **argv;
136{
137	struct kinfo_proc *kp;
138	struct kinfo_proc *dkp;
139	struct stat *stp;
140	FILE *ut;
141	time_t touched;
142	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
143	const char *memf, *nlistf, *p;
144	char *x_suffix;
145	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
146	char fn[MAXHOSTNAMELEN];
147	char *dot;
148
149	(void)setlocale(LC_ALL, "");
150	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
151	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
152
153	/* Are we w(1) or uptime(1)? */
154	if (this_is_uptime(argv[0]) == 0) {
155		wcmd = 0;
156		p = "";
157	} else {
158		wcmd = 1;
159		p = "dhiflM:N:nsuw";
160	}
161
162	dropgid = 0;
163	memf = nlistf = _PATH_DEVNULL;
164	while ((ch = getopt(argc, argv, p)) != -1)
165		switch (ch) {
166		case 'd':
167			dflag = 1;
168			break;
169		case 'h':
170			header = 0;
171			break;
172		case 'i':
173			sortidle = 1;
174			break;
175		case 'M':
176			header = 0;
177			memf = optarg;
178			dropgid = 1;
179			break;
180		case 'N':
181			nlistf = optarg;
182			dropgid = 1;
183			break;
184		case 'n':
185			nflag = 1;
186			break;
187		case 'f': case 'l': case 's': case 'u': case 'w':
188			warnx("[-flsuw] no longer supported");
189			/* FALLTHROUGH */
190		case '?':
191		default:
192			usage(wcmd);
193		}
194	argc -= optind;
195	argv += optind;
196
197	if (!(_res.options & RES_INIT))
198		res_init();
199	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
200	_res.retry = 1;		/* only try once.. */
201
202	/*
203	 * Discard setgid privileges if not the running kernel so that bad
204	 * guys can't print interesting stuff from kernel memory.
205	 */
206	if (dropgid)
207		setgid(getgid());
208
209	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
210		errx(1, "%s", errbuf);
211
212	(void)time(&now);
213	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
214		err(1, "%s", _PATH_UTMP);
215
216	if (*argv)
217		sel_users = argv;
218
219	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
220		if (utmp.ut_name[0] == '\0')
221			continue;
222		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
223			continue;	/* corrupted record */
224		++nusers;
225		if (wcmd == 0)
226			continue;
227		if (sel_users) {
228			int usermatch;
229			char **user;
230
231			usermatch = 0;
232			for (user = sel_users; !usermatch && *user; user++)
233				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
234					usermatch = 1;
235			if (!usermatch)
236				continue;
237		}
238		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
239			errx(1, "calloc");
240		*nextp = ep;
241		nextp = &ep->next;
242		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
243		ep->tdev = stp->st_rdev;
244#ifdef CPU_CONSDEV
245		/*
246		 * If this is the console device, attempt to ascertain
247		 * the true console device dev_t.
248		 */
249		if (ep->tdev == 0) {
250			int mib[2];
251			size_t size;
252
253			mib[0] = CTL_MACHDEP;
254			mib[1] = CPU_CONSDEV;
255			size = sizeof(dev_t);
256			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
257		}
258#endif
259		touched = stp->st_atime;
260		if (touched < ep->utmp.ut_time) {
261			/* tty untouched since before login */
262			touched = ep->utmp.ut_time;
263		}
264		if ((ep->idle = now - touched) < 0)
265			ep->idle = 0;
266	}
267	(void)fclose(ut);
268
269	if (header || wcmd == 0) {
270		pr_header(&now, nusers);
271		if (wcmd == 0) {
272			(void)kvm_close(kd);
273			exit(0);
274		}
275
276#define HEADER_USER		"USER"
277#define HEADER_TTY		"TTY"
278#define HEADER_FROM		"FROM"
279#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
280#define HEADER_WHAT		"WHAT\n"
281#define WUSED  (UT_NAMESIZE + UT_LINESIZE + W_DISPHOSTSIZE + \
282		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
283		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
284				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
285				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
286				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
287				HEADER_LOGIN_IDLE HEADER_WHAT);
288	}
289
290	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
291		err(1, "%s", kvm_geterr(kd));
292	for (i = 0; i < nentries; i++, kp++) {
293		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
294			continue;
295		for (ep = ehead; ep != NULL; ep = ep->next) {
296			if (ep->tdev == kp->ki_tdev) {
297				/*
298				 * proc is associated with this terminal
299				 */
300				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
301					/*
302					 * Proc is 'most interesting'
303					 */
304					if (proc_compare(ep->kp, kp))
305						ep->kp = kp;
306				}
307				/*
308				 * Proc debug option info; add to debug
309				 * list using kinfo_proc ki_spare[0]
310				 * as next pointer; ptr to ptr avoids the
311				 * ptr = long assumption.
312				 */
313				dkp = ep->dkp;
314				ep->dkp = kp;
315				debugproc(kp) = dkp;
316			}
317		}
318	}
319	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
320	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
321	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
322	       ttywidth = 79;
323        else
324	       ttywidth = ws.ws_col - 1;
325	argwidth = ttywidth - WUSED;
326	if (argwidth < 4)
327		argwidth = 8;
328	for (ep = ehead; ep != NULL; ep = ep->next) {
329		if (ep->kp == NULL) {
330			ep->args = strdup("-");
331			continue;
332		}
333		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
334		    ep->kp->ki_comm, MAXCOMLEN);
335		if (ep->args == NULL)
336			err(1, NULL);
337	}
338	/* sort by idle time */
339	if (sortidle && ehead != NULL) {
340		struct entry *from, *save;
341
342		from = ehead;
343		ehead = NULL;
344		while (from != NULL) {
345			for (nextp = &ehead;
346			    (*nextp) && from->idle >= (*nextp)->idle;
347			    nextp = &(*nextp)->next)
348				continue;
349			save = from;
350			from = from->next;
351			save->next = *nextp;
352			*nextp = save;
353		}
354	}
355
356	for (ep = ehead; ep != NULL; ep = ep->next) {
357		char host_buf[UT_HOSTSIZE + 1];
358		struct sockaddr_storage ss;
359		struct sockaddr *sa = (struct sockaddr *)&ss;
360		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
361		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
362		int isaddr;
363
364		host_buf[UT_HOSTSIZE] = '\0';
365		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
366		p = *host_buf ? host_buf : "-";
367		if ((x_suffix = strrchr(p, ':')) != NULL) {
368			if ((dot = strchr(x_suffix, '.')) != NULL &&
369			    strchr(dot+1, '.') == NULL)
370				*x_suffix++ = '\0';
371			else
372				x_suffix = NULL;
373		}
374		if (!nflag) {
375			/* Attempt to change an IP address into a name */
376			isaddr = 0;
377			memset(&ss, '\0', sizeof(ss));
378			if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
379				lsin6->sin6_len = sizeof(*lsin6);
380				lsin6->sin6_family = AF_INET6;
381				isaddr = 1;
382			} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
383				lsin->sin_len = sizeof(*lsin);
384				lsin->sin_family = AF_INET;
385				isaddr = 1;
386			}
387			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
388			    sa->sa_len) == HOSTNAME_FOUND)
389				p = fn;
390		}
391		if (x_suffix) {
392			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
393			p = buf;
394		}
395		if (dflag) {
396			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
397				const char *ptr;
398
399				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
400				    dkp->ki_comm, MAXCOMLEN);
401				if (ptr == NULL)
402					ptr = "-";
403				(void)printf("\t\t%-9d %s\n",
404				    dkp->ki_pid, ptr);
405			}
406		}
407		(void)printf("%-*.*s %-*.*s %-*.*s ",
408		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
409		    UT_LINESIZE, UT_LINESIZE,
410		    strncmp(ep->utmp.ut_line, "tty", 3) &&
411		    strncmp(ep->utmp.ut_line, "cua", 3) ?
412		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
413		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
414		pr_attime(&ep->utmp.ut_time, &now);
415		longidle = pr_idle(ep->idle);
416		(void)printf("%.*s\n", argwidth - longidle, ep->args);
417	}
418	(void)kvm_close(kd);
419	exit(0);
420}
421
422static void
423pr_header(nowp, nusers)
424	time_t *nowp;
425	int nusers;
426{
427	double avenrun[3];
428	time_t luptime;
429	int days, hrs, i, mins, secs;
430	int mib[2];
431	size_t size;
432	char buf[256];
433
434	/*
435	 * Print time of day.
436	 */
437	(void)strftime(buf, sizeof(buf)	- 1,
438		       use_ampm	? "%l:%M%p" : "%k:%M", localtime(nowp));
439	buf[sizeof(buf) - 1] = '\0';
440	(void)printf("%s ", buf);
441
442	/*
443	 * Print how long system has been up.
444	 * (Found by looking getting "boottime" from the kernel)
445	 */
446	mib[0] = CTL_KERN;
447	mib[1] = KERN_BOOTTIME;
448	size = sizeof(boottime);
449	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
450	    boottime.tv_sec != 0) {
451		luptime = now - boottime.tv_sec;
452		if (luptime > 60)
453			luptime += 30;
454		days = luptime / 86400;
455		luptime %= 86400;
456		hrs = luptime / 3600;
457		luptime %= 3600;
458		mins = luptime / 60;
459		secs = luptime % 60;
460		(void)printf(" up");
461		if (days > 0)
462			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
463		if (hrs > 0 && mins > 0)
464			(void)printf(" %2d:%02d,", hrs, mins);
465		else if (hrs > 0)
466			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
467		else if (mins > 0)
468			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
469		else
470			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
471	}
472
473	/* Print number of users logged in to system */
474	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
475
476	/*
477	 * Print 1, 5, and 15 minute load averages.
478	 */
479	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
480		(void)printf(", no load average information available\n");
481	else {
482		(void)printf(", load averages:");
483		for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) {
484			if (use_comma && i > 0)
485				(void)printf(",");
486			(void)printf(" %.2f", avenrun[i]);
487		}
488		(void)printf("\n");
489	}
490}
491
492static struct stat *
493ttystat(line, sz)
494	char *line;
495	int sz;
496{
497	static struct stat sb;
498	char ttybuf[MAXPATHLEN];
499
500	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
501	if (stat(ttybuf, &sb)) {
502		warn("%s", ttybuf);
503		return (NULL);
504	}
505	return (&sb);
506}
507
508static void
509usage(wcmd)
510	int wcmd;
511{
512	if (wcmd)
513		(void)fprintf(stderr,
514		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
515	else
516		(void)fprintf(stderr, "usage: uptime\n");
517	exit(1);
518}
519
520static int
521this_is_uptime(s)
522	const char *s;
523{
524	const char *u;
525
526	if ((u = strrchr(s, '/')) != NULL)
527		++u;
528	else
529		u = s;
530	if (strcmp(u, "uptime") == 0)
531		return (0);
532	return (-1);
533}
534