xref: /freebsd/usr.bin/w/w.c (revision 6990ffd8a95caaba6858ad44ff1b3157d1efba8f)
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/lock.h>
56 #include <sys/time.h>
57 #include <sys/stat.h>
58 #include <sys/sysctl.h>
59 #include <sys/proc.h>
60 #include <sys/user.h>
61 #include <sys/ioctl.h>
62 #include <sys/socket.h>
63 #include <sys/tty.h>
64 
65 #include <machine/cpu.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.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 <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <unistd.h>
85 #include <utmp.h>
86 #include <vis.h>
87 
88 #include <arpa/nameser.h>
89 #include <resolv.h>
90 
91 #include "extern.h"
92 
93 struct timeval	boottime;
94 struct utmp	utmp;
95 struct winsize	ws;
96 kvm_t	       *kd;
97 time_t		now;		/* the current time of day */
98 time_t		uptime;		/* time of last reboot & elapsed time since */
99 int		ttywidth;	/* width of tty */
100 int		argwidth;	/* width of tty */
101 int		header = 1;	/* true if -h flag: don't print heading */
102 int		nflag;		/* true if -n flag: don't convert addrs */
103 int		dflag;		/* true if -d flag: output debug info */
104 int		sortidle;	/* sort by idle time */
105 int		use_ampm;	/* use AM/PM time */
106 int             use_comma;      /* use comma as floats separator */
107 char	      **sel_users;	/* login array of particular users selected */
108 
109 /*
110  * One of these per active utmp entry.
111  */
112 struct	entry {
113 	struct	entry *next;
114 	struct	utmp utmp;
115 	dev_t	tdev;			/* dev_t of terminal */
116 	time_t	idle;			/* idle time of terminal in seconds */
117 	struct	kinfo_proc *kp;		/* `most interesting' proc */
118 	char	*args;			/* arg list of interesting process */
119 	struct	kinfo_proc *dkp;	/* debug option proc list */
120 } *ep, *ehead = NULL, **nextp = &ehead;
121 
122 #define debugproc(p) *((struct kinfo_proc **)&(p)->ki_spare[0])
123 
124 /* W_DISPHOSTSIZE should not be greater than UT_HOSTSIZE */
125 #define	W_DISPHOSTSIZE	16
126 
127 static void		 pr_header __P((time_t *, int));
128 static struct stat	*ttystat __P((char *, int));
129 static void		 usage __P((int));
130 static int		 this_is_uptime __P((const char *s));
131 
132 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
133 
134 int
135 main(argc, argv)
136 	int argc;
137 	char **argv;
138 {
139 	struct kinfo_proc *kp;
140 	struct kinfo_proc *dkp;
141 	struct hostent *hp;
142 	struct stat *stp;
143 	FILE *ut;
144 	u_long l;
145 	time_t touched;
146 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
147 	char *memf, *nlistf, *p, *x_suffix;
148 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
149 	char fn[MAXHOSTNAMELEN];
150 	char *dot;
151 
152 	(void)setlocale(LC_ALL, "");
153 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
154 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
155 
156 	/* Are we w(1) or uptime(1)? */
157 	if (this_is_uptime(argv[0]) == 0) {
158 		wcmd = 0;
159 		p = "";
160 	} else {
161 		wcmd = 1;
162 		p = "dhiflM:N:nsuw";
163 	}
164 
165 	dropgid = 0;
166 	memf = nlistf = _PATH_DEVNULL;
167 	while ((ch = getopt(argc, argv, p)) != -1)
168 		switch (ch) {
169 		case 'd':
170 			dflag = 1;
171 			break;
172 		case 'h':
173 			header = 0;
174 			break;
175 		case 'i':
176 			sortidle = 1;
177 			break;
178 		case 'M':
179 			header = 0;
180 			memf = optarg;
181 			dropgid = 1;
182 			break;
183 		case 'N':
184 			nlistf = optarg;
185 			dropgid = 1;
186 			break;
187 		case 'n':
188 			nflag = 1;
189 			break;
190 		case 'f': case 'l': case 's': case 'u': case 'w':
191 			warnx("[-flsuw] no longer supported");
192 			/* FALLTHROUGH */
193 		case '?':
194 		default:
195 			usage(wcmd);
196 		}
197 	argc -= optind;
198 	argv += optind;
199 
200 	if (!(_res.options & RES_INIT))
201 		res_init();
202 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
203 	_res.retry = 1;		/* only try once.. */
204 
205 	/*
206 	 * Discard setgid privileges if not the running kernel so that bad
207 	 * guys can't print interesting stuff from kernel memory.
208 	 */
209 	if (dropgid)
210 		setgid(getgid());
211 
212 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
213 		errx(1, "%s", errbuf);
214 
215 	(void)time(&now);
216 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
217 		err(1, "%s", _PATH_UTMP);
218 
219 	if (*argv)
220 		sel_users = argv;
221 
222 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
223 		if (utmp.ut_name[0] == '\0')
224 			continue;
225 		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
226 			continue;	/* corrupted record */
227 		++nusers;
228 		if (wcmd == 0)
229 			continue;
230 		if (sel_users) {
231 			int usermatch;
232 			char **user;
233 
234 			usermatch = 0;
235 			for (user = sel_users; !usermatch && *user; user++)
236 				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
237 					usermatch = 1;
238 			if (!usermatch)
239 				continue;
240 		}
241 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
242 			errx(1, "calloc");
243 		*nextp = ep;
244 		nextp = &ep->next;
245 		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
246 		ep->tdev = stp->st_rdev;
247 #ifdef CPU_CONSDEV
248 		/*
249 		 * If this is the console device, attempt to ascertain
250 		 * the true console device dev_t.
251 		 */
252 		if (ep->tdev == 0) {
253 			int mib[2];
254 			size_t size;
255 
256 			mib[0] = CTL_MACHDEP;
257 			mib[1] = CPU_CONSDEV;
258 			size = sizeof(dev_t);
259 			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
260 		}
261 #endif
262 		touched = stp->st_atime;
263 		if (touched < ep->utmp.ut_time) {
264 			/* tty untouched since before login */
265 			touched = ep->utmp.ut_time;
266 		}
267 		if ((ep->idle = now - touched) < 0)
268 			ep->idle = 0;
269 	}
270 	(void)fclose(ut);
271 
272 	if (header || wcmd == 0) {
273 		pr_header(&now, nusers);
274 		if (wcmd == 0) {
275 			(void)kvm_close(kd);
276 			exit(0);
277 		}
278 
279 #define HEADER_USER		"USER"
280 #define HEADER_TTY		"TTY"
281 #define HEADER_FROM		"FROM"
282 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
283 #define HEADER_WHAT		"WHAT\n"
284 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + W_DISPHOSTSIZE + \
285 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
286 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
287 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
288 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
289 				W_DISPHOSTSIZE, W_DISPHOSTSIZE, HEADER_FROM,
290 				HEADER_LOGIN_IDLE HEADER_WHAT);
291 	}
292 
293 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
294 		err(1, "%s", kvm_geterr(kd));
295 	for (i = 0; i < nentries; i++, kp++) {
296 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
297 			continue;
298 		for (ep = ehead; ep != NULL; ep = ep->next) {
299 			if (ep->tdev == kp->ki_tdev) {
300 				/*
301 				 * proc is associated with this terminal
302 				 */
303 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
304 					/*
305 					 * Proc is 'most interesting'
306 					 */
307 					if (proc_compare(ep->kp, kp))
308 						ep->kp = kp;
309 				}
310 				/*
311 				 * Proc debug option info; add to debug
312 				 * list using kinfo_proc ki_spare[0]
313 				 * as next pointer; ptr to ptr avoids the
314 				 * ptr = long assumption.
315 				 */
316 				dkp = ep->dkp;
317 				ep->dkp = kp;
318 				debugproc(kp) = dkp;
319 			}
320 		}
321 	}
322 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
323 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
324 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
325 	       ttywidth = 79;
326         else
327 	       ttywidth = ws.ws_col - 1;
328 	argwidth = ttywidth - WUSED;
329 	if (argwidth < 4)
330 		argwidth = 8;
331 	for (ep = ehead; ep != NULL; ep = ep->next) {
332 		if (ep->kp == NULL) {
333 			ep->args = "-";
334 			continue;
335 		}
336 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
337 		    ep->kp->ki_comm, MAXCOMLEN);
338 		if (ep->args == NULL)
339 			err(1, NULL);
340 	}
341 	/* sort by idle time */
342 	if (sortidle && ehead != NULL) {
343 		struct entry *from, *save;
344 
345 		from = ehead;
346 		ehead = NULL;
347 		while (from != NULL) {
348 			for (nextp = &ehead;
349 			    (*nextp) && from->idle >= (*nextp)->idle;
350 			    nextp = &(*nextp)->next)
351 				continue;
352 			save = from;
353 			from = from->next;
354 			save->next = *nextp;
355 			*nextp = save;
356 		}
357 	}
358 
359 	for (ep = ehead; ep != NULL; ep = ep->next) {
360 		char host_buf[UT_HOSTSIZE + 1];
361 		struct sockaddr_storage ss;
362 		struct sockaddr *sa = (struct sockaddr *)&ss;
363 		struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
364 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
365 		int isaddr;
366 
367 		host_buf[UT_HOSTSIZE] = '\0';
368 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
369 		p = *host_buf ? host_buf : "-";
370 		if ((x_suffix = strrchr(p, ':')) != NULL) {
371 			if ((dot = strchr(x_suffix, '.')) != NULL &&
372 			    strchr(dot+1, '.') == NULL)
373 				*x_suffix++ = '\0';
374 			else
375 				x_suffix = NULL;
376 		}
377 		if (!nflag) {
378 			/* Attempt to change an IP address into a name */
379 			isaddr = 0;
380 			memset(&ss, '\0', sizeof(ss));
381 			if (inet_pton(AF_INET6, p, &sin6->sin6_addr) == 1) {
382 				sin6->sin6_len = sizeof(*sin6);
383 				sin6->sin6_family = AF_INET6;
384 				isaddr = 1;
385 			} else if (inet_pton(AF_INET, p, &sin->sin_addr) == 1) {
386 				sin->sin_len = sizeof(*sin);
387 				sin->sin_family = AF_INET;
388 				isaddr = 1;
389 			}
390 			if (isaddr && realhostname_sa(fn, sizeof(fn), sa,
391 			    sa->sa_len) == HOSTNAME_FOUND)
392 				p = fn;
393 		}
394 		if (x_suffix) {
395 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x_suffix);
396 			p = buf;
397 		}
398 		if (dflag) {
399 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
400 				char *ptr;
401 
402 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
403 				    dkp->ki_comm, MAXCOMLEN);
404 				if (ptr == NULL)
405 					ptr = "-";
406 				(void)printf("\t\t%-9d %s\n",
407 				    dkp->ki_pid, ptr);
408 			}
409 		}
410 		(void)printf("%-*.*s %-*.*s %-*.*s ",
411 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
412 		    UT_LINESIZE, UT_LINESIZE,
413 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
414 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
415 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
416 		    W_DISPHOSTSIZE, W_DISPHOSTSIZE, *p ? p : "-");
417 		pr_attime(&ep->utmp.ut_time, &now);
418 		longidle = pr_idle(ep->idle);
419 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
420 	}
421 	(void)kvm_close(kd);
422 	exit(0);
423 }
424 
425 static void
426 pr_header(nowp, nusers)
427 	time_t *nowp;
428 	int nusers;
429 {
430 	double avenrun[3];
431 	time_t uptime;
432 	int days, hrs, i, mins, secs;
433 	int mib[2];
434 	size_t size;
435 	char buf[256];
436 
437 	/*
438 	 * Print time of day.
439 	 */
440 	(void)strftime(buf, sizeof(buf)	- 1,
441 		       use_ampm	? "%l:%M%p" : "%k:%M", localtime(nowp));
442 	buf[sizeof(buf) - 1] = '\0';
443 	(void)printf("%s ", buf);
444 
445 	/*
446 	 * Print how long system has been up.
447 	 * (Found by looking getting "boottime" from the kernel)
448 	 */
449 	mib[0] = CTL_KERN;
450 	mib[1] = KERN_BOOTTIME;
451 	size = sizeof(boottime);
452 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
453 	    boottime.tv_sec != 0) {
454 		uptime = now - boottime.tv_sec;
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