xref: /freebsd/usr.bin/w/w.c (revision c11e094d96120a2e0e726ed9705ae0ec08db49b6)
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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 
36 __FBSDID("$FreeBSD$");
37 
38 #ifndef lint
39 static const char copyright[] =
40 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
41 	The Regents of the University of California.  All rights reserved.\n";
42 #endif
43 
44 #ifndef lint
45 static const char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
46 #endif
47 
48 /*
49  * w - print system status (who and what)
50  *
51  * This program is similar to the systat command on Tenex/Tops 10/20
52  *
53  */
54 #include <sys/param.h>
55 #include <sys/time.h>
56 #include <sys/stat.h>
57 #include <sys/sysctl.h>
58 #include <sys/proc.h>
59 #include <sys/user.h>
60 #include <sys/ioctl.h>
61 #include <sys/socket.h>
62 #include <sys/tty.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 <libutil.h>
76 #include <limits.h>
77 #include <locale.h>
78 #include <netdb.h>
79 #include <nlist.h>
80 #include <paths.h>
81 #include <resolv.h>
82 #include <stdio.h>
83 #include <stdlib.h>
84 #include <string.h>
85 #include <unistd.h>
86 #include <utmp.h>
87 #include <vis.h>
88 
89 #include "extern.h"
90 
91 struct timeval	boottime;
92 struct utmp	utmp;
93 struct winsize	ws;
94 kvm_t	       *kd;
95 time_t		now;		/* the current time of day */
96 int		ttywidth;	/* width of tty */
97 int		argwidth;	/* width of tty */
98 int		header = 1;	/* true if -h flag: don't print heading */
99 int		nflag;		/* true if -n flag: don't convert addrs */
100 int		dflag;		/* true if -d flag: output debug info */
101 int		sortidle;	/* sort by idle time */
102 int		use_ampm;	/* use AM/PM time */
103 int             use_comma;      /* use comma as floats separator */
104 char	      **sel_users;	/* login array of particular users selected */
105 
106 /*
107  * One of these per active utmp entry.
108  */
109 struct	entry {
110 	struct	entry *next;
111 	struct	utmp 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_spare[0])
120 
121 /* W_DISPHOSTSIZE should not be greater than UT_HOSTSIZE */
122 #define	W_DISPHOSTSIZE	16
123 
124 static void		 pr_header(time_t *, int);
125 static struct stat	*ttystat(char *, int);
126 static void		 usage(int);
127 static int		 this_is_uptime(const char *s);
128 
129 char *fmt_argv(char **, char *, int);	/* ../../bin/ps/fmt.c */
130 
131 int
132 main(argc, argv)
133 	int argc;
134 	char **argv;
135 {
136 	struct kinfo_proc *kp;
137 	struct kinfo_proc *dkp;
138 	struct stat *stp;
139 	FILE *ut;
140 	time_t touched;
141 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
142 	const char *memf, *nlistf, *p;
143 	char *x_suffix;
144 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
145 	char fn[MAXHOSTNAMELEN];
146 	char *dot;
147 
148 	(void)setlocale(LC_ALL, "");
149 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
150 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
151 
152 	/* Are we w(1) or uptime(1)? */
153 	if (this_is_uptime(argv[0]) == 0) {
154 		wcmd = 0;
155 		p = "";
156 	} else {
157 		wcmd = 1;
158 		p = "dhiflM:N:nsuw";
159 	}
160 
161 	dropgid = 0;
162 	memf = nlistf = _PATH_DEVNULL;
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 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
213 		err(1, "%s", _PATH_UTMP);
214 
215 	if (*argv)
216 		sel_users = argv;
217 
218 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
219 		if (utmp.ut_name[0] == '\0')
220 			continue;
221 		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
222 			continue;	/* corrupted record */
223 		++nusers;
224 		if (wcmd == 0)
225 			continue;
226 		if (sel_users) {
227 			int usermatch;
228 			char **user;
229 
230 			usermatch = 0;
231 			for (user = sel_users; !usermatch && *user; user++)
232 				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
233 					usermatch = 1;
234 			if (!usermatch)
235 				continue;
236 		}
237 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
238 			errx(1, "calloc");
239 		*nextp = ep;
240 		nextp = &ep->next;
241 		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
242 		ep->tdev = stp->st_rdev;
243 #ifdef CPU_CONSDEV
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 			int mib[2];
250 			size_t size;
251 
252 			mib[0] = CTL_MACHDEP;
253 			mib[1] = CPU_CONSDEV;
254 			size = sizeof(dev_t);
255 			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
256 		}
257 #endif
258 		touched = stp->st_atime;
259 		if (touched < ep->utmp.ut_time) {
260 			/* tty untouched since before login */
261 			touched = ep->utmp.ut_time;
262 		}
263 		if ((ep->idle = now - touched) < 0)
264 			ep->idle = 0;
265 	}
266 	(void)fclose(ut);
267 
268 	if (header || wcmd == 0) {
269 		pr_header(&now, nusers);
270 		if (wcmd == 0) {
271 			(void)kvm_close(kd);
272 			exit(0);
273 		}
274 
275 #define HEADER_USER		"USER"
276 #define HEADER_TTY		"TTY"
277 #define HEADER_FROM		"FROM"
278 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
279 #define HEADER_WHAT		"WHAT\n"
280 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + W_DISPHOSTSIZE + \
281 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
282 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
283 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
284 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
285 				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
286 				HEADER_LOGIN_IDLE HEADER_WHAT);
287 	}
288 
289 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
290 		err(1, "%s", kvm_geterr(kd));
291 	for (i = 0; i < nentries; i++, kp++) {
292 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
293 			continue;
294 		for (ep = ehead; ep != NULL; ep = ep->next) {
295 			if (ep->tdev == kp->ki_tdev) {
296 				/*
297 				 * proc is associated with this terminal
298 				 */
299 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
300 					/*
301 					 * Proc is 'most interesting'
302 					 */
303 					if (proc_compare(ep->kp, kp))
304 						ep->kp = kp;
305 				}
306 				/*
307 				 * Proc debug option info; add to debug
308 				 * list using kinfo_proc ki_spare[0]
309 				 * as next pointer; ptr to ptr avoids the
310 				 * ptr = long assumption.
311 				 */
312 				dkp = ep->dkp;
313 				ep->dkp = kp;
314 				debugproc(kp) = dkp;
315 			}
316 		}
317 	}
318 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
319 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
320 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
321 	       ttywidth = 79;
322         else
323 	       ttywidth = ws.ws_col - 1;
324 	argwidth = ttywidth - WUSED;
325 	if (argwidth < 4)
326 		argwidth = 8;
327 	for (ep = ehead; ep != NULL; ep = ep->next) {
328 		if (ep->kp == NULL) {
329 			ep->args = strdup("-");
330 			continue;
331 		}
332 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
333 		    ep->kp->ki_comm, MAXCOMLEN);
334 		if (ep->args == NULL)
335 			err(1, NULL);
336 	}
337 	/* sort by idle time */
338 	if (sortidle && ehead != NULL) {
339 		struct entry *from, *save;
340 
341 		from = ehead;
342 		ehead = NULL;
343 		while (from != NULL) {
344 			for (nextp = &ehead;
345 			    (*nextp) && from->idle >= (*nextp)->idle;
346 			    nextp = &(*nextp)->next)
347 				continue;
348 			save = from;
349 			from = from->next;
350 			save->next = *nextp;
351 			*nextp = save;
352 		}
353 	}
354 
355 	for (ep = ehead; ep != NULL; ep = ep->next) {
356 		char host_buf[UT_HOSTSIZE + 1];
357 		struct sockaddr_storage ss;
358 		struct sockaddr *sa = (struct sockaddr *)&ss;
359 		struct sockaddr_in *lsin = (struct sockaddr_in *)&ss;
360 		struct sockaddr_in6 *lsin6 = (struct sockaddr_in6 *)&ss;
361 		int isaddr;
362 
363 		host_buf[UT_HOSTSIZE] = '\0';
364 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
365 		p = *host_buf ? host_buf : "-";
366 		if ((x_suffix = strrchr(p, ':')) != NULL) {
367 			if ((dot = strchr(x_suffix, '.')) != NULL &&
368 			    strchr(dot+1, '.') == NULL)
369 				*x_suffix++ = '\0';
370 			else
371 				x_suffix = NULL;
372 		}
373 		if (!nflag) {
374 			/* Attempt to change an IP address into a name */
375 			isaddr = 0;
376 			memset(&ss, '\0', sizeof(ss));
377 			if (inet_pton(AF_INET6, p, &lsin6->sin6_addr) == 1) {
378 				lsin6->sin6_len = sizeof(*lsin6);
379 				lsin6->sin6_family = AF_INET6;
380 				isaddr = 1;
381 			} else if (inet_pton(AF_INET, p, &lsin->sin_addr) == 1) {
382 				lsin->sin_len = sizeof(*lsin);
383 				lsin->sin_family = AF_INET;
384 				isaddr = 1;
385 			}
386 			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
387 			    sa->sa_len) == HOSTNAME_FOUND)
388 				p = fn;
389 		}
390 		if (x_suffix) {
391 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
392 			p = buf;
393 		}
394 		if (dflag) {
395 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
396 				const char *ptr;
397 
398 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
399 				    dkp->ki_comm, MAXCOMLEN);
400 				if (ptr == NULL)
401 					ptr = "-";
402 				(void)printf("\t\t%-9d %s\n",
403 				    dkp->ki_pid, ptr);
404 			}
405 		}
406 		(void)printf("%-*.*s %-*.*s %-*.*s ",
407 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
408 		    UT_LINESIZE, UT_LINESIZE,
409 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
410 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
411 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
412 		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
413 		pr_attime(&ep->utmp.ut_time, &now);
414 		longidle = pr_idle(ep->idle);
415 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
416 	}
417 	(void)kvm_close(kd);
418 	exit(0);
419 }
420 
421 static void
422 pr_header(nowp, nusers)
423 	time_t *nowp;
424 	int nusers;
425 {
426 	double avenrun[3];
427 	time_t uptime;
428 	int days, hrs, i, mins, secs;
429 	int mib[2];
430 	size_t size;
431 	char buf[256];
432 
433 	/*
434 	 * Print time of day.
435 	 */
436 	(void)strftime(buf, sizeof(buf)	- 1,
437 		       use_ampm	? "%l:%M%p" : "%k:%M", localtime(nowp));
438 	buf[sizeof(buf) - 1] = '\0';
439 	(void)printf("%s ", buf);
440 
441 	/*
442 	 * Print how long system has been up.
443 	 * (Found by looking getting "boottime" from the kernel)
444 	 */
445 	mib[0] = CTL_KERN;
446 	mib[1] = KERN_BOOTTIME;
447 	size = sizeof(boottime);
448 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
449 	    boottime.tv_sec != 0) {
450 		uptime = now - boottime.tv_sec;
451 		if (uptime > 60)
452 			uptime += 30;
453 		days = uptime / 86400;
454 		uptime %= 86400;
455 		hrs = uptime / 3600;
456 		uptime %= 3600;
457 		mins = uptime / 60;
458 		secs = uptime % 60;
459 		(void)printf(" up");
460 		if (days > 0)
461 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
462 		if (hrs > 0 && mins > 0)
463 			(void)printf(" %2d:%02d,", hrs, mins);
464 		else if (hrs > 0)
465 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
466 		else if (mins > 0)
467 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
468 		else
469 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
470 	}
471 
472 	/* Print number of users logged in to system */
473 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
474 
475 	/*
476 	 * Print 1, 5, and 15 minute load averages.
477 	 */
478 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
479 		(void)printf(", no load average information available\n");
480 	else {
481 		(void)printf(", load averages:");
482 		for (i = 0; i < (int)(sizeof(avenrun) / sizeof(avenrun[0])); i++) {
483 			if (use_comma && i > 0)
484 				(void)printf(",");
485 			(void)printf(" %.2f", avenrun[i]);
486 		}
487 		(void)printf("\n");
488 	}
489 }
490 
491 static struct stat *
492 ttystat(line, sz)
493 	char *line;
494 	int sz;
495 {
496 	static struct stat sb;
497 	char ttybuf[MAXPATHLEN];
498 
499 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
500 	if (stat(ttybuf, &sb)) {
501 		warn("%s", ttybuf);
502 		return (NULL);
503 	}
504 	return (&sb);
505 }
506 
507 static void
508 usage(wcmd)
509 	int wcmd;
510 {
511 	if (wcmd)
512 		(void)fprintf(stderr,
513 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
514 	else
515 		(void)fprintf(stderr, "usage: uptime\n");
516 	exit(1);
517 }
518 
519 static int
520 this_is_uptime(s)
521 	const char *s;
522 {
523 	const char *u;
524 
525 	if ((u = strrchr(s, '/')) != NULL)
526 		++u;
527 	else
528 		u = s;
529 	if (strcmp(u, "uptime") == 0)
530 		return (0);
531 	return (-1);
532 }
533