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