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