w.c revision 158444
1209513Simp/*-
2209513Simp * Copyright (c) 1980, 1991, 1993, 1994
3209513Simp *	The Regents of the University of California.  All rights reserved.
4209513Simp *
5209513Simp * Redistribution and use in source and binary forms, with or without
6209513Simp * modification, are permitted provided that the following conditions
7209513Simp * are met:
8209513Simp * 1. Redistributions of source code must retain the above copyright
9209513Simp *    notice, this list of conditions and the following disclaimer.
10209513Simp * 2. Redistributions in binary form must reproduce the above copyright
11209513Simp *    notice, this list of conditions and the following disclaimer in the
12209513Simp *    documentation and/or other materials provided with the distribution.
13209513Simp * 3. All advertising materials mentioning features or use of this software
14209513Simp *    must display the following acknowledgement:
15209513Simp *	This product includes software developed by the University of
16209513Simp *	California, Berkeley and its contributors.
17209513Simp * 4. Neither the name of the University nor the names of its contributors
18209513Simp *    may be used to endorse or promote products derived from this software
19209513Simp *    without specific prior written permission.
20209513Simp *
21209513Simp * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22209513Simp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23209513Simp * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24209513Simp * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25209513Simp * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26209513Simp * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27209513Simp * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28209513Simp * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29209513Simp * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30209513Simp * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31209513Simp * SUCH DAMAGE.
32209513Simp */
33209513Simp
34209513Simp#include <sys/cdefs.h>
35209513Simp
36209513Simp__FBSDID("$FreeBSD: head/usr.bin/w/w.c 158444 2006-05-11 17:25:36Z phk $");
37209513Simp
38209513Simp#ifndef lint
39209513Simpstatic const char copyright[] =
40209513Simp"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
41209513Simp	The Regents of the University of California.  All rights reserved.\n";
42209513Simp#endif
43209513Simp
44209513Simp#ifndef lint
45209513Simpstatic const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
46209513Simp#endif
47209513Simp
48209513Simp/*
49209513Simp * w - print system status (who and what)
50209513Simp *
51209513Simp * This program is similar to the systat command on Tenex/Tops 10/20
52209513Simp *
53209513Simp */
54209513Simp#include <sys/param.h>
55209513Simp#include <sys/time.h>
56209513Simp#include <sys/stat.h>
57209513Simp#include <sys/sysctl.h>
58209513Simp#include <sys/proc.h>
59209513Simp#include <sys/user.h>
60209513Simp#include <sys/ioctl.h>
61209513Simp#include <sys/socket.h>
62209513Simp#include <sys/tty.h>
63209513Simp
64209513Simp#include <machine/cpu.h>
65209513Simp#include <netinet/in.h>
66209513Simp#include <arpa/inet.h>
67209513Simp#include <arpa/nameser.h>
68209513Simp
69209513Simp#include <ctype.h>
70209513Simp#include <err.h>
71209513Simp#include <errno.h>
72209513Simp#include <fcntl.h>
73209513Simp#include <kvm.h>
74209513Simp#include <langinfo.h>
75209513Simp#include <libutil.h>
76209513Simp#include <limits.h>
77209513Simp#include <locale.h>
78209513Simp#include <netdb.h>
79209513Simp#include <nlist.h>
80209513Simp#include <paths.h>
81209513Simp#include <resolv.h>
82209513Simp#include <stdio.h>
83209513Simp#include <stdlib.h>
84209513Simp#include <string.h>
85209513Simp#include <timeconv.h>
86209513Simp#include <unistd.h>
87209513Simp#include <utmp.h>
88209513Simp#include <vis.h>
89209513Simp
90209513Simp#include "extern.h"
91209513Simp
92209513Simpstruct timeval	boottime;
93209513Simpstruct utmp	utmp;
94209513Simpstruct winsize	ws;
95209513Simpkvm_t	       *kd;
96209513Simptime_t		now;		/* the current time of day */
97209513Simpint		ttywidth;	/* width of tty */
98209513Simpint		argwidth;	/* width of tty */
99209513Simpint		header = 1;	/* true if -h flag: don't print heading */
100209513Simpint		nflag;		/* true if -n flag: don't convert addrs */
101209513Simpint		dflag;		/* true if -d flag: output debug info */
102209513Simpint		sortidle;	/* sort by idle time */
103209513Simpint		use_ampm;	/* use AM/PM time */
104209513Simpint             use_comma;      /* use comma as floats separator */
105209513Simpchar	      **sel_users;	/* login array of particular users selected */
106209513Simp
107209513Simp/*
108209513Simp * One of these per active utmp entry.
109209513Simp */
110209513Simpstruct	entry {
111209513Simp	struct	entry *next;
112209513Simp	struct	utmp utmp;
113209513Simp	dev_t	tdev;			/* dev_t of terminal */
114209513Simp	time_t	idle;			/* idle time of terminal in seconds */
115209513Simp	struct	kinfo_proc *kp;		/* `most interesting' proc */
116209513Simp	char	*args;			/* arg list of interesting process */
117209513Simp	struct	kinfo_proc *dkp;	/* debug option proc list */
118209513Simp} *ep, *ehead = NULL, **nextp = &ehead;
119209513Simp
120209513Simp#define	debugproc(p) *((struct kinfo_proc **)&(p)->ki_udata)
121209513Simp
122209513Simp/* W_DISPHOSTSIZE should not be greater than UT_HOSTSIZE */
123209513Simp#define	W_DISPHOSTSIZE	16
124209513Simp
125209513Simpstatic void		 pr_header(time_t *, int);
126209513Simpstatic struct stat	*ttystat(char *, int);
127209513Simpstatic void		 usage(int);
128209513Simpstatic int		 this_is_uptime(const char *s);
129209513Simp
130209513Simpchar *fmt_argv(char **, char *, int);	/* ../../bin/ps/fmt.c */
131209513Simp
132209513Simpint
133209513Simpmain(int argc, char *argv[])
134209513Simp{
135209513Simp	struct kinfo_proc *kp;
136209513Simp	struct kinfo_proc *dkp;
137209513Simp	struct stat *stp;
138209513Simp	FILE *ut;
139209513Simp	time_t touched;
140209513Simp	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
141209513Simp	const char *memf, *nlistf, *p;
142209513Simp	char *x_suffix;
143209513Simp	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
144209513Simp	char fn[MAXHOSTNAMELEN];
145209513Simp	char *dot;
146209513Simp
147209513Simp	(void)setlocale(LC_ALL, "");
148209513Simp	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
149209513Simp	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
150209513Simp
151209513Simp	/* Are we w(1) or uptime(1)? */
152209513Simp	if (this_is_uptime(argv[0]) == 0) {
153209513Simp		wcmd = 0;
154209513Simp		p = "";
155209513Simp	} else {
156209513Simp		wcmd = 1;
157209513Simp		p = "dhiflM:N:nsuw";
158209513Simp	}
159209513Simp
160209513Simp	dropgid = 0;
161209513Simp	memf = nlistf = _PATH_DEVNULL;
162209513Simp	while ((ch = getopt(argc, argv, p)) != -1)
163209513Simp		switch (ch) {
164209513Simp		case 'd':
165209513Simp			dflag = 1;
166209513Simp			break;
167209513Simp		case 'h':
168209513Simp			header = 0;
169209513Simp			break;
170209513Simp		case 'i':
171209513Simp			sortidle = 1;
172209513Simp			break;
173209513Simp		case 'M':
174209513Simp			header = 0;
175209513Simp			memf = optarg;
176209513Simp			dropgid = 1;
177209513Simp			break;
178209513Simp		case 'N':
179209513Simp			nlistf = optarg;
180209513Simp			dropgid = 1;
181209513Simp			break;
182209513Simp		case 'n':
183209513Simp			nflag = 1;
184209513Simp			break;
185209513Simp		case 'f': case 'l': case 's': case 'u': case 'w':
186209513Simp			warnx("[-flsuw] no longer supported");
187209513Simp			/* FALLTHROUGH */
188209513Simp		case '?':
189209513Simp		default:
190209513Simp			usage(wcmd);
191209513Simp		}
192209513Simp	argc -= optind;
193209513Simp	argv += optind;
194209513Simp
195209513Simp	if (!(_res.options & RES_INIT))
196209513Simp		res_init();
197209513Simp	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
198209513Simp	_res.retry = 1;		/* only try once.. */
199209513Simp
200209513Simp	/*
201209513Simp	 * Discard setgid privileges if not the running kernel so that bad
202209513Simp	 * guys can't print interesting stuff from kernel memory.
203209513Simp	 */
204209513Simp	if (dropgid)
205209513Simp		setgid(getgid());
206209513Simp
207	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
208		errx(1, "%s", errbuf);
209
210	(void)time(&now);
211	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
212		err(1, "%s", _PATH_UTMP);
213
214	if (*argv)
215		sel_users = argv;
216
217	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
218		if (utmp.ut_name[0] == '\0')
219			continue;
220		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
221			continue;	/* corrupted record */
222		++nusers;
223		if (wcmd == 0)
224			continue;
225		if (sel_users) {
226			int usermatch;
227			char **user;
228
229			usermatch = 0;
230			for (user = sel_users; !usermatch && *user; user++)
231				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
232					usermatch = 1;
233			if (!usermatch)
234				continue;
235		}
236		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
237			errx(1, "calloc");
238		*nextp = ep;
239		nextp = &ep->next;
240		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
241		ep->tdev = stp->st_rdev;
242		/*
243		 * If this is the console device, attempt to ascertain
244		 * the true console device dev_t.
245		 */
246		if (ep->tdev == 0) {
247			size_t size;
248
249			size = sizeof(dev_t);
250			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
251		}
252		touched = stp->st_atime;
253		if (touched < ep->utmp.ut_time) {
254			/* tty untouched since before login */
255			touched = ep->utmp.ut_time;
256		}
257		if ((ep->idle = now - touched) < 0)
258			ep->idle = 0;
259	}
260	(void)fclose(ut);
261
262	if (header || wcmd == 0) {
263		pr_header(&now, nusers);
264		if (wcmd == 0) {
265			(void)kvm_close(kd);
266			exit(0);
267		}
268
269#define HEADER_USER		"USER"
270#define HEADER_TTY		"TTY"
271#define HEADER_FROM		"FROM"
272#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
273#define HEADER_WHAT		"WHAT\n"
274#define WUSED  (UT_NAMESIZE + UT_LINESIZE + W_DISPHOSTSIZE + \
275		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
276		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
277				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
278				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
279				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
280				HEADER_LOGIN_IDLE HEADER_WHAT);
281	}
282
283	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
284		err(1, "%s", kvm_geterr(kd));
285	for (i = 0; i < nentries; i++, kp++) {
286		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
287			continue;
288		for (ep = ehead; ep != NULL; ep = ep->next) {
289			if (ep->tdev == kp->ki_tdev) {
290				/*
291				 * proc is associated with this terminal
292				 */
293				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
294					/*
295					 * Proc is 'most interesting'
296					 */
297					if (proc_compare(ep->kp, kp))
298						ep->kp = kp;
299				}
300				/*
301				 * Proc debug option info; add to debug
302				 * list using kinfo_proc ki_spare[0]
303				 * as next pointer; ptr to ptr avoids the
304				 * ptr = long assumption.
305				 */
306				dkp = ep->dkp;
307				ep->dkp = kp;
308				debugproc(kp) = dkp;
309			}
310		}
311	}
312	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
313	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
314	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
315	       ttywidth = 79;
316        else
317	       ttywidth = ws.ws_col - 1;
318	argwidth = ttywidth - WUSED;
319	if (argwidth < 4)
320		argwidth = 8;
321	for (ep = ehead; ep != NULL; ep = ep->next) {
322		if (ep->kp == NULL) {
323			ep->args = strdup("-");
324			continue;
325		}
326		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
327		    ep->kp->ki_comm, MAXCOMLEN);
328		if (ep->args == NULL)
329			err(1, NULL);
330	}
331	/* sort by idle time */
332	if (sortidle && ehead != NULL) {
333		struct entry *from, *save;
334
335		from = ehead;
336		ehead = NULL;
337		while (from != NULL) {
338			for (nextp = &ehead;
339			    (*nextp) && from->idle >= (*nextp)->idle;
340			    nextp = &(*nextp)->next)
341				continue;
342			save = from;
343			from = from->next;
344			save->next = *nextp;
345			*nextp = save;
346		}
347	}
348
349	for (ep = ehead; ep != NULL; ep = ep->next) {
350		char host_buf[UT_HOSTSIZE + 1];
351		struct sockaddr_storage ss;
352		struct sockaddr *sa = (struct sockaddr *)&ss;
353		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
354		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
355		time_t t;
356		int isaddr;
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_suffix = strrchr(p, ':')) != NULL) {
362			if ((dot = strchr(x_suffix, '.')) != NULL &&
363			    strchr(dot+1, '.') == NULL)
364				*x_suffix++ = '\0';
365			else
366				x_suffix = NULL;
367		}
368		if (!nflag) {
369			/* Attempt to change an IP address into a name */
370			isaddr = 0;
371			memset(&ss, '\0', sizeof(ss));
372			if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
373				lsin6->sin6_len = sizeof(*lsin6);
374				lsin6->sin6_family = AF_INET6;
375				isaddr = 1;
376			} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
377				lsin->sin_len = sizeof(*lsin);
378				lsin->sin_family = AF_INET;
379				isaddr = 1;
380			}
381			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
382			    sa->sa_len) == HOSTNAME_FOUND)
383				p = fn;
384		}
385		if (x_suffix) {
386			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
387			p = buf;
388		}
389		if (dflag) {
390			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
391				const 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		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
408		t = _time_to_time32(ep->utmp.ut_time);
409		pr_attime(&t, &now);
410		longidle = pr_idle(ep->idle);
411		(void)printf("%.*s\n", argwidth - longidle, ep->args);
412	}
413	(void)kvm_close(kd);
414	exit(0);
415}
416
417static void
418pr_header(time_t *nowp, int nusers)
419{
420	double avenrun[3];
421	time_t uptime;
422	struct timespec tp;
423	int days, hrs, i, mins, secs;
424	char buf[256];
425
426	/*
427	 * Print time of day.
428	 */
429	if (strftime(buf, sizeof(buf),
430	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
431		(void)printf("%s ", buf);
432	/*
433	 * Print how long system has been up.
434	 */
435	if (clock_gettime(CLOCK_MONOTONIC, &tp) != -1) {
436		uptime = tp.tv_sec;
437		if (uptime > 60)
438			uptime += 30;
439		days = uptime / 86400;
440		uptime %= 86400;
441		hrs = uptime / 3600;
442		uptime %= 3600;
443		mins = uptime / 60;
444		secs = uptime % 60;
445		(void)printf(" up");
446		if (days > 0)
447			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
448		if (hrs > 0 && mins > 0)
449			(void)printf(" %2d:%02d,", hrs, mins);
450		else if (hrs > 0)
451			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
452		else if (mins > 0)
453			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
454		else
455			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
456	}
457
458	/* Print number of users logged in to system */
459	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
460
461	/*
462	 * Print 1, 5, and 15 minute load averages.
463	 */
464	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
465		(void)printf(", no load average information available\n");
466	else {
467		(void)printf(", load averages:");
468		for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) {
469			if (use_comma && i > 0)
470				(void)printf(",");
471			(void)printf(" %.2f", avenrun[i]);
472		}
473		(void)printf("\n");
474	}
475}
476
477static struct stat *
478ttystat(char *line, int sz)
479{
480	static struct stat sb;
481	char ttybuf[MAXPATHLEN];
482
483	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
484	if (stat(ttybuf, &sb) == 0) {
485		return (&sb);
486	} else
487		return (NULL);
488}
489
490static void
491usage(int wcmd)
492{
493	if (wcmd)
494		(void)fprintf(stderr,
495		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
496	else
497		(void)fprintf(stderr, "usage: uptime\n");
498	exit(1);
499}
500
501static int
502this_is_uptime(const char *s)
503{
504	const char *u;
505
506	if ((u = strrchr(s, '/')) != NULL)
507		++u;
508	else
509		u = s;
510	if (strcmp(u, "uptime") == 0)
511		return (0);
512	return (-1);
513}
514