xref: /freebsd/usr.bin/w/w.c (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
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 #include <sys/cdefs.h>
33 
34 __FBSDID("$FreeBSD$");
35 
36 #ifndef lint
37 static const char copyright[] =
38 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 #endif
41 
42 #ifndef lint
43 static const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
44 #endif
45 
46 /*
47  * w - print system status (who and what)
48  *
49  * This program is similar to the systat command on Tenex/Tops 10/20
50  *
51  */
52 #include <sys/param.h>
53 #include <sys/time.h>
54 #include <sys/stat.h>
55 #include <sys/sysctl.h>
56 #include <sys/proc.h>
57 #include <sys/user.h>
58 #include <sys/ioctl.h>
59 #include <sys/sbuf.h>
60 #include <sys/socket.h>
61 #include <sys/tty.h>
62 #include <sys/types.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 <libgen.h>
76 #include <libutil.h>
77 #include <limits.h>
78 #include <locale.h>
79 #include <netdb.h>
80 #include <nlist.h>
81 #include <paths.h>
82 #include <resolv.h>
83 #include <stdio.h>
84 #include <stdlib.h>
85 #include <string.h>
86 #include <timeconv.h>
87 #include <unistd.h>
88 #include <utmpx.h>
89 #include <vis.h>
90 #include <libxo/xo.h>
91 
92 #include "extern.h"
93 
94 static struct utmpx *utmp;
95 static struct winsize ws;
96 static kvm_t   *kd;
97 static time_t	now;		/* the current time of day */
98 static size_t	ttywidth;	/* width of tty */
99 static size_t	fromwidth = 0;	/* max width of "from" field */
100 static size_t	argwidth;	/* width of arguments */
101 static int	header = 1;	/* true if -h flag: don't print heading */
102 static int	nflag;		/* true if -n flag: don't convert addrs */
103 static int	dflag;		/* true if -d flag: output debug info */
104 static int	sortidle;	/* sort by idle time */
105 int		use_ampm;	/* use AM/PM time */
106 static int	use_comma;      /* use comma as floats separator */
107 static char   **sel_users;	/* login array of particular users selected */
108 
109 /*
110  * One of these per active utmp entry.
111  */
112 static struct entry {
113 	struct	entry *next;
114 	struct	utmpx utmp;
115 	dev_t	tdev;			/* dev_t of terminal */
116 	time_t	idle;			/* idle time of terminal in seconds */
117 	struct	kinfo_proc *kp;		/* `most interesting' proc */
118 	char	*args;			/* arg list of interesting process */
119 	struct	kinfo_proc *dkp;	/* debug option proc list */
120 	char	*from;			/* "from": name or addr */
121 	char	*save_from;		/* original "from": name or addr */
122 } *ep, *ehead = NULL, **nextp = &ehead;
123 
124 #define	debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
125 
126 #define	W_DISPUSERSIZE	10
127 #define	W_DISPLINESIZE	8
128 #define	W_MAXHOSTSIZE	40
129 
130 static void		 pr_header(time_t *, int);
131 static struct stat	*ttystat(char *);
132 static void		 usage(int);
133 
134 char *fmt_argv(char **, char *, char *, size_t);	/* ../../bin/ps/fmt.c */
135 
136 int
137 main(int argc, char *argv[])
138 {
139 	struct kinfo_proc *kp;
140 	struct kinfo_proc *dkp;
141 	struct stat *stp;
142 	time_t touched;
143 	size_t width;
144 	int ch, i, nentries, nusers, wcmd, longidle, longattime;
145 	const char *memf, *nlistf, *p, *save_p;
146 	char *x_suffix;
147 	char errbuf[_POSIX2_LINE_MAX];
148 	char buf[MAXHOSTNAMELEN], fn[MAXHOSTNAMELEN];
149 	char *dot;
150 
151 	(void)setlocale(LC_ALL, "");
152 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
153 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
154 
155 	argc = xo_parse_args(argc, argv);
156 	if (argc < 0)
157 		exit(1);
158 
159 	/* Are we w(1) or uptime(1)? */
160 	if (strcmp(basename(argv[0]), "uptime") == 0) {
161 		wcmd = 0;
162 		p = "";
163 	} else {
164 		wcmd = 1;
165 		p = "dhiflM:N:nsuw";
166 	}
167 
168 	memf = _PATH_DEVNULL;
169 	nlistf = NULL;
170 	while ((ch = getopt(argc, argv, p)) != -1)
171 		switch (ch) {
172 		case 'd':
173 			dflag = 1;
174 			break;
175 		case 'h':
176 			header = 0;
177 			break;
178 		case 'i':
179 			sortidle = 1;
180 			break;
181 		case 'M':
182 			header = 0;
183 			memf = optarg;
184 			break;
185 		case 'N':
186 			nlistf = optarg;
187 			break;
188 		case 'n':
189 			nflag += 1;
190 			break;
191 		case 'f': case 'l': case 's': case 'u': case 'w':
192 			warnx("-%c no longer supported", ch);
193 			/* FALLTHROUGH */
194 		case '?':
195 		default:
196 			usage(wcmd);
197 		}
198 	argc -= optind;
199 	argv += optind;
200 
201 	if (!(_res.options & RES_INIT))
202 		res_init();
203 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
204 	_res.retry = 1;		/* only try once.. */
205 
206 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
207 		errx(1, "%s", errbuf);
208 
209 	(void)time(&now);
210 
211 	if (*argv)
212 		sel_users = argv;
213 
214 	setutxent();
215 	for (nusers = 0; (utmp = getutxent()) != NULL;) {
216 		struct addrinfo hints, *res;
217 		struct sockaddr_storage ss;
218 		struct sockaddr *sa = (struct sockaddr *)&ss;
219 		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
220 		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
221 		int isaddr;
222 
223 		if (utmp->ut_type != USER_PROCESS)
224 			continue;
225 		if (!(stp = ttystat(utmp->ut_line)))
226 			continue;	/* corrupted record */
227 		++nusers;
228 		if (wcmd == 0)
229 			continue;
230 		if (sel_users) {
231 			int usermatch;
232 			char **user;
233 
234 			usermatch = 0;
235 			for (user = sel_users; !usermatch && *user; user++)
236 				if (!strcmp(utmp->ut_user, *user))
237 					usermatch = 1;
238 			if (!usermatch)
239 				continue;
240 		}
241 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
242 			errx(1, "calloc");
243 		*nextp = ep;
244 		nextp = &ep->next;
245 		memmove(&ep->utmp, utmp, sizeof *utmp);
246 		ep->tdev = stp->st_rdev;
247 		/*
248 		 * If this is the console device, attempt to ascertain
249 		 * the true console device dev_t.
250 		 */
251 		if (ep->tdev == 0) {
252 			size_t size;
253 
254 			size = sizeof(dev_t);
255 			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
256 		}
257 		touched = stp->st_atime;
258 		if (touched < ep->utmp.ut_tv.tv_sec) {
259 			/* tty untouched since before login */
260 			touched = ep->utmp.ut_tv.tv_sec;
261 		}
262 		if ((ep->idle = now - touched) < 0)
263 			ep->idle = 0;
264 
265 		save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
266 		if ((x_suffix = strrchr(p, ':')) != NULL) {
267 			if ((dot = strchr(x_suffix, '.')) != NULL &&
268 			    strchr(dot+1, '.') == NULL)
269 				*x_suffix++ = '\0';
270 			else
271 				x_suffix = NULL;
272 		}
273 
274 		isaddr = 0;
275 		memset(&ss, '\0', sizeof(ss));
276 		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
277 			lsin6->sin6_len = sizeof(*lsin6);
278 			lsin6->sin6_family = AF_INET6;
279 			isaddr = 1;
280 		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
281 			lsin->sin_len = sizeof(*lsin);
282 			lsin->sin_family = AF_INET;
283 			isaddr = 1;
284 		}
285 		if (nflag == 0) {
286 			/* Attempt to change an IP address into a name */
287 			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
288 			    sa->sa_len) == HOSTNAME_FOUND)
289 				p = fn;
290 		} else if (!isaddr && nflag > 1) {
291 			/*
292 			 * If a host has only one A/AAAA RR, change a
293 			 * name into an IP address
294 			 */
295 			memset(&hints, 0, sizeof(hints));
296 			hints.ai_flags = AI_PASSIVE;
297 			hints.ai_family = AF_UNSPEC;
298 			hints.ai_socktype = SOCK_STREAM;
299 			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
300 				if (res->ai_next == NULL &&
301 				    getnameinfo(res->ai_addr, res->ai_addrlen,
302 					fn, sizeof(fn), NULL, 0,
303 					NI_NUMERICHOST) == 0)
304 					p = fn;
305 				freeaddrinfo(res);
306 			}
307 		}
308 
309 		if (x_suffix) {
310 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
311 			p = buf;
312 		}
313 		ep->from = strdup(p);
314 		if ((width = strlen(p)) > fromwidth)
315 			fromwidth = width;
316 		if (save_p != p)
317 			ep->save_from = strdup(save_p);
318 	}
319 	endutxent();
320 
321 #define HEADER_USER		"USER"
322 #define HEADER_TTY		"TTY"
323 #define HEADER_FROM		"FROM"
324 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
325 #define HEADER_WHAT		"WHAT\n"
326 #define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + fromwidth + \
327 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
328 
329 	if (sizeof(HEADER_FROM) > fromwidth)
330 		fromwidth = sizeof(HEADER_FROM);
331 	fromwidth++;
332 	if (fromwidth > W_MAXHOSTSIZE)
333 		fromwidth = W_MAXHOSTSIZE;
334 
335 	xo_open_container("uptime-information");
336 
337 	if (header || wcmd == 0) {
338 		pr_header(&now, nusers);
339 		if (wcmd == 0) {
340 			xo_close_container("uptime-information");
341 			xo_finish();
342 			(void)kvm_close(kd);
343 			exit(0);
344 		}
345 
346 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s}  {T:/%s}",
347 				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
348 				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
349 				fromwidth, fromwidth, HEADER_FROM,
350 				HEADER_LOGIN_IDLE HEADER_WHAT);
351 	}
352 
353 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
354 		err(1, "%s", kvm_geterr(kd));
355 	for (i = 0; i < nentries; i++, kp++) {
356 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
357 		    kp->ki_tdev == NODEV)
358 			continue;
359 		for (ep = ehead; ep != NULL; ep = ep->next) {
360 			if (ep->tdev == kp->ki_tdev) {
361 				/*
362 				 * proc is associated with this terminal
363 				 */
364 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
365 					/*
366 					 * Proc is 'most interesting'
367 					 */
368 					if (proc_compare(ep->kp, kp))
369 						ep->kp = kp;
370 				}
371 				/*
372 				 * Proc debug option info; add to debug
373 				 * list using kinfo_proc ki_spare[0]
374 				 * as next pointer; ptr to ptr avoids the
375 				 * ptr = long assumption.
376 				 */
377 				dkp = ep->dkp;
378 				ep->dkp = kp;
379 				debugproc(kp) = dkp;
380 			}
381 		}
382 	}
383 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
384 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
385 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
386 	       ttywidth = 79;
387         else
388 	       ttywidth = ws.ws_col - 1;
389 	argwidth = ttywidth - WUSED;
390 	if (argwidth < 4)
391 		argwidth = 8;
392 	/* Don't truncate if we're outputting json or XML. */
393 	if (xo_get_style(NULL) != XO_STYLE_TEXT)
394 		argwidth = ARG_MAX;
395 	for (ep = ehead; ep != NULL; ep = ep->next) {
396 		if (ep->kp == NULL) {
397 			ep->args = strdup("-");
398 			continue;
399 		}
400 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
401 		    ep->kp->ki_comm, NULL, MAXCOMLEN);
402 		if (ep->args == NULL)
403 			err(1, NULL);
404 	}
405 	/* sort by idle time */
406 	if (sortidle && ehead != NULL) {
407 		struct entry *from, *save;
408 
409 		from = ehead;
410 		ehead = NULL;
411 		while (from != NULL) {
412 			for (nextp = &ehead;
413 			    (*nextp) && from->idle >= (*nextp)->idle;
414 			    nextp = &(*nextp)->next)
415 				continue;
416 			save = from;
417 			from = from->next;
418 			save->next = *nextp;
419 			*nextp = save;
420 		}
421 	}
422 
423 	xo_open_container("user-table");
424 	xo_open_list("user-entry");
425 
426 	for (ep = ehead; ep != NULL; ep = ep->next) {
427 		time_t t;
428 
429 		xo_open_instance("user-entry");
430 
431 		if (dflag) {
432 			xo_open_container("process-table");
433 			xo_open_list("process-entry");
434 
435 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
436 				const char *ptr;
437 
438 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
439 				    dkp->ki_comm, NULL, MAXCOMLEN);
440 				if (ptr == NULL)
441 					ptr = "-";
442 				xo_open_instance("process-entry");
443 				xo_emit("\t\t{:process-id/%-9d/%d} "
444 				    "{:command/%hs}\n", dkp->ki_pid, ptr);
445 				xo_close_instance("process-entry");
446 			}
447 			xo_close_list("process-entry");
448 			xo_close_container("process-table");
449 		}
450 		xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ",
451 			W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
452 			W_DISPLINESIZE, W_DISPLINESIZE,
453 			*ep->utmp.ut_line ?
454 			(strncmp(ep->utmp.ut_line, "tty", 3) &&
455 			 strncmp(ep->utmp.ut_line, "cua", 3) ?
456 			 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-");
457 
458 		if (ep->save_from)
459 		    xo_attr("address", "%s", ep->save_from);
460 		xo_emit("{:from/%-*.*s/%@**@s} ",
461 		    (int)fromwidth, (int)fromwidth, ep->from);
462 		t = ep->utmp.ut_tv.tv_sec;
463 		longattime = pr_attime(&t, &now);
464 		longidle = pr_idle(ep->idle);
465 		xo_emit("{:command/%.*hs/%@*@hs}\n",
466 		    (int)argwidth - longidle - longattime,
467 		    ep->args);
468 
469 		xo_close_instance("user-entry");
470 	}
471 
472 	xo_close_list("user-entry");
473 	xo_close_container("user-table");
474 	xo_close_container("uptime-information");
475 	xo_finish();
476 
477 	(void)kvm_close(kd);
478 	exit(0);
479 }
480 
481 static void
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 *
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
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