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