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