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