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