xref: /freebsd/usr.bin/w/w.c (revision 941e286383714ef25f1ffe9ba6ae5040afdd7060)
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$");
37 
38 #ifndef lint
39 static 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
45 static 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 <timeconv.h>
86 #define	_ULOG_POSIX_NAMES
87 #include <ulog.h>
88 #include <unistd.h>
89 #include <vis.h>
90 
91 #include "extern.h"
92 
93 struct timeval	boottime;
94 struct utmpx   *utmp;
95 struct winsize	ws;
96 kvm_t	       *kd;
97 time_t		now;		/* the current time of day */
98 int		ttywidth;	/* width of tty */
99 int		argwidth;	/* width of tty */
100 int		header = 1;	/* true if -h flag: don't print heading */
101 int		nflag;		/* true if -n flag: don't convert addrs */
102 int		dflag;		/* true if -d flag: output debug info */
103 int		sortidle;	/* sort by idle time */
104 int		use_ampm;	/* use AM/PM time */
105 int             use_comma;      /* use comma as floats separator */
106 char	      **sel_users;	/* login array of particular users selected */
107 
108 /*
109  * One of these per active utmp entry.
110  */
111 struct	entry {
112 	struct	entry *next;
113 	struct	utmpx utmp;
114 	dev_t	tdev;			/* dev_t of terminal */
115 	time_t	idle;			/* idle time of terminal in seconds */
116 	struct	kinfo_proc *kp;		/* `most interesting' proc */
117 	char	*args;			/* arg list of interesting process */
118 	struct	kinfo_proc *dkp;	/* debug option proc list */
119 } *ep, *ehead = NULL, **nextp = &ehead;
120 
121 #define	debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
122 
123 #define	W_DISPUSERSIZE	10
124 #define	W_DISPLINESIZE	8
125 #define	W_DISPHOSTSIZE	24
126 
127 static void		 pr_header(time_t *, int);
128 static struct stat	*ttystat(char *);
129 static void		 usage(int);
130 static int		 this_is_uptime(const char *s);
131 
132 char *fmt_argv(char **, char *, int);	/* ../../bin/ps/fmt.c */
133 
134 int
135 main(int argc, char *argv[])
136 {
137 	struct kinfo_proc *kp;
138 	struct kinfo_proc *dkp;
139 	struct stat *stp;
140 	time_t touched;
141 	int ch, i, nentries, nusers, wcmd, longidle, longattime, dropgid;
142 	const char *memf, *nlistf, *p;
143 	char *x_suffix;
144 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
145 	char fn[MAXHOSTNAMELEN];
146 	char *dot;
147 
148 	(void)setlocale(LC_ALL, "");
149 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
150 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
151 
152 	/* Are we w(1) or uptime(1)? */
153 	if (this_is_uptime(argv[0]) == 0) {
154 		wcmd = 0;
155 		p = "";
156 	} else {
157 		wcmd = 1;
158 		p = "dhiflM:N:nsuw";
159 	}
160 
161 	dropgid = 0;
162 	memf = nlistf = _PATH_DEVNULL;
163 	while ((ch = getopt(argc, argv, p)) != -1)
164 		switch (ch) {
165 		case 'd':
166 			dflag = 1;
167 			break;
168 		case 'h':
169 			header = 0;
170 			break;
171 		case 'i':
172 			sortidle = 1;
173 			break;
174 		case 'M':
175 			header = 0;
176 			memf = optarg;
177 			dropgid = 1;
178 			break;
179 		case 'N':
180 			nlistf = optarg;
181 			dropgid = 1;
182 			break;
183 		case 'n':
184 			nflag = 1;
185 			break;
186 		case 'f': case 'l': case 's': case 'u': case 'w':
187 			warnx("[-flsuw] no longer supported");
188 			/* FALLTHROUGH */
189 		case '?':
190 		default:
191 			usage(wcmd);
192 		}
193 	argc -= optind;
194 	argv += optind;
195 
196 	if (!(_res.options & RES_INIT))
197 		res_init();
198 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
199 	_res.retry = 1;		/* only try once.. */
200 
201 	/*
202 	 * Discard setgid privileges if not the running kernel so that bad
203 	 * guys can't print interesting stuff from kernel memory.
204 	 */
205 	if (dropgid)
206 		setgid(getgid());
207 
208 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
209 		errx(1, "%s", errbuf);
210 
211 	(void)time(&now);
212 
213 	if (*argv)
214 		sel_users = argv;
215 
216 	setutxent();
217 	for (nusers = 0; (utmp = getutxent()) != NULL;) {
218 		if (utmp->ut_type != USER_PROCESS)
219 			continue;
220 		if (!(stp = ttystat(utmp->ut_line)))
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 (!strcmp(utmp->ut_user, *user))
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 *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_tv.tv_sec) {
254 			/* tty untouched since before login */
255 			touched = ep->utmp.ut_tv.tv_sec;
256 		}
257 		if ((ep->idle = now - touched) < 0)
258 			ep->idle = 0;
259 	}
260 	endutxent();
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  (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \
275 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
276 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
277 				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
278 				W_DISPLINESIZE, W_DISPLINESIZE, 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 		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 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
422 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
423 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
424 		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
425 		t = ep->utmp.ut_tv.tv_sec;
426 		longattime = pr_attime(&t, &now);
427 		longidle = pr_idle(ep->idle);
428 		(void)printf("%.*s\n", argwidth - longidle - longattime,
429 		    ep->args);
430 	}
431 	(void)kvm_close(kd);
432 	exit(0);
433 }
434 
435 static void
436 pr_header(time_t *nowp, int nusers)
437 {
438 	double avenrun[3];
439 	time_t uptime;
440 	struct timespec tp;
441 	int days, hrs, i, mins, secs;
442 	char buf[256];
443 
444 	/*
445 	 * Print time of day.
446 	 */
447 	if (strftime(buf, sizeof(buf),
448 	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
449 		(void)printf("%s ", buf);
450 	/*
451 	 * Print how long system has been up.
452 	 */
453 	if (clock_gettime(CLOCK_MONOTONIC, &tp) != -1) {
454 		uptime = tp.tv_sec;
455 		if (uptime > 60)
456 			uptime += 30;
457 		days = uptime / 86400;
458 		uptime %= 86400;
459 		hrs = uptime / 3600;
460 		uptime %= 3600;
461 		mins = uptime / 60;
462 		secs = uptime % 60;
463 		(void)printf(" up");
464 		if (days > 0)
465 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
466 		if (hrs > 0 && mins > 0)
467 			(void)printf(" %2d:%02d,", hrs, mins);
468 		else if (hrs > 0)
469 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
470 		else if (mins > 0)
471 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
472 		else
473 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
474 	}
475 
476 	/* Print number of users logged in to system */
477 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
478 
479 	/*
480 	 * Print 1, 5, and 15 minute load averages.
481 	 */
482 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
483 		(void)printf(", no load average information available\n");
484 	else {
485 		(void)printf(", load averages:");
486 		for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) {
487 			if (use_comma && i > 0)
488 				(void)printf(",");
489 			(void)printf(" %.2f", avenrun[i]);
490 		}
491 		(void)printf("\n");
492 	}
493 }
494 
495 static struct stat *
496 ttystat(char *line)
497 {
498 	static struct stat sb;
499 	char ttybuf[MAXPATHLEN];
500 
501 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
502 	if (stat(ttybuf, &sb) == 0) {
503 		return (&sb);
504 	} else
505 		return (NULL);
506 }
507 
508 static void
509 usage(int wcmd)
510 {
511 	if (wcmd)
512 		(void)fprintf(stderr,
513 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
514 	else
515 		(void)fprintf(stderr, "usage: uptime\n");
516 	exit(1);
517 }
518 
519 static int
520 this_is_uptime(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