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