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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31
32__FBSDID("$FreeBSD$");
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
39
40#ifndef lint
41static const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
42#endif
43
44/*
45 * w - print system status (who and what)
46 *
47 * This program is similar to the systat command on Tenex/Tops 10/20
48 *
49 */
50#include <sys/param.h>
51#include <sys/time.h>
52#include <sys/stat.h>
53#include <sys/sysctl.h>
54#include <sys/proc.h>
55#include <sys/user.h>
56#include <sys/ioctl.h>
57#include <sys/socket.h>
58#include <sys/tty.h>
59
60#include <machine/cpu.h>
61#include <netinet/in.h>
62#include <arpa/inet.h>
63#include <arpa/nameser.h>
64
65#include <ctype.h>
66#include <err.h>
67#include <errno.h>
68#include <fcntl.h>
69#include <kvm.h>
70#include <langinfo.h>
71#include <libutil.h>
72#include <limits.h>
73#include <locale.h>
74#include <netdb.h>
75#include <nlist.h>
76#include <paths.h>
77#include <resolv.h>
78#include <stdio.h>
79#include <stdlib.h>
80#include <string.h>
81#include <timeconv.h>
82#include <unistd.h>
83#include <utmpx.h>
84#include <vis.h>
85
86#include "extern.h"
87
88static struct utmpx *utmp;
89static struct winsize ws;
90static kvm_t   *kd;
91static time_t	now;		/* the current time of day */
92static int	ttywidth;	/* width of tty */
93static int	argwidth;	/* width of tty */
94static int	header = 1;	/* true if -h flag: don't print heading */
95static int	nflag;		/* true if -n flag: don't convert addrs */
96static int	dflag;		/* true if -d flag: output debug info */
97static int	sortidle;	/* sort by idle time */
98int		use_ampm;	/* use AM/PM time */
99static int	use_comma;      /* use comma as floats separator */
100static char   **sel_users;	/* login array of particular users selected */
101
102/*
103 * One of these per active utmp entry.
104 */
105static struct entry {
106	struct	entry *next;
107	struct	utmpx utmp;
108	dev_t	tdev;			/* dev_t of terminal */
109	time_t	idle;			/* idle time of terminal in seconds */
110	struct	kinfo_proc *kp;		/* `most interesting' proc */
111	char	*args;			/* arg list of interesting process */
112	struct	kinfo_proc *dkp;	/* debug option proc list */
113} *ep, *ehead = NULL, **nextp = &ehead;
114
115#define	debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
116
117#define	W_DISPUSERSIZE	10
118#define	W_DISPLINESIZE	8
119#define	W_DISPHOSTSIZE	24
120
121static void		 pr_header(time_t *, int);
122static struct stat	*ttystat(char *);
123static void		 usage(int);
124static int		 this_is_uptime(const char *s);
125
126char *fmt_argv(char **, char *, char *, size_t);	/* ../../bin/ps/fmt.c */
127
128int
129main(int argc, char *argv[])
130{
131	struct kinfo_proc *kp;
132	struct kinfo_proc *dkp;
133	struct stat *stp;
134	time_t touched;
135	int ch, i, nentries, nusers, wcmd, longidle, longattime;
136	const char *memf, *nlistf, *p;
137	char *x_suffix;
138	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
139	char fn[MAXHOSTNAMELEN];
140	char *dot;
141
142	(void)setlocale(LC_ALL, "");
143	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
144	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
145
146	/* Are we w(1) or uptime(1)? */
147	if (this_is_uptime(argv[0]) == 0) {
148		wcmd = 0;
149		p = "";
150	} else {
151		wcmd = 1;
152		p = "dhiflM:N:nsuw";
153	}
154
155	memf = _PATH_DEVNULL;
156	nlistf = NULL;
157	while ((ch = getopt(argc, argv, p)) != -1)
158		switch (ch) {
159		case 'd':
160			dflag = 1;
161			break;
162		case 'h':
163			header = 0;
164			break;
165		case 'i':
166			sortidle = 1;
167			break;
168		case 'M':
169			header = 0;
170			memf = optarg;
171			break;
172		case 'N':
173			nlistf = optarg;
174			break;
175		case 'n':
176			nflag = 1;
177			break;
178		case 'f': case 'l': case 's': case 'u': case 'w':
179			warnx("[-flsuw] no longer supported");
180			/* FALLTHROUGH */
181		case '?':
182		default:
183			usage(wcmd);
184		}
185	argc -= optind;
186	argv += optind;
187
188	if (!(_res.options & RES_INIT))
189		res_init();
190	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
191	_res.retry = 1;		/* only try once.. */
192
193	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
194		errx(1, "%s", errbuf);
195
196	(void)time(&now);
197
198	if (*argv)
199		sel_users = argv;
200
201	setutxent();
202	for (nusers = 0; (utmp = getutxent()) != NULL;) {
203		if (utmp->ut_type != USER_PROCESS)
204			continue;
205		if (!(stp = ttystat(utmp->ut_line)))
206			continue;	/* corrupted record */
207		++nusers;
208		if (wcmd == 0)
209			continue;
210		if (sel_users) {
211			int usermatch;
212			char **user;
213
214			usermatch = 0;
215			for (user = sel_users; !usermatch && *user; user++)
216				if (!strcmp(utmp->ut_user, *user))
217					usermatch = 1;
218			if (!usermatch)
219				continue;
220		}
221		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
222			errx(1, "calloc");
223		*nextp = ep;
224		nextp = &ep->next;
225		memmove(&ep->utmp, utmp, sizeof *utmp);
226		ep->tdev = stp->st_rdev;
227		/*
228		 * If this is the console device, attempt to ascertain
229		 * the true console device dev_t.
230		 */
231		if (ep->tdev == 0) {
232			size_t size;
233
234			size = sizeof(dev_t);
235			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
236		}
237		touched = stp->st_atime;
238		if (touched < ep->utmp.ut_tv.tv_sec) {
239			/* tty untouched since before login */
240			touched = ep->utmp.ut_tv.tv_sec;
241		}
242		if ((ep->idle = now - touched) < 0)
243			ep->idle = 0;
244	}
245	endutxent();
246
247	if (header || wcmd == 0) {
248		pr_header(&now, nusers);
249		if (wcmd == 0) {
250			(void)kvm_close(kd);
251			exit(0);
252		}
253
254#define HEADER_USER		"USER"
255#define HEADER_TTY		"TTY"
256#define HEADER_FROM		"FROM"
257#define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
258#define HEADER_WHAT		"WHAT\n"
259#define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \
260		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
261		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
262				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
263				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
264				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
265				HEADER_LOGIN_IDLE HEADER_WHAT);
266	}
267
268	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
269		err(1, "%s", kvm_geterr(kd));
270	for (i = 0; i < nentries; i++, kp++) {
271		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
272		    kp->ki_tdev == NODEV)
273			continue;
274		for (ep = ehead; ep != NULL; ep = ep->next) {
275			if (ep->tdev == kp->ki_tdev) {
276				/*
277				 * proc is associated with this terminal
278				 */
279				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
280					/*
281					 * Proc is 'most interesting'
282					 */
283					if (proc_compare(ep->kp, kp))
284						ep->kp = kp;
285				}
286				/*
287				 * Proc debug option info; add to debug
288				 * list using kinfo_proc ki_spare[0]
289				 * as next pointer; ptr to ptr avoids the
290				 * ptr = long assumption.
291				 */
292				dkp = ep->dkp;
293				ep->dkp = kp;
294				debugproc(kp) = dkp;
295			}
296		}
297	}
298	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
299	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
300	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
301	       ttywidth = 79;
302        else
303	       ttywidth = ws.ws_col - 1;
304	argwidth = ttywidth - WUSED;
305	if (argwidth < 4)
306		argwidth = 8;
307	for (ep = ehead; ep != NULL; ep = ep->next) {
308		if (ep->kp == NULL) {
309			ep->args = strdup("-");
310			continue;
311		}
312		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
313		    ep->kp->ki_comm, NULL, MAXCOMLEN);
314		if (ep->args == NULL)
315			err(1, NULL);
316	}
317	/* sort by idle time */
318	if (sortidle && ehead != NULL) {
319		struct entry *from, *save;
320
321		from = ehead;
322		ehead = NULL;
323		while (from != NULL) {
324			for (nextp = &ehead;
325			    (*nextp) && from->idle >= (*nextp)->idle;
326			    nextp = &(*nextp)->next)
327				continue;
328			save = from;
329			from = from->next;
330			save->next = *nextp;
331			*nextp = save;
332		}
333	}
334
335	for (ep = ehead; ep != NULL; ep = ep->next) {
336		struct addrinfo hints, *res;
337		struct sockaddr_storage ss;
338		struct sockaddr *sa = (struct sockaddr *)&ss;
339		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
340		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
341		time_t t;
342		int isaddr;
343
344		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
345		if ((x_suffix = strrchr(p, ':')) != NULL) {
346			if ((dot = strchr(x_suffix, '.')) != NULL &&
347			    strchr(dot+1, '.') == NULL)
348				*x_suffix++ = '\0';
349			else
350				x_suffix = NULL;
351		}
352
353		isaddr = 0;
354		memset(&ss, '\0', sizeof(ss));
355		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
356			lsin6->sin6_len = sizeof(*lsin6);
357			lsin6->sin6_family = AF_INET6;
358			isaddr = 1;
359		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
360			lsin->sin_len = sizeof(*lsin);
361			lsin->sin_family = AF_INET;
362			isaddr = 1;
363		}
364		if (!nflag) {
365			/* Attempt to change an IP address into a name */
366			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
367			    sa->sa_len) == HOSTNAME_FOUND)
368				p = fn;
369		} else if (!isaddr) {
370			/*
371			 * If a host has only one A/AAAA RR, change a
372			 * name into an IP address
373			 */
374			memset(&hints, 0, sizeof(hints));
375			hints.ai_flags = AI_PASSIVE;
376			hints.ai_family = AF_UNSPEC;
377			hints.ai_socktype = SOCK_STREAM;
378			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
379				if (res->ai_next == NULL &&
380				    getnameinfo(res->ai_addr, res->ai_addrlen,
381					fn, sizeof(fn), NULL, 0,
382					NI_NUMERICHOST) == 0)
383					p = fn;
384				freeaddrinfo(res);
385			}
386		}
387
388		if (x_suffix) {
389			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
390			p = buf;
391		}
392		if (dflag) {
393			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
394				const char *ptr;
395
396				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
397				    dkp->ki_comm, NULL, MAXCOMLEN);
398				if (ptr == NULL)
399					ptr = "-";
400				(void)printf("\t\t%-9d %s\n",
401				    dkp->ki_pid, ptr);
402			}
403		}
404		(void)printf("%-*.*s %-*.*s %-*.*s ",
405		    W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
406		    W_DISPLINESIZE, W_DISPLINESIZE,
407		    *ep->utmp.ut_line ?
408		    (strncmp(ep->utmp.ut_line, "tty", 3) &&
409		    strncmp(ep->utmp.ut_line, "cua", 3) ?
410		    ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-",
411		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
412		t = ep->utmp.ut_tv.tv_sec;
413		longattime = pr_attime(&t, &now);
414		longidle = pr_idle(ep->idle);
415		(void)printf("%.*s\n", argwidth - longidle - longattime,
416		    ep->args);
417	}
418	(void)kvm_close(kd);
419	exit(0);
420}
421
422static void
423pr_header(time_t *nowp, int nusers)
424{
425	double avenrun[3];
426	time_t uptime;
427	struct timespec tp;
428	int days, hrs, i, mins, secs;
429	char buf[256];
430
431	/*
432	 * Print time of day.
433	 */
434	if (strftime(buf, sizeof(buf),
435	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
436		(void)printf("%s ", buf);
437	/*
438	 * Print how long system has been up.
439	 */
440	if (clock_gettime(CLOCK_UPTIME, &tp) != -1) {
441		uptime = tp.tv_sec;
442		if (uptime > 60)
443			uptime += 30;
444		days = uptime / 86400;
445		uptime %= 86400;
446		hrs = uptime / 3600;
447		uptime %= 3600;
448		mins = uptime / 60;
449		secs = uptime % 60;
450		(void)printf(" up");
451		if (days > 0)
452			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
453		if (hrs > 0 && mins > 0)
454			(void)printf(" %2d:%02d,", hrs, mins);
455		else if (hrs > 0)
456			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
457		else if (mins > 0)
458			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
459		else
460			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
461	}
462
463	/* Print number of users logged in to system */
464	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
465
466	/*
467	 * Print 1, 5, and 15 minute load averages.
468	 */
469	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
470		(void)printf(", no load average information available\n");
471	else {
472		(void)printf(", load averages:");
473		for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) {
474			if (use_comma && i > 0)
475				(void)printf(",");
476			(void)printf(" %.2f", avenrun[i]);
477		}
478		(void)printf("\n");
479	}
480}
481
482static struct stat *
483ttystat(char *line)
484{
485	static struct stat sb;
486	char ttybuf[MAXPATHLEN];
487
488	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
489	if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode)) {
490		return (&sb);
491	} else
492		return (NULL);
493}
494
495static void
496usage(int wcmd)
497{
498	if (wcmd)
499		(void)fprintf(stderr,
500		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
501	else
502		(void)fprintf(stderr, "usage: uptime\n");
503	exit(1);
504}
505
506static int
507this_is_uptime(const char *s)
508{
509	const char *u;
510
511	if ((u = strrchr(s, '/')) != NULL)
512		++u;
513	else
514		u = s;
515	if (strcmp(u, "uptime") == 0)
516		return (0);
517	return (-1);
518}
519