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