xref: /freebsd/usr.bin/w/w.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
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 <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 char		domain[MAXHOSTNAMELEN];
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 static void		 pr_header __P((time_t *, int));
125 static struct stat	*ttystat __P((char *, int));
126 static void		 usage __P((int));
127 static int		 this_is_uptime __P((const char *s));
128 
129 char *fmt_argv __P((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 hostent *hp;
139 	struct stat *stp;
140 	FILE *ut;
141 	u_long l;
142 	time_t touched;
143 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
144 	char *memf, *nlistf, *p, *x;
145 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
146 
147 	(void)setlocale(LC_ALL, "");
148 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
149 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
150 
151 	/* Are we w(1) or uptime(1)? */
152 	if (this_is_uptime(argv[0]) == 0) {
153 		wcmd = 0;
154 		p = "";
155 	} else {
156 		wcmd = 1;
157 		p = "dhiflM:N:nsuw";
158 	}
159 
160 	dropgid = 0;
161 	memf = nlistf = _PATH_DEVNULL;
162 	while ((ch = getopt(argc, argv, p)) != -1)
163 		switch (ch) {
164 		case 'd':
165 			dflag = 1;
166 			break;
167 		case 'h':
168 			header = 0;
169 			break;
170 		case 'i':
171 			sortidle = 1;
172 			break;
173 		case 'M':
174 			header = 0;
175 			memf = optarg;
176 			dropgid = 1;
177 			break;
178 		case 'N':
179 			nlistf = optarg;
180 			dropgid = 1;
181 			break;
182 		case 'n':
183 			nflag = 1;
184 			break;
185 		case 'f': case 'l': case 's': case 'u': case 'w':
186 			warnx("[-flsuw] no longer supported");
187 			/* FALLTHROUGH */
188 		case '?':
189 		default:
190 			usage(wcmd);
191 		}
192 	argc -= optind;
193 	argv += optind;
194 
195 	if (!(_res.options & RES_INIT))
196 		res_init();
197 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
198 	_res.retry = 1;		/* only try once.. */
199 
200 	/*
201 	 * Discard setgid privileges if not the running kernel so that bad
202 	 * guys can't print interesting stuff from kernel memory.
203 	 */
204 	if (dropgid)
205 		setgid(getgid());
206 
207 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
208 		errx(1, "%s", errbuf);
209 
210 	(void)time(&now);
211 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
212 		err(1, "%s", _PATH_UTMP);
213 
214 	if (*argv)
215 		sel_users = argv;
216 
217 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
218 		if (utmp.ut_name[0] == '\0')
219 			continue;
220 		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
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 (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
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(struct utmp));
241 		ep->tdev = stp->st_rdev;
242 #ifdef CPU_CONSDEV
243 		/*
244 		 * If this is the console device, attempt to ascertain
245 		 * the true console device dev_t.
246 		 */
247 		if (ep->tdev == 0) {
248 			int mib[2];
249 			size_t size;
250 
251 			mib[0] = CTL_MACHDEP;
252 			mib[1] = CPU_CONSDEV;
253 			size = sizeof(dev_t);
254 			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
255 		}
256 #endif
257 		touched = stp->st_atime;
258 		if (touched < ep->utmp.ut_time) {
259 			/* tty untouched since before login */
260 			touched = ep->utmp.ut_time;
261 		}
262 		if ((ep->idle = now - touched) < 0)
263 			ep->idle = 0;
264 	}
265 	(void)fclose(ut);
266 
267 	if (header || wcmd == 0) {
268 		pr_header(&now, nusers);
269 		if (wcmd == 0) {
270 			(void)kvm_close(kd);
271 			exit(0);
272 		}
273 
274 #define HEADER_USER		"USER"
275 #define HEADER_TTY		"TTY"
276 #define HEADER_FROM		"FROM"
277 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
278 #define HEADER_WHAT		"WHAT\n"
279 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
280 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
281 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
282 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
283 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
284 				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
285 				HEADER_LOGIN_IDLE HEADER_WHAT);
286 	}
287 
288 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
289 		err(1, "%s", kvm_geterr(kd));
290 	for (i = 0; i < nentries; i++, kp++) {
291 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
292 			continue;
293 		for (ep = ehead; ep != NULL; ep = ep->next) {
294 			if (ep->tdev == kp->ki_tdev) {
295 				/*
296 				 * proc is associated with this terminal
297 				 */
298 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
299 					/*
300 					 * Proc is 'most interesting'
301 					 */
302 					if (proc_compare(ep->kp, kp))
303 						ep->kp = kp;
304 				}
305 				/*
306 				 * Proc debug option info; add to debug
307 				 * list using kinfo_proc ki_spare[0]
308 				 * as next pointer; ptr to ptr avoids the
309 				 * ptr = long assumption.
310 				 */
311 				dkp = ep->dkp;
312 				ep->dkp = kp;
313 				debugproc(kp) = dkp;
314 			}
315 		}
316 	}
317 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
318 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
319 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
320 	       ttywidth = 79;
321         else
322 	       ttywidth = ws.ws_col - 1;
323 	argwidth = ttywidth - WUSED;
324 	if (argwidth < 4)
325 		argwidth = 8;
326 	for (ep = ehead; ep != NULL; ep = ep->next) {
327 		if (ep->kp == NULL) {
328 			ep->args = "-";
329 			continue;
330 		}
331 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
332 		    ep->kp->ki_comm, MAXCOMLEN);
333 		if (ep->args == NULL)
334 			err(1, NULL);
335 	}
336 	/* sort by idle time */
337 	if (sortidle && ehead != NULL) {
338 		struct entry *from, *save;
339 
340 		from = ehead;
341 		ehead = NULL;
342 		while (from != NULL) {
343 			for (nextp = &ehead;
344 			    (*nextp) && from->idle >= (*nextp)->idle;
345 			    nextp = &(*nextp)->next)
346 				continue;
347 			save = from;
348 			from = from->next;
349 			save->next = *nextp;
350 			*nextp = save;
351 		}
352 	}
353 
354 	if (!nflag) {
355 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
356 		    (p = strchr(domain, '.')) == NULL)
357 			domain[0] = '\0';
358 		else {
359 			domain[sizeof(domain) - 1] = '\0';
360 			memmove(domain, p, strlen(p) + 1);
361 		}
362 	}
363 
364 	for (ep = ehead; ep != NULL; ep = ep->next) {
365 		char host_buf[UT_HOSTSIZE + 1];
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 = strchr(p, ':')) != NULL)
371 			*x++ = '\0';
372 		if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 &&
373 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
374 			if (domain[0] != '\0') {
375 				p = hp->h_name;
376 				p += strlen(hp->h_name);
377 				p -= strlen(domain);
378 				if (p > hp->h_name &&
379 				    strcasecmp(p, domain) == 0)
380 					*p = '\0';
381 			}
382 			p = hp->h_name;
383 		}
384 		if (nflag && *p && strcmp(p, "-") &&
385 		    inet_addr(p) == INADDR_NONE) {
386 			hp = gethostbyname(p);
387 
388 			if (hp != NULL) {
389 				struct in_addr in;
390 
391 				memmove(&in, hp->h_addr, sizeof(in));
392 				p = inet_ntoa(in);
393 			}
394 		}
395 		if (x) {
396 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
397 			p = buf;
398 		}
399 		if (dflag) {
400 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
401 				char *ptr;
402 
403 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
404 				    dkp->ki_comm, MAXCOMLEN);
405 				if (ptr == NULL)
406 					ptr = "-";
407 				(void)printf("\t\t%-9d %s\n",
408 				    dkp->ki_pid, ptr);
409 			}
410 		}
411 		(void)printf("%-*.*s %-*.*s %-*.*s ",
412 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
413 		    UT_LINESIZE, UT_LINESIZE,
414 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
415 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
416 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
417 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
418 		pr_attime(&ep->utmp.ut_time, &now);
419 		longidle = pr_idle(ep->idle);
420 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
421 	}
422 	(void)kvm_close(kd);
423 	exit(0);
424 }
425 
426 static void
427 pr_header(nowp, nusers)
428 	time_t *nowp;
429 	int nusers;
430 {
431 	double avenrun[3];
432 	time_t uptime;
433 	int days, hrs, i, mins, secs;
434 	int mib[2];
435 	size_t size;
436 	char buf[256];
437 
438 	/*
439 	 * Print time of day.
440 	 */
441 	(void)strftime(buf, sizeof(buf)	- 1,
442 		       use_ampm	? "%l:%M%p" : "%k:%M", localtime(nowp));
443 	buf[sizeof(buf) - 1] = '\0';
444 	(void)printf("%s ", buf);
445 
446 	/*
447 	 * Print how long system has been up.
448 	 * (Found by looking getting "boottime" from the kernel)
449 	 */
450 	mib[0] = CTL_KERN;
451 	mib[1] = KERN_BOOTTIME;
452 	size = sizeof(boottime);
453 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
454 	    boottime.tv_sec != 0) {
455 		uptime = now - boottime.tv_sec;
456 		uptime += 30;
457 		days = uptime / 86400;
458 		uptime %= 86400;
459 		hrs = uptime / 3600;
460 		uptime %= 3600;
461 		mins = uptime / 60;
462 		secs = uptime % 60;
463 		(void)printf(" up");
464 		if (days > 0)
465 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
466 		if (hrs > 0 && mins > 0)
467 			(void)printf(" %2d:%02d,", hrs, mins);
468 		else if (hrs > 0)
469 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
470 		else if (mins > 0)
471 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
472 		else
473 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
474 	}
475 
476 	/* Print number of users logged in to system */
477 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
478 
479 	/*
480 	 * Print 1, 5, and 15 minute load averages.
481 	 */
482 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
483 		(void)printf(", no load average information available\n");
484 	else {
485 		(void)printf(", load averages:");
486 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
487 			if (use_comma && i > 0)
488 				(void)printf(",");
489 			(void)printf(" %.2f", avenrun[i]);
490 		}
491 		(void)printf("\n");
492 	}
493 }
494 
495 static struct stat *
496 ttystat(line, sz)
497 	char *line;
498 	int sz;
499 {
500 	static struct stat sb;
501 	char ttybuf[MAXPATHLEN];
502 
503 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
504 	if (stat(ttybuf, &sb)) {
505 		warn("%s", ttybuf);
506 		return (NULL);
507 	}
508 	return (&sb);
509 }
510 
511 static void
512 usage(wcmd)
513 	int wcmd;
514 {
515 	if (wcmd)
516 		(void)fprintf(stderr,
517 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
518 	else
519 		(void)fprintf(stderr, "usage: uptime\n");
520 	exit(1);
521 }
522 
523 static int
524 this_is_uptime(s)
525 	const char *s;
526 {
527 	const char *u;
528 
529 	if ((u = strrchr(s, '/')) != NULL)
530 		++u;
531 	else
532 		u = s;
533 	if (strcmp(u, "uptime") == 0)
534 		return (0);
535 	return (-1);
536 }
537