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