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