w.c revision 202199
1144046Sjcamou/*-
2144046Sjcamou * Copyright (c) 1980, 1991, 1993, 1994
3144046Sjcamou *	The Regents of the University of California.  All rights reserved.
4144046Sjcamou *
5144046Sjcamou * Redistribution and use in source and binary forms, with or without
6144046Sjcamou * modification, are permitted provided that the following conditions
7144046Sjcamou * are met:
8144046Sjcamou * 1. Redistributions of source code must retain the above copyright
9144046Sjcamou *    notice, this list of conditions and the following disclaimer.
10144046Sjcamou * 2. Redistributions in binary form must reproduce the above copyright
11144046Sjcamou *    notice, this list of conditions and the following disclaimer in the
12144046Sjcamou *    documentation and/or other materials provided with the distribution.
13144046Sjcamou * 3. All advertising materials mentioning features or use of this software
14144046Sjcamou *    must display the following acknowledgement:
15144046Sjcamou *	This product includes software developed by the University of
16144046Sjcamou *	California, Berkeley and its contributors.
17144046Sjcamou * 4. Neither the name of the University nor the names of its contributors
18144046Sjcamou *    may be used to endorse or promote products derived from this software
19144046Sjcamou *    without specific prior written permission.
20144046Sjcamou *
21144046Sjcamou * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22144046Sjcamou * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23144046Sjcamou * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24144046Sjcamou * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25144046Sjcamou * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26144046Sjcamou * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27164752Sjoel * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28144046Sjcamou * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29144046Sjcamou * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30144046Sjcamou * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31144046Sjcamou * SUCH DAMAGE.
32144046Sjcamou */
33144046Sjcamou
34152984Sjoel#include <sys/cdefs.h>
35152984Sjoel
36152984Sjoel__FBSDID("$FreeBSD: head/usr.bin/w/w.c 202199 2010-01-13 18:09:21Z ed $");
37144046Sjcamou
38144046Sjcamou#ifndef lint
39152984Sjoelstatic const char copyright[] =
40152984Sjoel"@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
41152984Sjoel	The Regents of the University of California.  All rights reserved.\n";
42152984Sjoel#endif
43152984Sjoel
44152984Sjoel#ifndef lint
45152984Sjoelstatic const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
46152984Sjoel#endif
47144046Sjcamou
48144046Sjcamou/*
49144046Sjcamou * w - print system status (who and what)
50144046Sjcamou *
51144046Sjcamou * This program is similar to the systat command on Tenex/Tops 10/20
52144046Sjcamou *
53144046Sjcamou */
54144046Sjcamou#include <sys/param.h>
55164752Sjoel#include <sys/time.h>
56164752Sjoel#include <sys/stat.h>
57164752Sjoel#include <sys/sysctl.h>
58164752Sjoel#include <sys/proc.h>
59164752Sjoel#include <sys/user.h>
60164752Sjoel#include <sys/ioctl.h>
61164752Sjoel#include <sys/socket.h>
62164752Sjoel#include <sys/tty.h>
63164752Sjoel
64164752Sjoel#include <machine/cpu.h>
65164752Sjoel#include <netinet/in.h>
66164752Sjoel#include <arpa/inet.h>
67164752Sjoel#include <arpa/nameser.h>
68164752Sjoel
69169495Sbrueffer#include <ctype.h>
70144046Sjcamou#include <err.h>
71144046Sjcamou#include <errno.h>
72144046Sjcamou#include <fcntl.h>
73144046Sjcamou#include <kvm.h>
74144046Sjcamou#include <langinfo.h>
75144046Sjcamou#include <libutil.h>
76144046Sjcamou#include <limits.h>
77144046Sjcamou#include <locale.h>
78144046Sjcamou#include <netdb.h>
79144046Sjcamou#include <nlist.h>
80144046Sjcamou#include <paths.h>
81144046Sjcamou#include <resolv.h>
82144046Sjcamou#include <stdio.h>
83144046Sjcamou#include <stdlib.h>
84144046Sjcamou#include <string.h>
85144046Sjcamou#include <timeconv.h>
86158014Sbrueffer#include <unistd.h>
87158014Sbrueffer#include <utmpx.h>
88144046Sjcamou#include <vis.h>
89144046Sjcamou
90144046Sjcamou#include "extern.h"
91144046Sjcamou
92144046Sjcamoustruct timeval	boottime;
93144046Sjcamoustruct utmpx   *utmp;
94144046Sjcamoustruct winsize	ws;
95144046Sjcamoukvm_t	       *kd;
96152890Sjoeltime_t		now;		/* the current time of day */
97152890Sjoelint		ttywidth;	/* width of tty */
98267938Sbaptint		argwidth;	/* width of tty */
99144046Sjcamouint		header = 1;	/* true if -h flag: don't print heading */
100147432Sruint		nflag;		/* true if -n flag: don't convert addrs */
101144046Sjcamouint		dflag;		/* true if -d flag: output debug info */
102147432Sruint		sortidle;	/* sort by idle time */
103144046Sjcamouint		use_ampm;	/* use AM/PM time */
104144046Sjcamouint             use_comma;      /* use comma as floats separator */
105144046Sjcamouchar	      **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	utmpx 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_udata)
121
122#define	W_DISPUSERSIZE	10
123#define	W_DISPLINESIZE	8
124#define	W_DISPHOSTSIZE	24
125
126static void		 pr_header(time_t *, int);
127static struct stat	*ttystat(char *);
128static void		 usage(int);
129static int		 this_is_uptime(const char *s);
130
131char *fmt_argv(char **, char *, int);	/* ../../bin/ps/fmt.c */
132
133int
134main(int argc, char *argv[])
135{
136	struct kinfo_proc *kp;
137	struct kinfo_proc *dkp;
138	struct stat *stp;
139	time_t touched;
140	int ch, i, nentries, nusers, wcmd, longidle, longattime, dropgid;
141	const char *memf, *nlistf, *p;
142	char *x_suffix;
143	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
144	char fn[MAXHOSTNAMELEN];
145	char *dot;
146
147	(void)setlocale(LC_ALL, "");
148	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
149	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
150
151	/* Are we w(1) or uptime(1)? */
152	if (this_is_uptime(argv[0]) == 0) {
153		wcmd = 0;
154		p = "";
155	} else {
156		wcmd = 1;
157		p = "dhiflM:N:nsuw";
158	}
159
160	dropgid = 0;
161	memf = nlistf = _PATH_DEVNULL;
162	while ((ch = getopt(argc, argv, p)) != -1)
163		switch (ch) {
164		case 'd':
165			dflag = 1;
166			break;
167		case 'h':
168			header = 0;
169			break;
170		case 'i':
171			sortidle = 1;
172			break;
173		case 'M':
174			header = 0;
175			memf = optarg;
176			dropgid = 1;
177			break;
178		case 'N':
179			nlistf = optarg;
180			dropgid = 1;
181			break;
182		case 'n':
183			nflag = 1;
184			break;
185		case 'f': case 'l': case 's': case 'u': case 'w':
186			warnx("[-flsuw] no longer supported");
187			/* FALLTHROUGH */
188		case '?':
189		default:
190			usage(wcmd);
191		}
192	argc -= optind;
193	argv += optind;
194
195	if (!(_res.options & RES_INIT))
196		res_init();
197	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
198	_res.retry = 1;		/* only try once.. */
199
200	/*
201	 * Discard setgid privileges if not the running kernel so that bad
202	 * guys can't print interesting stuff from kernel memory.
203	 */
204	if (dropgid)
205		setgid(getgid());
206
207	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
208		errx(1, "%s", errbuf);
209
210	(void)time(&now);
211
212	if (*argv)
213		sel_users = argv;
214
215	setutxent();
216	for (nusers = 0; (utmp = getutxent()) != NULL;) {
217		if (utmp->ut_type != USER_PROCESS)
218			continue;
219		if (!(stp = ttystat(utmp->ut_line)))
220			continue;	/* corrupted record */
221		++nusers;
222		if (wcmd == 0)
223			continue;
224		if (sel_users) {
225			int usermatch;
226			char **user;
227
228			usermatch = 0;
229			for (user = sel_users; !usermatch && *user; user++)
230				if (!strcmp(utmp->ut_user, *user))
231					usermatch = 1;
232			if (!usermatch)
233				continue;
234		}
235		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
236			errx(1, "calloc");
237		*nextp = ep;
238		nextp = &ep->next;
239		memmove(&ep->utmp, utmp, sizeof *utmp);
240		ep->tdev = stp->st_rdev;
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			size_t size;
247
248			size = sizeof(dev_t);
249			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
250		}
251		touched = stp->st_atime;
252		if (touched < ep->utmp.ut_tv.tv_sec) {
253			/* tty untouched since before login */
254			touched = ep->utmp.ut_tv.tv_sec;
255		}
256		if ((ep->idle = now - touched) < 0)
257			ep->idle = 0;
258	}
259	endutxent();
260
261	if (header || wcmd == 0) {
262		pr_header(&now, nusers);
263		if (wcmd == 0) {
264			(void)kvm_close(kd);
265			exit(0);
266		}
267
268#define HEADER_USER		"USER"
269#define HEADER_TTY		"TTY"
270#define HEADER_FROM		"FROM"
271#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
272#define HEADER_WHAT		"WHAT\n"
273#define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \
274		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
275		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
276				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
277				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
278				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
279				HEADER_LOGIN_IDLE HEADER_WHAT);
280	}
281
282	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
283		err(1, "%s", kvm_geterr(kd));
284	for (i = 0; i < nentries; i++, kp++) {
285		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
286		    kp->ki_tdev == NODEV)
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		struct addrinfo hints, *res;
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		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
359		if ((x_suffix = strrchr(p, ':')) != NULL) {
360			if ((dot = strchr(x_suffix, '.')) != NULL &&
361			    strchr(dot+1, '.') == NULL)
362				*x_suffix++ = '\0';
363			else
364				x_suffix = NULL;
365		}
366
367		isaddr = 0;
368		memset(&ss, '\0', sizeof(ss));
369		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
370			lsin6->sin6_len = sizeof(*lsin6);
371			lsin6->sin6_family = AF_INET6;
372			isaddr = 1;
373		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
374			lsin->sin_len = sizeof(*lsin);
375			lsin->sin_family = AF_INET;
376			isaddr = 1;
377		}
378		if (!nflag) {
379			/* Attempt to change an IP address into a name */
380			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
381			    sa->sa_len) == HOSTNAME_FOUND)
382				p = fn;
383		} else if (!isaddr) {
384			/*
385			 * If a host has only one A/AAAA RR, change a
386			 * name into an IP address
387			 */
388			memset(&hints, 0, sizeof(hints));
389			hints.ai_flags = AI_PASSIVE;
390			hints.ai_family = AF_UNSPEC;
391			hints.ai_socktype = SOCK_STREAM;
392			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
393				if (res->ai_next == NULL &&
394				    getnameinfo(res->ai_addr, res->ai_addrlen,
395					fn, sizeof(fn), NULL, 0,
396					NI_NUMERICHOST) == 0)
397					p = fn;
398				freeaddrinfo(res);
399			}
400		}
401
402		if (x_suffix) {
403			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
404			p = buf;
405		}
406		if (dflag) {
407			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
408				const char *ptr;
409
410				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
411				    dkp->ki_comm, MAXCOMLEN);
412				if (ptr == NULL)
413					ptr = "-";
414				(void)printf("\t\t%-9d %s\n",
415				    dkp->ki_pid, ptr);
416			}
417		}
418		(void)printf("%-*.*s %-*.*s %-*.*s ",
419		    W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
420		    W_DISPLINESIZE, W_DISPLINESIZE,
421		    *ep->utmp.ut_line ?
422		    (strncmp(ep->utmp.ut_line, "tty", 3) &&
423		    strncmp(ep->utmp.ut_line, "cua", 3) ?
424		    ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-",
425		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
426		t = ep->utmp.ut_tv.tv_sec;
427		longattime = pr_attime(&t, &now);
428		longidle = pr_idle(ep->idle);
429		(void)printf("%.*s\n", argwidth - longidle - longattime,
430		    ep->args);
431	}
432	(void)kvm_close(kd);
433	exit(0);
434}
435
436static void
437pr_header(time_t *nowp, int nusers)
438{
439	double avenrun[3];
440	time_t uptime;
441	struct timespec tp;
442	int days, hrs, i, mins, secs;
443	char buf[256];
444
445	/*
446	 * Print time of day.
447	 */
448	if (strftime(buf, sizeof(buf),
449	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
450		(void)printf("%s ", buf);
451	/*
452	 * Print how long system has been up.
453	 */
454	if (clock_gettime(CLOCK_MONOTONIC, &tp) != -1) {
455		uptime = tp.tv_sec;
456		if (uptime > 60)
457			uptime += 30;
458		days = uptime / 86400;
459		uptime %= 86400;
460		hrs = uptime / 3600;
461		uptime %= 3600;
462		mins = uptime / 60;
463		secs = uptime % 60;
464		(void)printf(" up");
465		if (days > 0)
466			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
467		if (hrs > 0 && mins > 0)
468			(void)printf(" %2d:%02d,", hrs, mins);
469		else if (hrs > 0)
470			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
471		else if (mins > 0)
472			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
473		else
474			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
475	}
476
477	/* Print number of users logged in to system */
478	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
479
480	/*
481	 * Print 1, 5, and 15 minute load averages.
482	 */
483	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
484		(void)printf(", no load average information available\n");
485	else {
486		(void)printf(", load averages:");
487		for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) {
488			if (use_comma && i > 0)
489				(void)printf(",");
490			(void)printf(" %.2f", avenrun[i]);
491		}
492		(void)printf("\n");
493	}
494}
495
496static struct stat *
497ttystat(char *line)
498{
499	static struct stat sb;
500	char ttybuf[MAXPATHLEN];
501
502	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
503	if (stat(ttybuf, &sb) == 0) {
504		return (&sb);
505	} else
506		return (NULL);
507}
508
509static void
510usage(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(const char *s)
522{
523	const char *u;
524
525	if ((u = strrchr(s, '/')) != NULL)
526		++u;
527	else
528		u = s;
529	if (strcmp(u, "uptime") == 0)
530		return (0);
531	return (-1);
532}
533