xref: /freebsd/usr.bin/w/w.c (revision 2ad872c5794e4c26fdf6ed219ad3f09ca0d5304a)
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 	"$Id: w.c,v 1.31 1998/12/24 23:27:33 dillon Exp $";
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 <netdb.h>
74 #include <nlist.h>
75 #include <paths.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <unistd.h>
80 #include <utmp.h>
81 #include <vis.h>
82 #include <locale.h>
83 
84 #include <arpa/nameser.h>
85 #include <resolv.h>
86 
87 #include "extern.h"
88 
89 struct timeval	boottime;
90 struct utmp	utmp;
91 struct winsize	ws;
92 kvm_t	       *kd;
93 time_t		now;		/* the current time of day */
94 time_t		uptime;		/* time of last reboot & elapsed time since */
95 int		ttywidth;	/* width of tty */
96 int		argwidth;	/* width of tty */
97 int		header = 1;	/* true if -h flag: don't print heading */
98 int		nflag;		/* true if -n flag: don't convert addrs */
99 int		dflag;		/* true if -d flag: output debug info */
100 int		sortidle;	/* sort by idle time */
101 char	       *sel_user;	/* login of particular user selected */
102 char		domain[MAXHOSTNAMELEN];
103 
104 /*
105  * One of these per active utmp entry.
106  */
107 struct	entry {
108 	struct	entry *next;
109 	struct	utmp 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 static void	pr_header __P((time_t *, int));
118 static struct stat
119 		*ttystat __P((char *));
120 static void	usage __P((int));
121 static int	this_is_uptime __P((const char *s));
122 
123 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
124 
125 int
126 main(argc, argv)
127 	int argc;
128 	char **argv;
129 {
130 	extern char *__progname;
131 	struct kinfo_proc *kp;
132 	struct kinfo_proc *dkp;
133 	struct hostent *hp;
134 	struct stat *stp;
135 	FILE *ut;
136 	u_long l;
137 	size_t arglen;
138 	int ch, i, nentries, nusers, wcmd, longidle;
139 	char *memf, *nlistf, *p, *x;
140 	char buf[MAXHOSTNAMELEN], errbuf[256];
141 
142 	(void) setlocale(LC_ALL, "");
143 
144 	/* Are we w(1) or uptime(1)? */
145 	if (this_is_uptime(argv[0]) == 0) {
146 		wcmd = 0;
147 		p = "";
148 	} else {
149 		wcmd = 1;
150 		p = "dhiflM:N:nsuw";
151 	}
152 
153 	memf = nlistf = NULL;
154 	while ((ch = getopt(argc, argv, p)) != -1)
155 		switch (ch) {
156 		case 'd':
157 			dflag = 1;
158 			break;
159 		case 'h':
160 			header = 0;
161 			break;
162 		case 'i':
163 			sortidle = 1;
164 			break;
165 		case 'M':
166 			header = 0;
167 			memf = optarg;
168 			break;
169 		case 'N':
170 			nlistf = optarg;
171 			break;
172 		case 'n':
173 			nflag = 1;
174 			break;
175 		case 'f': case 'l': case 's': case 'u': case 'w':
176 			warnx("[-flsuw] no longer supported");
177 			/* FALLTHROUGH */
178 		case '?':
179 		default:
180 			usage(wcmd);
181 		}
182 	argc -= optind;
183 	argv += optind;
184 
185 	if (!(_res.options & RES_INIT))
186 		res_init();
187 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
188 	_res.retry = 1;		/* only try once.. */
189 
190 	/*
191 	 * Discard setgid privileges if not the running kernel so that bad
192 	 * guys can't print interesting stuff from kernel memory.
193 	 */
194 	if (nlistf != NULL || memf != NULL)
195 		setgid(getgid());
196 
197 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
198 		errx(1, "%s", errbuf);
199 
200 	(void)time(&now);
201 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
202 		err(1, "%s", _PATH_UTMP);
203 
204 	if (*argv)
205 		sel_user = *argv;
206 
207 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
208 		if (utmp.ut_name[0] == '\0')
209 			continue;
210 		if (!(stp = ttystat(utmp.ut_line))) /* corrupted record */
211 			continue;
212 		++nusers;
213 		if (wcmd == 0 || (sel_user &&
214 		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
215 			continue;
216 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
217 			errx(1, "calloc");
218 		*nextp = ep;
219 		nextp = &(ep->next);
220 		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
221 		ep->tdev = stp->st_rdev;
222 #ifdef CPU_CONSDEV
223 		/*
224 		 * If this is the console device, attempt to ascertain
225 		 * the true console device dev_t.
226 		 */
227 		if (ep->tdev == 0) {
228 			int mib[2];
229 			size_t size;
230 
231 			mib[0] = CTL_MACHDEP;
232 			mib[1] = CPU_CONSDEV;
233 			size = sizeof(dev_t);
234 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
235 		}
236 #endif
237 		if ((ep->idle = now - stp->st_atime) < 0)
238 			ep->idle = 0;
239 	}
240 	(void)fclose(ut);
241 
242 	if (header || wcmd == 0) {
243 		pr_header(&now, nusers);
244 		if (wcmd == 0)
245 			exit (0);
246 
247 #define HEADER_USER		"USER"
248 #define HEADER_TTY		"TTY"
249 #define HEADER_FROM		"FROM"
250 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
251 #define HEADER_WHAT		"WHAT\n"
252 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
253 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
254 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
255 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
256 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
257 				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
258 				HEADER_LOGIN_IDLE HEADER_WHAT);
259 	}
260 
261 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
262 		err(1, "%s", kvm_geterr(kd));
263 	for (i = 0; i < nentries; i++, kp++) {
264 		struct proc *p = &kp->kp_proc;
265 		struct eproc *e;
266 
267 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
268 			continue;
269 		e = &kp->kp_eproc;
270 		for (ep = ehead; ep != NULL; ep = ep->next) {
271 			if (ep->tdev == e->e_tdev) {
272 				/*
273 				 * proc is associated with this terminal
274 				 */
275 				if (ep->kp == NULL && e->e_pgid == e->e_tpgid) {
276 					/*
277 					 * Proc is 'most interesting'
278 					 */
279 					if (proc_compare(&ep->kp->kp_proc, p))
280 						ep->kp = kp;
281 				}
282 				/*
283 				 * Proc debug option info; add to debug
284 				 * list using kinfo_proc kp_eproc.e_spare
285 				 * as next pointer; ptr to ptr avoids the
286 				 * ptr = long assumption.
287 				 */
288 				dkp = ep->dkp;
289 				ep->dkp = kp;
290 				*((struct kinfo_proc **)(&kp->kp_eproc.e_spare[0])) = dkp;
291 			}
292 		}
293 	}
294 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
295 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
296 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
297 	       ttywidth = 79;
298         else
299 	       ttywidth = ws.ws_col - 1;
300 	argwidth = ttywidth - WUSED;
301 	if (argwidth < 4)
302 		argwidth = 8;
303 	for (ep = ehead; ep != NULL; ep = ep->next) {
304 		if (ep->kp == NULL) {
305 			ep->args = "-";
306 			continue;
307 		}
308 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
309 		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
310 		if (ep->args == NULL)
311 			err(1, NULL);
312 	}
313 	/* sort by idle time */
314 	if (sortidle && ehead != NULL) {
315 		struct entry *from = ehead, *save;
316 
317 		ehead = NULL;
318 		while (from != NULL) {
319 			for (nextp = &ehead;
320 			    (*nextp) && from->idle >= (*nextp)->idle;
321 			    nextp = &(*nextp)->next)
322 				continue;
323 			save = from;
324 			from = from->next;
325 			save->next = *nextp;
326 			*nextp = save;
327 		}
328 	}
329 
330 	if (!nflag)
331 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
332 		    (p = strchr(domain, '.')) == 0)
333 			domain[0] = '\0';
334 		else {
335 			domain[sizeof(domain) - 1] = '\0';
336 			memmove(domain, p, strlen(p) + 1);
337 		}
338 
339 	for (ep = ehead; ep != NULL; ep = ep->next) {
340 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
341 		if ((x = strchr(p, ':')) != NULL)
342 			*x++ = '\0';
343 		if (!nflag && isdigit(*p) &&
344 		    (long)(l = inet_addr(p)) != -1 &&
345 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
346 			if (domain[0] != '\0') {
347 				p = hp->h_name;
348 				p += strlen(hp->h_name);
349 				p -= strlen(domain);
350 				if (p > hp->h_name && strcmp(p, domain) == 0)
351 					*p = '\0';
352 			}
353 			p = hp->h_name;
354 		}
355 		if (nflag && *p && strcmp(p, "-") &&
356 		    inet_addr(p) == INADDR_NONE) {
357 			hp = gethostbyname(p);
358 
359 			if (hp != NULL) {
360 				struct in_addr in;
361 
362 				memmove(&in, hp->h_addr, sizeof(in));
363 				p = inet_ntoa(in);
364 			}
365 		}
366 		if (x) {
367 			(void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
368 			    ep->utmp.ut_host + UT_HOSTSIZE - x, x);
369 			p = buf;
370 		}
371 		if (dflag) {
372 			for (dkp = ep->dkp; dkp != NULL; dkp = *((struct kinfo_proc **)(&dkp->kp_eproc.e_spare[0]))) {
373 				char *p;
374 				p = fmt_argv(kvm_getargv(kd, dkp, argwidth),
375 					    dkp->kp_proc.p_comm, MAXCOMLEN);
376 				if (p == NULL)
377 					p = "-";
378 				(void)printf( "\t\t%-9d %s\n", dkp->kp_proc.p_pid, p);
379 			}
380 		}
381 		(void)printf("%-*.*s %-*.*s %-*.*s ",
382 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
383 		    UT_LINESIZE, UT_LINESIZE,
384 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
385 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
386 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
387 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
388 		pr_attime(&ep->utmp.ut_time, &now);
389 		longidle = pr_idle(ep->idle);
390 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
391 	}
392 	exit(0);
393 }
394 
395 static void
396 pr_header(nowp, nusers)
397 	time_t *nowp;
398 	int nusers;
399 {
400 	double avenrun[3];
401 	time_t uptime;
402 	int days, hrs, i, mins, secs;
403 	int mib[2];
404 	size_t size;
405 	char buf[256];
406 
407 	/*
408 	 * Print time of day.
409 	 *
410 	 * SCCS forces the string manipulation below, as it replaces
411 	 * %, M, and % in a character string with the file name.
412 	 */
413 	(void)strftime(buf, sizeof(buf) - 1,
414 	    __CONCAT("%l:%","M%p"), localtime(nowp));
415 	buf[sizeof(buf) - 1] = '\0';
416 	(void)printf("%s ", buf);
417 
418 	/*
419 	 * Print how long system has been up.
420 	 * (Found by looking getting "boottime" from the kernel)
421 	 */
422 	mib[0] = CTL_KERN;
423 	mib[1] = KERN_BOOTTIME;
424 	size = sizeof(boottime);
425 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
426 	    boottime.tv_sec != 0) {
427 		uptime = now - boottime.tv_sec;
428 		uptime += 30;
429 		days = uptime / 86400;
430 		uptime %= 86400;
431 		hrs = uptime / 3600;
432 		uptime %= 3600;
433 		mins = uptime / 60;
434 		secs = uptime % 60;
435 		(void)printf(" up");
436 		if (days > 0)
437 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
438 		if (hrs > 0 && mins > 0)
439 			(void)printf(" %2d:%02d,", hrs, mins);
440 		else if (hrs > 0)
441 			(void)printf(" %d hr%s,",
442 				     hrs, hrs > 1 ? "s" : "");
443 		else if (mins > 0)
444 			(void)printf(" %d min%s,",
445 				     mins, mins > 1 ? "s" : "");
446 		else
447 			(void)printf(" %d sec%s,",
448 				     secs, secs > 1 ? "s" : "");
449 	}
450 
451 	/* Print number of users logged in to system */
452 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
453 
454 	/*
455 	 * Print 1, 5, and 15 minute load averages.
456 	 */
457 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
458 		(void)printf(", no load average information available\n");
459 	else {
460 		(void)printf(", load averages:");
461 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
462 			if (i > 0)
463 				(void)printf(",");
464 			(void)printf(" %.2f", avenrun[i]);
465 		}
466 		(void)printf("\n");
467 	}
468 }
469 
470 static struct stat *
471 ttystat(line)
472 	char *line;
473 {
474 	static struct stat sb;
475 	char ttybuf[MAXPATHLEN];
476 
477 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
478 	if (stat(ttybuf, &sb)) {
479 		warn("%s", ttybuf);
480 		return NULL;
481 	}
482 	return (&sb);
483 }
484 
485 static void
486 usage(wcmd)
487 	int wcmd;
488 {
489 	if (wcmd)
490 		(void)fprintf(stderr,
491 		    "usage: w [-dhin] [-M core] [-N system] [user]\n");
492 	else
493 		(void)fprintf(stderr,
494 			"usage: uptime\n");
495 	exit (1);
496 }
497 
498 static int
499 this_is_uptime(s)
500 	const char *s;
501 {
502 	const char *u;
503 
504 	if ((u = strrchr(s, '/')) != NULL)
505 		++u;
506 	else
507 		u = s;
508 	if (strcmp(u, "uptime") == 0)
509 		return(0);
510 	return(-1);
511 }
512 
513