xref: /freebsd/usr.bin/w/w.c (revision 110f229794b4b31ee0fd6568fda89002b26664c8)
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 } *ep, *ehead = NULL, **nextp = &ehead;
122 
123 #define	debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
124 
125 #define	W_DISPUSERSIZE	10
126 #define	W_DISPLINESIZE	8
127 #define	W_MAXHOSTSIZE	40
128 
129 static void		 pr_header(time_t *, int);
130 static struct stat	*ttystat(char *);
131 static void		 usage(int);
132 
133 char *fmt_argv(char **, char *, char *, size_t);	/* ../../bin/ps/fmt.c */
134 
135 int
136 main(int argc, char *argv[])
137 {
138 	struct kinfo_proc *kp;
139 	struct kinfo_proc *dkp;
140 	struct stat *stp;
141 	time_t touched;
142 	int ch, i, nentries, nusers, wcmd, longidle, longattime;
143 	const char *memf, *nlistf, *p, *save_p;
144 	char *x_suffix;
145 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
146 	char fn[MAXHOSTNAMELEN];
147 	char *dot;
148 
149 	(void)setlocale(LC_ALL, "");
150 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
151 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
152 
153 	argc = xo_parse_args(argc, argv);
154 	if (argc < 0)
155 		exit(1);
156 
157 	/* Are we w(1) or uptime(1)? */
158 	if (strcmp(basename(argv[0]), "uptime") == 0) {
159 		wcmd = 0;
160 		p = "";
161 	} else {
162 		wcmd = 1;
163 		p = "dhiflM:N:nsuw";
164 	}
165 
166 	memf = _PATH_DEVNULL;
167 	nlistf = NULL;
168 	while ((ch = getopt(argc, argv, p)) != -1)
169 		switch (ch) {
170 		case 'd':
171 			dflag = 1;
172 			break;
173 		case 'h':
174 			header = 0;
175 			break;
176 		case 'i':
177 			sortidle = 1;
178 			break;
179 		case 'M':
180 			header = 0;
181 			memf = optarg;
182 			break;
183 		case 'N':
184 			nlistf = optarg;
185 			break;
186 		case 'n':
187 			nflag += 1;
188 			break;
189 		case 'f': case 'l': case 's': case 'u': case 'w':
190 			warnx("[-flsuw] no longer supported");
191 			/* FALLTHROUGH */
192 		case '?':
193 		default:
194 			usage(wcmd);
195 		}
196 	argc -= optind;
197 	argv += optind;
198 
199 	if (!(_res.options & RES_INIT))
200 		res_init();
201 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
202 	_res.retry = 1;		/* only try once.. */
203 
204 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
205 		errx(1, "%s", errbuf);
206 
207 	(void)time(&now);
208 
209 	if (*argv)
210 		sel_users = argv;
211 
212 	save_p = NULL;
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 	}
316 	endutxent();
317 
318 #define HEADER_USER		"USER"
319 #define HEADER_TTY		"TTY"
320 #define HEADER_FROM		"FROM"
321 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
322 #define HEADER_WHAT		"WHAT\n"
323 #define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + fromwidth + \
324 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
325 
326 
327 	if ((int) sizeof(HEADER_FROM) > fromwidth)
328 		fromwidth = sizeof(HEADER_FROM);
329 	fromwidth++;
330 	if (fromwidth > W_MAXHOSTSIZE)
331 		fromwidth = W_MAXHOSTSIZE;
332 
333 	xo_open_container("uptime-information");
334 
335 	if (header || wcmd == 0) {
336 		pr_header(&now, nusers);
337 		if (wcmd == 0) {
338 			xo_close_container("uptime-information");
339 			xo_finish();
340 
341 			(void)kvm_close(kd);
342 			exit(0);
343 		}
344 
345 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s}  {T:/%s}",
346 				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
347 				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
348 				fromwidth, fromwidth, HEADER_FROM,
349 				HEADER_LOGIN_IDLE HEADER_WHAT);
350 	}
351 
352 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
353 		err(1, "%s", kvm_geterr(kd));
354 	for (i = 0; i < nentries; i++, kp++) {
355 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
356 		    kp->ki_tdev == NODEV)
357 			continue;
358 		for (ep = ehead; ep != NULL; ep = ep->next) {
359 			if (ep->tdev == kp->ki_tdev) {
360 				/*
361 				 * proc is associated with this terminal
362 				 */
363 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
364 					/*
365 					 * Proc is 'most interesting'
366 					 */
367 					if (proc_compare(ep->kp, kp))
368 						ep->kp = kp;
369 				}
370 				/*
371 				 * Proc debug option info; add to debug
372 				 * list using kinfo_proc ki_spare[0]
373 				 * as next pointer; ptr to ptr avoids the
374 				 * ptr = long assumption.
375 				 */
376 				dkp = ep->dkp;
377 				ep->dkp = kp;
378 				debugproc(kp) = dkp;
379 			}
380 		}
381 	}
382 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
383 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
384 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
385 	       ttywidth = 79;
386         else
387 	       ttywidth = ws.ws_col - 1;
388 	argwidth = ttywidth - WUSED;
389 	if (argwidth < 4)
390 		argwidth = 8;
391 	for (ep = ehead; ep != NULL; ep = ep->next) {
392 		if (ep->kp == NULL) {
393 			ep->args = strdup("-");
394 			continue;
395 		}
396 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
397 		    ep->kp->ki_comm, NULL, MAXCOMLEN);
398 		if (ep->args == NULL)
399 			err(1, NULL);
400 	}
401 	/* sort by idle time */
402 	if (sortidle && ehead != NULL) {
403 		struct entry *from, *save;
404 
405 		from = ehead;
406 		ehead = NULL;
407 		while (from != NULL) {
408 			for (nextp = &ehead;
409 			    (*nextp) && from->idle >= (*nextp)->idle;
410 			    nextp = &(*nextp)->next)
411 				continue;
412 			save = from;
413 			from = from->next;
414 			save->next = *nextp;
415 			*nextp = save;
416 		}
417 	}
418 
419 	xo_open_container("user-table");
420 	xo_open_list("user-entry");
421 
422 	for (ep = ehead; ep != NULL; ep = ep->next) {
423 		time_t t;
424 
425 		xo_open_instance("user-entry");
426 
427 		if (dflag) {
428 		        xo_open_container("process-table");
429 		        xo_open_list("process-entry");
430 
431 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
432 				const char *ptr;
433 
434 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
435 				    dkp->ki_comm, NULL, MAXCOMLEN);
436 				if (ptr == NULL)
437 					ptr = "-";
438 				xo_open_instance("process-entry");
439 				xo_emit("\t\t{:process-id/%-9d/%d} {:command/%s}\n",
440 				    dkp->ki_pid, ptr);
441 				xo_close_instance("process-entry");
442 			}
443 		        xo_close_list("process-entry");
444 		        xo_close_container("process-table");
445 		}
446 		xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ",
447 			W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
448 			W_DISPLINESIZE, W_DISPLINESIZE,
449 			*ep->utmp.ut_line ?
450 			(strncmp(ep->utmp.ut_line, "tty", 3) &&
451 			 strncmp(ep->utmp.ut_line, "cua", 3) ?
452 			 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-");
453 
454 		if (save_p && save_p != p)
455 		    xo_attr("address", "%s", save_p);
456 		xo_emit("{:from/%-*.*s/%@**@s} ",
457 		    fromwidth, fromwidth, ep->from);
458 		t = ep->utmp.ut_tv.tv_sec;
459 		longattime = pr_attime(&t, &now);
460 		longidle = pr_idle(ep->idle);
461 		xo_emit("{:command/%.*s/%@*@s}\n",
462 		    argwidth - longidle - longattime,
463 		    ep->args);
464 
465 		xo_close_instance("user-entry");
466 	}
467 
468 	xo_close_list("user-entry");
469 	xo_close_container("user-table");
470 	xo_close_container("uptime-information");
471 	xo_finish();
472 
473 	(void)kvm_close(kd);
474 	exit(0);
475 }
476 
477 static void
478 pr_header(time_t *nowp, int nusers)
479 {
480 	double avenrun[3];
481 	time_t uptime;
482 	struct timespec tp;
483 	int days, hrs, i, mins, secs;
484 	char buf[256];
485 	struct sbuf *upbuf;
486 
487 	upbuf = sbuf_new_auto();
488 	/*
489 	 * Print time of day.
490 	 */
491 	if (strftime(buf, sizeof(buf),
492 	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
493 		xo_emit("{:time-of-day/%s} ", buf);
494 	/*
495 	 * Print how long system has been up.
496 	 */
497 	if (clock_gettime(CLOCK_UPTIME, &tp) != -1) {
498 		uptime = tp.tv_sec;
499 		if (uptime > 60)
500 			uptime += 30;
501 		days = uptime / 86400;
502 		uptime %= 86400;
503 		hrs = uptime / 3600;
504 		uptime %= 3600;
505 		mins = uptime / 60;
506 		secs = uptime % 60;
507 		xo_emit(" up");
508 		xo_emit("{e:uptime/%lu}", (unsigned long) tp.tv_sec);
509 		xo_emit("{e:days/%d}{e:hours/%d}{e:minutes/%d}{e:seconds/%d}", days, hrs, mins, secs);
510 
511 		if (days > 0)
512 			sbuf_printf(upbuf, " %d day%s,",
513 				days, days > 1 ? "s" : "");
514 		if (hrs > 0 && mins > 0)
515 			sbuf_printf(upbuf, " %2d:%02d,", hrs, mins);
516 		else if (hrs > 0)
517 			sbuf_printf(upbuf, " %d hr%s,",
518 				hrs, hrs > 1 ? "s" : "");
519 		else if (mins > 0)
520 			sbuf_printf(upbuf, " %d min%s,",
521 				mins, mins > 1 ? "s" : "");
522 		else
523 			sbuf_printf(upbuf, " %d sec%s,",
524 				secs, secs > 1 ? "s" : "");
525 		if (sbuf_finish(upbuf) != 0)
526 			xo_err(1, "Could not generate output");
527 		xo_emit("{:uptime-human/%s}", sbuf_data(upbuf));
528 		sbuf_delete(upbuf);
529 	}
530 
531 	/* Print number of users logged in to system */
532 	xo_emit(" {:users/%d} {Np:user,users}", nusers);
533 
534 	/*
535 	 * Print 1, 5, and 15 minute load averages.
536 	 */
537 	if (getloadavg(avenrun, nitems(avenrun)) == -1)
538 		xo_emit(", no load average information available\n");
539 	else {
540 	        static const char *format[] = {
541 		    " {:load-average-1/%.2f}",
542 		    " {:load-average-5/%.2f}",
543 		    " {:load-average-15/%.2f}",
544 		};
545 		xo_emit(", load averages:");
546 		for (i = 0; i < (int)(nitems(avenrun)); i++) {
547 			if (use_comma && i > 0)
548 				xo_emit(",");
549 			xo_emit(format[i], avenrun[i]);
550 		}
551 		xo_emit("\n");
552 	}
553 }
554 
555 static struct stat *
556 ttystat(char *line)
557 {
558 	static struct stat sb;
559 	char ttybuf[MAXPATHLEN];
560 
561 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
562 	if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode)) {
563 		return (&sb);
564 	} else
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