xref: /freebsd/usr.bin/w/w.c (revision d93a896e)
1 /*-
2  * Copyright (c) 1980, 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 
32 __FBSDID("$FreeBSD$");
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif
39 
40 #ifndef lint
41 static const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
42 #endif
43 
44 /*
45  * w - print system status (who and what)
46  *
47  * This program is similar to the systat command on Tenex/Tops 10/20
48  *
49  */
50 #include <sys/param.h>
51 #include <sys/time.h>
52 #include <sys/stat.h>
53 #include <sys/sysctl.h>
54 #include <sys/proc.h>
55 #include <sys/user.h>
56 #include <sys/ioctl.h>
57 #include <sys/sbuf.h>
58 #include <sys/socket.h>
59 #include <sys/tty.h>
60 #include <sys/types.h>
61 
62 #include <machine/cpu.h>
63 #include <netinet/in.h>
64 #include <arpa/inet.h>
65 #include <arpa/nameser.h>
66 
67 #include <ctype.h>
68 #include <err.h>
69 #include <errno.h>
70 #include <fcntl.h>
71 #include <kvm.h>
72 #include <langinfo.h>
73 #include <libgen.h>
74 #include <libutil.h>
75 #include <limits.h>
76 #include <locale.h>
77 #include <netdb.h>
78 #include <nlist.h>
79 #include <paths.h>
80 #include <resolv.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <timeconv.h>
85 #include <unistd.h>
86 #include <utmpx.h>
87 #include <vis.h>
88 #include <libxo/xo.h>
89 
90 #include "extern.h"
91 
92 static struct utmpx *utmp;
93 static struct winsize ws;
94 static kvm_t   *kd;
95 static time_t	now;		/* the current time of day */
96 static int	ttywidth;	/* width of tty */
97 static int	argwidth;	/* width of tty */
98 static int	header = 1;	/* true if -h flag: don't print heading */
99 static int	nflag;		/* true if -n flag: don't convert addrs */
100 static int	dflag;		/* true if -d flag: output debug info */
101 static int	sortidle;	/* sort by idle time */
102 int		use_ampm;	/* use AM/PM time */
103 static int	use_comma;      /* use comma as floats separator */
104 static char   **sel_users;	/* login array of particular users selected */
105 
106 /*
107  * One of these per active utmp entry.
108  */
109 static struct entry {
110 	struct	entry *next;
111 	struct	utmpx utmp;
112 	dev_t	tdev;			/* dev_t of terminal */
113 	time_t	idle;			/* idle time of terminal in seconds */
114 	struct	kinfo_proc *kp;		/* `most interesting' proc */
115 	char	*args;			/* arg list of interesting process */
116 	struct	kinfo_proc *dkp;	/* debug option proc list */
117 } *ep, *ehead = NULL, **nextp = &ehead;
118 
119 #define	debugproc(p) *(&((struct kinfo_proc *)p)->ki_udata)
120 
121 #define	W_DISPUSERSIZE	10
122 #define	W_DISPLINESIZE	8
123 #define	W_DISPHOSTSIZE	40
124 
125 static void		 pr_header(time_t *, int);
126 static struct stat	*ttystat(char *);
127 static void		 usage(int);
128 
129 char *fmt_argv(char **, char *, char *, size_t);	/* ../../bin/ps/fmt.c */
130 
131 int
132 main(int argc, char *argv[])
133 {
134 	struct kinfo_proc *kp;
135 	struct kinfo_proc *dkp;
136 	struct stat *stp;
137 	time_t touched;
138 	int ch, i, nentries, nusers, wcmd, longidle, longattime;
139 	const char *memf, *nlistf, *p, *save_p;
140 	char *x_suffix;
141 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
142 	char fn[MAXHOSTNAMELEN];
143 	char *dot;
144 
145 	(void)setlocale(LC_ALL, "");
146 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
147 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
148 
149 	argc = xo_parse_args(argc, argv);
150 	if (argc < 0)
151 		exit(1);
152 
153 	/* Are we w(1) or uptime(1)? */
154 	if (strcmp(basename(argv[0]), "uptime") == 0) {
155 		wcmd = 0;
156 		p = "";
157 	} else {
158 		wcmd = 1;
159 		p = "dhiflM:N:nsuw";
160 	}
161 
162 	memf = _PATH_DEVNULL;
163 	nlistf = NULL;
164 	while ((ch = getopt(argc, argv, p)) != -1)
165 		switch (ch) {
166 		case 'd':
167 			dflag = 1;
168 			break;
169 		case 'h':
170 			header = 0;
171 			break;
172 		case 'i':
173 			sortidle = 1;
174 			break;
175 		case 'M':
176 			header = 0;
177 			memf = optarg;
178 			break;
179 		case 'N':
180 			nlistf = optarg;
181 			break;
182 		case 'n':
183 			nflag += 1;
184 			break;
185 		case 'f': case 'l': case 's': case 'u': case 'w':
186 			warnx("[-flsuw] no longer supported");
187 			/* FALLTHROUGH */
188 		case '?':
189 		default:
190 			usage(wcmd);
191 		}
192 	argc -= optind;
193 	argv += optind;
194 
195 	if (!(_res.options & RES_INIT))
196 		res_init();
197 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
198 	_res.retry = 1;		/* only try once.. */
199 
200 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
201 		errx(1, "%s", errbuf);
202 
203 	(void)time(&now);
204 
205 	if (*argv)
206 		sel_users = argv;
207 
208 	setutxent();
209 	for (nusers = 0; (utmp = getutxent()) != NULL;) {
210 		if (utmp->ut_type != USER_PROCESS)
211 			continue;
212 		if (!(stp = ttystat(utmp->ut_line)))
213 			continue;	/* corrupted record */
214 		++nusers;
215 		if (wcmd == 0)
216 			continue;
217 		if (sel_users) {
218 			int usermatch;
219 			char **user;
220 
221 			usermatch = 0;
222 			for (user = sel_users; !usermatch && *user; user++)
223 				if (!strcmp(utmp->ut_user, *user))
224 					usermatch = 1;
225 			if (!usermatch)
226 				continue;
227 		}
228 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
229 			errx(1, "calloc");
230 		*nextp = ep;
231 		nextp = &ep->next;
232 		memmove(&ep->utmp, utmp, sizeof *utmp);
233 		ep->tdev = stp->st_rdev;
234 		/*
235 		 * If this is the console device, attempt to ascertain
236 		 * the true console device dev_t.
237 		 */
238 		if (ep->tdev == 0) {
239 			size_t size;
240 
241 			size = sizeof(dev_t);
242 			(void)sysctlbyname("machdep.consdev", &ep->tdev, &size, NULL, 0);
243 		}
244 		touched = stp->st_atime;
245 		if (touched < ep->utmp.ut_tv.tv_sec) {
246 			/* tty untouched since before login */
247 			touched = ep->utmp.ut_tv.tv_sec;
248 		}
249 		if ((ep->idle = now - touched) < 0)
250 			ep->idle = 0;
251 	}
252 	endutxent();
253 
254 	xo_open_container("uptime-information");
255 
256 	if (header || wcmd == 0) {
257 		pr_header(&now, nusers);
258 		if (wcmd == 0) {
259 			xo_close_container("uptime-information");
260 			xo_finish();
261 
262 			(void)kvm_close(kd);
263 			exit(0);
264 		}
265 
266 #define HEADER_USER		"USER"
267 #define HEADER_TTY		"TTY"
268 #define HEADER_FROM		"FROM"
269 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
270 #define HEADER_WHAT		"WHAT\n"
271 #define WUSED  (W_DISPUSERSIZE + W_DISPLINESIZE + W_DISPHOSTSIZE + \
272 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
273 		xo_emit("{T:/%-*.*s} {T:/%-*.*s} {T:/%-*.*s}  {T:/%s}",
274 				W_DISPUSERSIZE, W_DISPUSERSIZE, HEADER_USER,
275 				W_DISPLINESIZE, W_DISPLINESIZE, HEADER_TTY,
276 				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
277 				HEADER_LOGIN_IDLE HEADER_WHAT);
278 	}
279 
280 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
281 		err(1, "%s", kvm_geterr(kd));
282 	for (i = 0; i < nentries; i++, kp++) {
283 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB ||
284 		    kp->ki_tdev == NODEV)
285 			continue;
286 		for (ep = ehead; ep != NULL; ep = ep->next) {
287 			if (ep->tdev == kp->ki_tdev) {
288 				/*
289 				 * proc is associated with this terminal
290 				 */
291 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
292 					/*
293 					 * Proc is 'most interesting'
294 					 */
295 					if (proc_compare(ep->kp, kp))
296 						ep->kp = kp;
297 				}
298 				/*
299 				 * Proc debug option info; add to debug
300 				 * list using kinfo_proc ki_spare[0]
301 				 * as next pointer; ptr to ptr avoids the
302 				 * ptr = long assumption.
303 				 */
304 				dkp = ep->dkp;
305 				ep->dkp = kp;
306 				debugproc(kp) = dkp;
307 			}
308 		}
309 	}
310 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
311 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
312 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
313 	       ttywidth = 79;
314         else
315 	       ttywidth = ws.ws_col - 1;
316 	argwidth = ttywidth - WUSED;
317 	if (argwidth < 4)
318 		argwidth = 8;
319 	for (ep = ehead; ep != NULL; ep = ep->next) {
320 		if (ep->kp == NULL) {
321 			ep->args = strdup("-");
322 			continue;
323 		}
324 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
325 		    ep->kp->ki_comm, NULL, MAXCOMLEN);
326 		if (ep->args == NULL)
327 			err(1, NULL);
328 	}
329 	/* sort by idle time */
330 	if (sortidle && ehead != NULL) {
331 		struct entry *from, *save;
332 
333 		from = ehead;
334 		ehead = NULL;
335 		while (from != NULL) {
336 			for (nextp = &ehead;
337 			    (*nextp) && from->idle >= (*nextp)->idle;
338 			    nextp = &(*nextp)->next)
339 				continue;
340 			save = from;
341 			from = from->next;
342 			save->next = *nextp;
343 			*nextp = save;
344 		}
345 	}
346 
347 	xo_open_container("user-table");
348 	xo_open_list("user-entry");
349 
350 	for (ep = ehead; ep != NULL; ep = ep->next) {
351 		struct addrinfo hints, *res;
352 		struct sockaddr_storage ss;
353 		struct sockaddr *sa = (struct sockaddr *)&ss;
354 		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
355 		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
356 		time_t t;
357 		int isaddr;
358 
359 		xo_open_instance("user-entry");
360 
361 		save_p = p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
362 		if ((x_suffix = strrchr(p, ':')) != NULL) {
363 			if ((dot = strchr(x_suffix, '.')) != NULL &&
364 			    strchr(dot+1, '.') == NULL)
365 				*x_suffix++ = '\0';
366 			else
367 				x_suffix = NULL;
368 		}
369 
370 		isaddr = 0;
371 		memset(&ss, '\0', sizeof(ss));
372 		if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
373 			lsin6->sin6_len = sizeof(*lsin6);
374 			lsin6->sin6_family = AF_INET6;
375 			isaddr = 1;
376 		} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
377 			lsin->sin_len = sizeof(*lsin);
378 			lsin->sin_family = AF_INET;
379 			isaddr = 1;
380 		}
381 		if (nflag == 0) {
382 			/* Attempt to change an IP address into a name */
383 			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
384 			    sa->sa_len) == HOSTNAME_FOUND)
385 				p = fn;
386 		} else if (!isaddr && nflag > 1) {
387 			/*
388 			 * If a host has only one A/AAAA RR, change a
389 			 * name into an IP address
390 			 */
391 			memset(&hints, 0, sizeof(hints));
392 			hints.ai_flags = AI_PASSIVE;
393 			hints.ai_family = AF_UNSPEC;
394 			hints.ai_socktype = SOCK_STREAM;
395 			if (getaddrinfo(p, NULL, &hints, &res) == 0) {
396 				if (res->ai_next == NULL &&
397 				    getnameinfo(res->ai_addr, res->ai_addrlen,
398 					fn, sizeof(fn), NULL, 0,
399 					NI_NUMERICHOST) == 0)
400 					p = fn;
401 				freeaddrinfo(res);
402 			}
403 		}
404 
405 		if (x_suffix) {
406 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
407 			p = buf;
408 		}
409 		if (dflag) {
410 		        xo_open_container("process-table");
411 		        xo_open_list("process-entry");
412 
413 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
414 				const char *ptr;
415 
416 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
417 				    dkp->ki_comm, NULL, MAXCOMLEN);
418 				if (ptr == NULL)
419 					ptr = "-";
420 				xo_open_instance("process-entry");
421 				xo_emit("\t\t{:process-id/%-9d/%d} {:command/%s}\n",
422 				    dkp->ki_pid, ptr);
423 				xo_close_instance("process-entry");
424 			}
425 		        xo_close_list("process-entry");
426 		        xo_close_container("process-table");
427 		}
428 		xo_emit("{:user/%-*.*s/%@**@s} {:tty/%-*.*s/%@**@s} ",
429 			W_DISPUSERSIZE, W_DISPUSERSIZE, ep->utmp.ut_user,
430 			W_DISPLINESIZE, W_DISPLINESIZE,
431 			*ep->utmp.ut_line ?
432 			(strncmp(ep->utmp.ut_line, "tty", 3) &&
433 			 strncmp(ep->utmp.ut_line, "cua", 3) ?
434 			 ep->utmp.ut_line : ep->utmp.ut_line + 3) : "-");
435 
436 		if (save_p && save_p != p)
437 		    xo_attr("address", "%s", save_p);
438 		xo_emit("{:from/%-*.*s/%@**@s} ",
439 		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
440 		t = ep->utmp.ut_tv.tv_sec;
441 		longattime = pr_attime(&t, &now);
442 		longidle = pr_idle(ep->idle);
443 		xo_emit("{:command/%.*s/%@*@s}\n",
444 		    argwidth - longidle - longattime,
445 		    ep->args);
446 
447 		xo_close_instance("user-entry");
448 	}
449 
450 	xo_close_list("user-entry");
451 	xo_close_container("user-table");
452 	xo_close_container("uptime-information");
453 	xo_finish();
454 
455 	(void)kvm_close(kd);
456 	exit(0);
457 }
458 
459 static void
460 pr_header(time_t *nowp, int nusers)
461 {
462 	double avenrun[3];
463 	time_t uptime;
464 	struct timespec tp;
465 	int days, hrs, i, mins, secs;
466 	char buf[256];
467 	struct sbuf *upbuf;
468 
469 	upbuf = sbuf_new_auto();
470 	/*
471 	 * Print time of day.
472 	 */
473 	if (strftime(buf, sizeof(buf),
474 	    use_ampm ? "%l:%M%p" : "%k:%M", localtime(nowp)) != 0)
475 		xo_emit("{:time-of-day/%s} ", buf);
476 	/*
477 	 * Print how long system has been up.
478 	 */
479 	if (clock_gettime(CLOCK_UPTIME, &tp) != -1) {
480 		uptime = tp.tv_sec;
481 		if (uptime > 60)
482 			uptime += 30;
483 		days = uptime / 86400;
484 		uptime %= 86400;
485 		hrs = uptime / 3600;
486 		uptime %= 3600;
487 		mins = uptime / 60;
488 		secs = uptime % 60;
489 		xo_emit(" up");
490 		xo_emit("{e:uptime/%lu}", (unsigned long) tp.tv_sec);
491 		xo_emit("{e:days/%d}{e:hours/%d}{e:minutes/%d}{e:seconds/%d}", days, hrs, mins, secs);
492 
493 		if (days > 0)
494 			sbuf_printf(upbuf, " %d day%s,",
495 				days, days > 1 ? "s" : "");
496 		if (hrs > 0 && mins > 0)
497 			sbuf_printf(upbuf, " %2d:%02d,", hrs, mins);
498 		else if (hrs > 0)
499 			sbuf_printf(upbuf, " %d hr%s,",
500 				hrs, hrs > 1 ? "s" : "");
501 		else if (mins > 0)
502 			sbuf_printf(upbuf, " %d min%s,",
503 				mins, mins > 1 ? "s" : "");
504 		else
505 			sbuf_printf(upbuf, " %d sec%s,",
506 				secs, secs > 1 ? "s" : "");
507 		if (sbuf_finish(upbuf) != 0)
508 			xo_err(1, "Could not generate output");
509 		xo_emit("{:uptime-human/%s}", sbuf_data(upbuf));
510 		sbuf_delete(upbuf);
511 	}
512 
513 	/* Print number of users logged in to system */
514 	xo_emit(" {:users/%d} {Np:user,users}", nusers);
515 
516 	/*
517 	 * Print 1, 5, and 15 minute load averages.
518 	 */
519 	if (getloadavg(avenrun, nitems(avenrun)) == -1)
520 		xo_emit(", no load average information available\n");
521 	else {
522 	        static const char *format[] = {
523 		    " {:load-average-1/%.2f}",
524 		    " {:load-average-5/%.2f}",
525 		    " {:load-average-15/%.2f}",
526 		};
527 		xo_emit(", load averages:");
528 		for (i = 0; i < (int)(nitems(avenrun)); i++) {
529 			if (use_comma && i > 0)
530 				xo_emit(",");
531 			xo_emit(format[i], avenrun[i]);
532 		}
533 		xo_emit("\n");
534 	}
535 }
536 
537 static struct stat *
538 ttystat(char *line)
539 {
540 	static struct stat sb;
541 	char ttybuf[MAXPATHLEN];
542 
543 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%s", _PATH_DEV, line);
544 	if (stat(ttybuf, &sb) == 0 && S_ISCHR(sb.st_mode)) {
545 		return (&sb);
546 	} else
547 		return (NULL);
548 }
549 
550 static void
551 usage(int wcmd)
552 {
553 	if (wcmd)
554 		xo_error("usage: w [-dhin] [-M core] [-N system] [user ...]\n");
555 	else
556 		xo_error("usage: uptime\n");
557 	xo_finish();
558 	exit(1);
559 }
560