xref: /dragonfly/usr.bin/w/w.c (revision 5667bed1)
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1980, 1991, 1993, 1994 The Regents of the University of California.  All rights reserved.
30  * @(#)w.c	8.4 (Berkeley) 4/16/94
31  * $FreeBSD: src/usr.bin/w/w.c,v 1.38.2.6 2002/03/12 19:51:51 phantom Exp $
32  */
33 
34 /*
35  * w - print system status (who and what)
36  *
37  * This program is similar to the systat command on Tenex/Tops 10/20
38  *
39  */
40 #include <sys/user.h>
41 #include <sys/param.h>
42 #include <sys/time.h>
43 #include <sys/stat.h>
44 #include <sys/sysctl.h>
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #include <sys/tty.h>
48 
49 #include <machine/cpu.h>
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
52 
53 #include <ctype.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <kvm.h>
58 #include <limits.h>
59 #include <langinfo.h>
60 #include <locale.h>
61 #include <netdb.h>
62 #include <nlist.h>
63 #include <paths.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <utmpx.h>
69 #include <vis.h>
70 
71 #include <arpa/nameser.h>
72 #include <resolv.h>
73 
74 #include "extern.h"
75 
76 struct timeval	boottime;
77 struct winsize	ws;
78 kvm_t	       *kd;
79 time_t		now;		/* the current time of day */
80 time_t		then;
81 time_t		uptime;		/* time of last reboot & elapsed time since */
82 int		ttywidth;	/* width of tty */
83 int		argwidth;	/* width of tty */
84 int		header = 1;	/* true if -h flag: don't print heading */
85 int		nflag;		/* true if -n flag: don't convert addrs */
86 int		dflag;		/* true if -d flag: output debug info */
87 int		sortidle;	/* sort by idle time */
88 int		use_ampm;	/* use AM/PM time */
89 int             use_comma;      /* use comma as floats separator */
90 char	      **sel_users;	/* login array of particular users selected */
91 char		domain[MAXHOSTNAMELEN];
92 int maxname = 8, maxline = 3, maxhost = 16;
93 
94 /*
95  * One of these per active utmp entry.
96  */
97 struct	entry {
98 	struct	entry *next;
99 	char name[UTX_USERSIZE + 1];
100 	char line[UTX_LINESIZE + 1];
101 	char host[UTX_HOSTSIZE + 1];
102 	char type[2];
103 	struct timeval tv;
104 	dev_t	tdev;			/* dev_t of terminal */
105 	time_t	idle;			/* idle time of terminal in seconds */
106 	struct	kinfo_proc *kp;		/* `most interesting' proc */
107 	char	*args;			/* arg list of interesting process */
108 	struct	kinfo_proc *dkp;	/* debug option proc list */
109 	pid_t	pid;			/* pid or ~0 if not known */
110 } *ep, *ehead = NULL, **nextp = &ehead;
111 
112 #define debugproc(p) *((struct kinfo_proc **)&(p)->kp_spare[0])
113 
114 static void		 pr_header(time_t *, int);
115 static struct stat	*ttystat(char *, int);
116 static void	process(struct entry *);
117 static void		 usage(int);
118 static int		 this_is_uptime(const char *s);
119 
120 char *fmt_argv(char **, char *, int);	/* ../../bin/ps/fmt.c */
121 
122 int
123 main(int argc, char **argv)
124 {
125 	struct kinfo_proc *kp;
126 	struct kinfo_proc *dkp;
127 	struct hostent *hp;
128 	in_addr_t l;
129 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
130 	char *memf, *nlistf, *p, *x;
131 	struct utmpx *utx;
132 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
133 
134 	(void)setlocale(LC_ALL, "");
135 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
136 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
137 
138 	/* Are we w(1) or uptime(1)? */
139 	if (this_is_uptime(argv[0]) == 0) {
140 		wcmd = 0;
141 		p = "";
142 	} else {
143 		wcmd = 1;
144 		p = "dhiflM:N:nsuw";
145 	}
146 
147 	dropgid = 0;
148 	memf = nlistf = _PATH_DEVNULL;
149 	while ((ch = getopt(argc, argv, p)) != -1)
150 		switch (ch) {
151 		case 'd':
152 			dflag = 1;
153 			break;
154 		case 'h':
155 			header = 0;
156 			break;
157 		case 'i':
158 			sortidle = 1;
159 			break;
160 		case 'M':
161 			header = 0;
162 			memf = optarg;
163 			dropgid = 1;
164 			break;
165 		case 'N':
166 			nlistf = optarg;
167 			dropgid = 1;
168 			break;
169 		case 'n':
170 			nflag = 1;
171 			break;
172 		case 'f': case 'l': case 's': case 'u': case 'w':
173 			warnx("[-flsuw] no longer supported");
174 			/* FALLTHROUGH */
175 		case '?':
176 		default:
177 			usage(wcmd);
178 		}
179 	argc -= optind;
180 	argv += optind;
181 
182 	if (!(_res.options & RES_INIT))
183 		res_init();
184 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
185 	_res.retry = 1;		/* only try once.. */
186 
187 	/*
188 	 * Discard setgid privileges if not the running kernel so that bad
189 	 * guys can't print interesting stuff from kernel memory.
190 	 */
191 	if (dropgid)
192 		setgid(getgid());
193 
194 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
195 		errx(1, "%s", errbuf);
196 
197 	(void)time(&now);
198 	setutxent();
199 
200 	if (*argv)
201 		sel_users = argv;
202 
203 	nusers = 0;
204 	while ((utx = getutxent()) != NULL) {
205 		if (utx->ut_type != USER_PROCESS)
206 			continue;
207 		++nusers;
208 
209 		if (sel_users) {
210 			int usermatch;
211 			char **user;
212 
213 			usermatch = 0;
214 			for (user = sel_users; !usermatch && *user; user++)
215 				if (!strncmp(utx->ut_name, *user, UTX_USERSIZE))
216 					usermatch = 1;
217 			if (!usermatch)
218 				continue;
219 		}
220 
221 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
222 			err(1, NULL);
223 		(void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
224 		(void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
225 		(void)memcpy(ep->host, utx->ut_host, sizeof(utx->ut_host));
226 		ep->name[sizeof(utx->ut_name)] = '\0';
227 		ep->line[sizeof(utx->ut_line)] = '\0';
228 		ep->host[sizeof(utx->ut_host)] = '\0';
229 #if 1
230 		/* XXX: Actually we don't support the utx->ut_ss stuff yet */
231 		if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
232 		    utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
233 		    NI_NUMERICHOST) != 0) {
234 			(void)memcpy(ep->host, utx->ut_host,
235 			    sizeof(utx->ut_host));
236 			ep->host[sizeof(utx->ut_host)] = '\0';
237 		}
238 #endif
239 		ep->type[0] = 'x';
240 		ep->tv = utx->ut_tv;
241 		ep->pid = utx->ut_pid;
242 
243 		*nextp = ep;
244 		nextp = &(ep->next);
245 		if (wcmd != 0)
246 			process(ep);
247 	}
248 	endutxent();
249 
250 	if (header || wcmd == 0) {
251 		pr_header(&now, nusers);
252 		if (wcmd == 0) {
253 			(void)kvm_close(kd);
254 			exit(0);
255 		}
256 
257 #define HEADER_USER		"USER"
258 #define HEADER_TTY		"TTY"
259 #define HEADER_FROM		"FROM"
260 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
261 #define HEADER_WHAT		"WHAT\n"
262 #define WUSED  (maxname + maxline + maxhost + \
263 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
264 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
265 				maxname, maxname, HEADER_USER,
266 				maxline, maxline, HEADER_TTY,
267 				maxhost, maxhost, HEADER_FROM,
268 				HEADER_LOGIN_IDLE HEADER_WHAT);
269 	}
270 
271 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
272 		err(1, "%s", kvm_geterr(kd));
273 	for (i = 0; i < nentries; i++, kp++) {
274 		if (kp->kp_stat == SIDL || kp->kp_stat == SZOMB)
275 			continue;
276 		for (ep = ehead; ep != NULL; ep = ep->next) {
277 			if (ep->tdev == kp->kp_tdev) {
278 				/*
279 				 * proc is associated with this terminal
280 				 */
281 				if (ep->kp == NULL && kp->kp_pgid == kp->kp_tpgid) {
282 					/*
283 					 * Proc is 'most interesting'
284 					 */
285 					if (proc_compare(ep->kp, kp))
286 						ep->kp = kp;
287 				}
288 				/*
289 				 * Proc debug option info; add to debug
290 				 * list using kinfo_proc kp_eproc.e_spare
291 				 * as next pointer; ptr to ptr avoids the
292 				 * ptr = long assumption.
293 				 */
294 				dkp = ep->dkp;
295 				ep->dkp = kp;
296 				debugproc(kp) = dkp;
297 			}
298 			if (ep->pid != 0 && ep->pid == kp->kp_pid) {
299 				ep->kp = kp;
300 				break;
301 			}
302 		}
303 	}
304 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
305 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
306 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
307 	       ttywidth = 79;
308         else
309 	       ttywidth = ws.ws_col - 1;
310 	argwidth = ttywidth - WUSED;
311 	if (argwidth < 4)
312 		argwidth = 8;
313 	for (ep = ehead; ep != NULL; ep = ep->next) {
314 		if (ep->kp == NULL) {
315 			ep->args = "-";
316 			continue;
317 		}
318 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
319 		    ep->kp->kp_comm, MAXCOMLEN);
320 		if (ep->args == NULL)
321 			err(1, NULL);
322 	}
323 	/* sort by idle time */
324 	if (sortidle && ehead != NULL) {
325 		struct entry *from, *save;
326 
327 		from = ehead;
328 		ehead = NULL;
329 		while (from != NULL) {
330 			for (nextp = &ehead;
331 			    (*nextp) && from->idle >= (*nextp)->idle;
332 			    nextp = &(*nextp)->next)
333 				continue;
334 			save = from;
335 			from = from->next;
336 			save->next = *nextp;
337 			*nextp = save;
338 		}
339 	} else if (ehead != NULL) {
340 		struct entry *from = ehead, *save;
341 
342 		ehead = NULL;
343 		while (from != NULL) {
344 			for (nextp = &ehead;
345 			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
346 			    nextp = &(*nextp)->next)
347 				continue;
348 			save = from;
349 			from = from->next;
350 			save->next = *nextp;
351 			*nextp = save;
352 		}
353 	}
354 
355 	if (!nflag) {
356 		if (gethostname(domain, sizeof(domain)) < 0 ||
357 		    (p = strchr(domain, '.')) == NULL)
358 			domain[0] = '\0';
359 		else {
360 			domain[sizeof(domain) - 1] = '\0';
361 			memmove(domain, p, strlen(p) + 1);
362 		}
363 	}
364 
365 	for (ep = ehead; ep != NULL; ep = ep->next) {
366 		char host_buf[UTX_HOSTSIZE + 1];
367 
368 		host_buf[UTX_HOSTSIZE] = '\0';
369 		strncpy(host_buf, ep->host, maxhost);
370 		p = *host_buf ? host_buf : "-";
371 		if ((x = strchr(p, ':')) != NULL)
372 			*x++ = '\0';
373 		if (!nflag && isdigit(*p) &&
374 		    (l = inet_addr(p)) != INADDR_NONE &&
375 		    (hp = gethostbyaddr(&l, sizeof(l), AF_INET))) {
376 			if (domain[0] != '\0') {
377 				p = hp->h_name;
378 				p += strlen(hp->h_name);
379 				p -= strlen(domain);
380 				if (p > hp->h_name &&
381 				    strcasecmp(p, domain) == 0)
382 					*p = '\0';
383 			}
384 			p = hp->h_name;
385 		}
386 		if (nflag && *p && strcmp(p, "-") &&
387 		    inet_addr(p) == INADDR_NONE) {
388 			hp = gethostbyname(p);
389 
390 			if (hp != NULL) {
391 				struct in_addr in;
392 
393 				memmove(&in, hp->h_addr, sizeof(in));
394 				p = inet_ntoa(in);
395 			}
396 		}
397 		if (x) {
398 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
399 			p = buf;
400 		}
401 		if (dflag) {
402 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
403 				char *ptr;
404 
405 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
406 				    dkp->kp_comm, MAXCOMLEN);
407 				if (ptr == NULL)
408 					ptr = "-";
409 				(void)printf("\t\t%-9d %s\n",
410 				    dkp->kp_pid, ptr);
411 			}
412 		}
413 		(void)printf("%-*.*s %-*.*s %-*.*s ",
414 		    maxname, maxname, ep->name,
415 		    maxline, maxline,
416 		    strncmp(ep->line, "tty", 3) &&
417 		    strncmp(ep->line, "cua", 3) ?
418 		    ep->line : ep->line + 3,
419 		    maxhost, maxhost, *p ? p : "-");
420 		then = (time_t)ep->tv.tv_sec;
421 		pr_attime(&then, &now);
422 		longidle = pr_idle(ep->idle);
423 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
424 	}
425 	(void)kvm_close(kd);
426 	exit(0);
427 }
428 
429 static void
430 pr_header(time_t *nowp, int nusers)
431 {
432 	double avenrun[3];
433 	time_t uptime;
434 	int days, hrs, i, mins, secs;
435 	int mib[2];
436 	size_t size;
437 	char buf[256];
438 
439 	/*
440 	 * Print time of day. (use "AM"/"PM" for all locales)
441 	 */
442 	(void)strftime_l(buf, sizeof(buf) - 1,
443 		       use_ampm	? "%l:%M%p" : "%k:%M",
444 		       localtime(nowp), NULL);
445 	buf[sizeof(buf) - 1] = '\0';
446 	(void)printf("%s ", buf);
447 
448 	/*
449 	 * Print how long system has been up.
450 	 * (Found by looking at "boottime" from the kernel)
451 	 */
452 	mib[0] = CTL_KERN;
453 	mib[1] = KERN_BOOTTIME;
454 	size = sizeof(boottime);
455 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
456 	    boottime.tv_sec != 0) {
457 		uptime = now - boottime.tv_sec;
458 		if (uptime > 60)
459 			uptime += 30;
460 		days = uptime / 86400;
461 		uptime %= 86400;
462 		hrs = uptime / 3600;
463 		uptime %= 3600;
464 		mins = uptime / 60;
465 		secs = uptime % 60;
466 		(void)printf(" up");
467 		if (days > 0)
468 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
469 		if (hrs > 0 && mins > 0)
470 			(void)printf(" %2d:%02d,", hrs, mins);
471 		else if (hrs > 0)
472 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
473 		else if (mins > 0)
474 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
475 		else
476 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
477 	}
478 
479 	/* Print number of users logged in on system */
480 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
481 
482 	/*
483 	 * Print 1, 5, and 15 minute load averages.
484 	 */
485 	if (getloadavg(avenrun, NELEM(avenrun)) == -1)
486 		(void)printf(", no load average information available\n");
487 	else {
488 		(void)printf(", load averages:");
489 		for (i = 0; i < (int)NELEM(avenrun); i++) {
490 			if (use_comma && i > 0)
491 				(void)printf(",");
492 			(void)printf(" %.2f", avenrun[i]);
493 		}
494 		(void)printf("\n");
495 	}
496 }
497 
498 static struct stat *
499 ttystat(char *line, int sz)
500 {
501 	static struct stat sb;
502 	char ttybuf[MAXPATHLEN];
503 
504 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
505 	if (stat(ttybuf, &sb)) {
506 		warn("%s", ttybuf);
507 		return (NULL);
508 	}
509 	return (&sb);
510 }
511 
512 static void
513 usage(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(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 
537 static void
538 process(struct entry *ep)
539 {
540 	struct stat *stp;
541 	time_t touched;
542 	int max;
543 
544 	if ((max = strlen(ep->name)) > maxname)
545 		maxname = max;
546 	if ((max = strlen(ep->line)) > maxline)
547 		maxline = max;
548 	if ((max = strlen(ep->host)) > maxhost)
549 		maxhost = max;
550 
551 	ep->tdev = 0;
552 	ep->idle = (time_t)-1;
553 
554 	if (!(stp = ttystat(ep->line, maxline)))
555 		return;	/* corrupted record */
556 
557 	ep->tdev = stp->st_rdev;
558 #ifdef CPU_CONSDEV
559 	/*
560 	 * If this is the console device, attempt to ascertain
561 	 * the true console device dev_t.
562 	 */
563 	if (ep->tdev == 0) {
564 		int mib[2];
565 		size_t size;
566 
567 		mib[0] = CTL_MACHDEP;
568 		mib[1] = CPU_CONSDEV;
569 		size = sizeof(dev_t);
570 		(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
571 	}
572 #endif
573 
574 	touched = stp->st_atime;
575 	if (touched < ep->tv.tv_sec) {
576 		/* tty untouched since before login */
577 		touched = ep->tv.tv_sec;
578 	}
579 	if ((ep->idle = now - touched) < 0)
580 		ep->idle = 0;
581 }
582