xref: /freebsd/usr.bin/w/w.c (revision a220d00e74dd245b4fca59c5eca0c53963686325)
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 #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 /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
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 
68 #include <ctype.h>
69 #include <err.h>
70 #include <errno.h>
71 #include <fcntl.h>
72 #include <kvm.h>
73 #include <langinfo.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 <stdio.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <unistd.h>
84 #include <utmp.h>
85 #include <vis.h>
86 
87 #include <arpa/nameser.h>
88 #include <resolv.h>
89 
90 #include "extern.h"
91 
92 struct timeval	boottime;
93 struct utmp	utmp;
94 struct winsize	ws;
95 kvm_t	       *kd;
96 time_t		now;		/* the current time of day */
97 time_t		uptime;		/* time of last reboot & elapsed time since */
98 int		ttywidth;	/* width of tty */
99 int		argwidth;	/* width of tty */
100 int		header = 1;	/* true if -h flag: don't print heading */
101 int		nflag;		/* true if -n flag: don't convert addrs */
102 int		dflag;		/* true if -d flag: output debug info */
103 int		sortidle;	/* sort by idle time */
104 int		use_ampm;	/* use AM/PM time */
105 int             use_comma;      /* use comma as floats separator */
106 char	      **sel_users;	/* login array of particular users selected */
107 
108 /*
109  * One of these per active utmp entry.
110  */
111 struct	entry {
112 	struct	entry *next;
113 	struct	utmp 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_spare[0])
122 
123 /* W_DISPHOSTSIZE should not be greater than UT_HOSTSIZE */
124 #define	W_DISPHOSTSIZE	16
125 
126 static void		 pr_header __P((time_t *, int));
127 static struct stat	*ttystat __P((char *, int));
128 static void		 usage __P((int));
129 static int		 this_is_uptime __P((const char *s));
130 
131 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
132 
133 int
134 main(argc, argv)
135 	int argc;
136 	char **argv;
137 {
138 	struct kinfo_proc *kp;
139 	struct kinfo_proc *dkp;
140 	struct hostent *hp;
141 	struct stat *stp;
142 	FILE *ut;
143 	u_long l;
144 	time_t touched;
145 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
146 	char *memf, *nlistf, *p, *x_suffix;
147 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
148 	char fn[MAXHOSTNAMELEN];
149 	char *dot;
150 
151 	(void)setlocale(LC_ALL, "");
152 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
153 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
154 
155 	/* Are we w(1) or uptime(1)? */
156 	if (this_is_uptime(argv[0]) == 0) {
157 		wcmd = 0;
158 		p = "";
159 	} else {
160 		wcmd = 1;
161 		p = "dhiflM:N:nsuw";
162 	}
163 
164 	dropgid = 0;
165 	memf = nlistf = _PATH_DEVNULL;
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 			dropgid = 1;
181 			break;
182 		case 'N':
183 			nlistf = optarg;
184 			dropgid = 1;
185 			break;
186 		case 'n':
187 			nflag = 1;
188 			break;
189 		case 'f': case 'l': case 's': case 'u': case 'w':
190 			warnx("[-flsuw] no longer supported");
191 			/* FALLTHROUGH */
192 		case '?':
193 		default:
194 			usage(wcmd);
195 		}
196 	argc -= optind;
197 	argv += optind;
198 
199 	if (!(_res.options & RES_INIT))
200 		res_init();
201 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
202 	_res.retry = 1;		/* only try once.. */
203 
204 	/*
205 	 * Discard setgid privileges if not the running kernel so that bad
206 	 * guys can't print interesting stuff from kernel memory.
207 	 */
208 	if (dropgid)
209 		setgid(getgid());
210 
211 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
212 		errx(1, "%s", errbuf);
213 
214 	(void)time(&now);
215 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
216 		err(1, "%s", _PATH_UTMP);
217 
218 	if (*argv)
219 		sel_users = argv;
220 
221 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
222 		if (utmp.ut_name[0] == '\0')
223 			continue;
224 		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
225 			continue;	/* corrupted record */
226 		++nusers;
227 		if (wcmd == 0)
228 			continue;
229 		if (sel_users) {
230 			int usermatch;
231 			char **user;
232 
233 			usermatch = 0;
234 			for (user = sel_users; !usermatch && *user; user++)
235 				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
236 					usermatch = 1;
237 			if (!usermatch)
238 				continue;
239 		}
240 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
241 			errx(1, "calloc");
242 		*nextp = ep;
243 		nextp = &ep->next;
244 		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
245 		ep->tdev = stp->st_rdev;
246 #ifdef CPU_CONSDEV
247 		/*
248 		 * If this is the console device, attempt to ascertain
249 		 * the true console device dev_t.
250 		 */
251 		if (ep->tdev == 0) {
252 			int mib[2];
253 			size_t size;
254 
255 			mib[0] = CTL_MACHDEP;
256 			mib[1] = CPU_CONSDEV;
257 			size = sizeof(dev_t);
258 			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
259 		}
260 #endif
261 		touched = stp->st_atime;
262 		if (touched < ep->utmp.ut_time) {
263 			/* tty untouched since before login */
264 			touched = ep->utmp.ut_time;
265 		}
266 		if ((ep->idle = now - touched) < 0)
267 			ep->idle = 0;
268 	}
269 	(void)fclose(ut);
270 
271 	if (header || wcmd == 0) {
272 		pr_header(&now, nusers);
273 		if (wcmd == 0) {
274 			(void)kvm_close(kd);
275 			exit(0);
276 		}
277 
278 #define HEADER_USER		"USER"
279 #define HEADER_TTY		"TTY"
280 #define HEADER_FROM		"FROM"
281 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
282 #define HEADER_WHAT		"WHAT\n"
283 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + W_DISPHOSTSIZE + \
284 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
285 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
286 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
287 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
288 				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
289 				HEADER_LOGIN_IDLE HEADER_WHAT);
290 	}
291 
292 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
293 		err(1, "%s", kvm_geterr(kd));
294 	for (i = 0; i < nentries; i++, kp++) {
295 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
296 			continue;
297 		for (ep = ehead; ep != NULL; ep = ep->next) {
298 			if (ep->tdev == kp->ki_tdev) {
299 				/*
300 				 * proc is associated with this terminal
301 				 */
302 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
303 					/*
304 					 * Proc is 'most interesting'
305 					 */
306 					if (proc_compare(ep->kp, kp))
307 						ep->kp = kp;
308 				}
309 				/*
310 				 * Proc debug option info; add to debug
311 				 * list using kinfo_proc ki_spare[0]
312 				 * as next pointer; ptr to ptr avoids the
313 				 * ptr = long assumption.
314 				 */
315 				dkp = ep->dkp;
316 				ep->dkp = kp;
317 				debugproc(kp) = dkp;
318 			}
319 		}
320 	}
321 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
322 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
323 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
324 	       ttywidth = 79;
325         else
326 	       ttywidth = ws.ws_col - 1;
327 	argwidth = ttywidth - WUSED;
328 	if (argwidth < 4)
329 		argwidth = 8;
330 	for (ep = ehead; ep != NULL; ep = ep->next) {
331 		if (ep->kp == NULL) {
332 			ep->args = "-";
333 			continue;
334 		}
335 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
336 		    ep->kp->ki_comm, MAXCOMLEN);
337 		if (ep->args == NULL)
338 			err(1, NULL);
339 	}
340 	/* sort by idle time */
341 	if (sortidle && ehead != NULL) {
342 		struct entry *from, *save;
343 
344 		from = ehead;
345 		ehead = NULL;
346 		while (from != NULL) {
347 			for (nextp = &ehead;
348 			    (*nextp) && from->idle >= (*nextp)->idle;
349 			    nextp = &(*nextp)->next)
350 				continue;
351 			save = from;
352 			from = from->next;
353 			save->next = *nextp;
354 			*nextp = save;
355 		}
356 	}
357 
358 	for (ep = ehead; ep != NULL; ep = ep->next) {
359 		char host_buf[UT_HOSTSIZE + 1];
360 		struct sockaddr_storage ss;
361 		struct sockaddr *sa = (struct sockaddr *)&ss;
362 		struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
363 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
364 		int isaddr;
365 
366 		host_buf[UT_HOSTSIZE] = '\0';
367 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
368 		p = *host_buf ? host_buf : "-";
369 		if ((x_suffix = strrchr(p, ':')) != NULL) {
370 			if ((dot = strchr(x_suffix, '.')) != NULL &&
371 			    strchr(dot+1, '.') == NULL)
372 				*x_suffix++ = '\0';
373 			else
374 				x_suffix = NULL;
375 		}
376 		if (!nflag) {
377 			/* Attempt to change an IP address into a name */
378 			isaddr = 0;
379 			memset(&ss, '\0', sizeof(ss));
380 			if (inet_pton(AF_INET6, p, &sin6->sin6_addr) == 1) {
381 				sin6->sin6_len = sizeof(*sin6);
382 				sin6->sin6_family = AF_INET6;
383 				isaddr = 1;
384 			} else if (inet_pton(AF_INET, p, &sin->sin_addr) == 1) {
385 				sin->sin_len = sizeof(*sin);
386 				sin->sin_family = AF_INET;
387 				isaddr = 1;
388 			}
389 			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
390 			    sa->sa_len) == HOSTNAME_FOUND)
391 				p = fn;
392 		}
393 		if (x_suffix) {
394 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
395 			p = buf;
396 		}
397 		if (dflag) {
398 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
399 				char *ptr;
400 
401 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
402 				    dkp->ki_comm, MAXCOMLEN);
403 				if (ptr == NULL)
404 					ptr = "-";
405 				(void)printf("\t\t%-9d %s\n",
406 				    dkp->ki_pid, ptr);
407 			}
408 		}
409 		(void)printf("%-*.*s %-*.*s %-*.*s ",
410 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
411 		    UT_LINESIZE, UT_LINESIZE,
412 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
413 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
414 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
415 		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
416 		pr_attime(&ep->utmp.ut_time, &now);
417 		longidle = pr_idle(ep->idle);
418 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
419 	}
420 	(void)kvm_close(kd);
421 	exit(0);
422 }
423 
424 static void
425 pr_header(nowp, nusers)
426 	time_t *nowp;
427 	int nusers;
428 {
429 	double avenrun[3];
430 	time_t uptime;
431 	int days, hrs, i, mins, secs;
432 	int mib[2];
433 	size_t size;
434 	char buf[256];
435 
436 	/*
437 	 * Print time of day.
438 	 */
439 	(void)strftime(buf, sizeof(buf)	- 1,
440 		       use_ampm	? "%l:%M%p" : "%k:%M", localtime(nowp));
441 	buf[sizeof(buf) - 1] = '\0';
442 	(void)printf("%s ", buf);
443 
444 	/*
445 	 * Print how long system has been up.
446 	 * (Found by looking getting "boottime" from the kernel)
447 	 */
448 	mib[0] = CTL_KERN;
449 	mib[1] = KERN_BOOTTIME;
450 	size = sizeof(boottime);
451 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
452 	    boottime.tv_sec != 0) {
453 		uptime = now - boottime.tv_sec;
454 		if (uptime > 60)
455 			uptime += 30;
456 		days = uptime / 86400;
457 		uptime %= 86400;
458 		hrs = uptime / 3600;
459 		uptime %= 3600;
460 		mins = uptime / 60;
461 		secs = uptime % 60;
462 		(void)printf(" up");
463 		if (days > 0)
464 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
465 		if (hrs > 0 && mins > 0)
466 			(void)printf(" %2d:%02d,", hrs, mins);
467 		else if (hrs > 0)
468 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
469 		else if (mins > 0)
470 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
471 		else
472 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
473 	}
474 
475 	/* Print number of users logged in to system */
476 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
477 
478 	/*
479 	 * Print 1, 5, and 15 minute load averages.
480 	 */
481 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
482 		(void)printf(", no load average information available\n");
483 	else {
484 		(void)printf(", load averages:");
485 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
486 			if (use_comma && i > 0)
487 				(void)printf(",");
488 			(void)printf(" %.2f", avenrun[i]);
489 		}
490 		(void)printf("\n");
491 	}
492 }
493 
494 static struct stat *
495 ttystat(line, sz)
496 	char *line;
497 	int sz;
498 {
499 	static struct stat sb;
500 	char ttybuf[MAXPATHLEN];
501 
502 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
503 	if (stat(ttybuf, &sb)) {
504 		warn("%s", ttybuf);
505 		return (NULL);
506 	}
507 	return (&sb);
508 }
509 
510 static void
511 usage(wcmd)
512 	int wcmd;
513 {
514 	if (wcmd)
515 		(void)fprintf(stderr,
516 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
517 	else
518 		(void)fprintf(stderr, "usage: uptime\n");
519 	exit(1);
520 }
521 
522 static int
523 this_is_uptime(s)
524 	const char *s;
525 {
526 	const char *u;
527 
528 	if ((u = strrchr(s, '/')) != NULL)
529 		++u;
530 	else
531 		u = s;
532 	if (strcmp(u, "uptime") == 0)
533 		return (0);
534 	return (-1);
535 }
536