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