xref: /dragonfly/usr.bin/w/w.c (revision e4adeac1)
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 static struct winsize	ws;
77 static kvm_t	*kd;
78 static time_t	now;		/* the current time of day */
79 static time_t	then;
80 static int	ttywidth;	/* width of tty */
81 static int	argwidth;	/* width of tty */
82 static int	header = 1;	/* true if -h flag: don't print heading */
83 static int	nflag;		/* true if -n flag: don't convert addrs */
84 static int	dflag;		/* true if -d flag: output debug info */
85 static int	sortidle;	/* sort by idle time */
86 int		use_ampm;	/* use AM/PM time */
87 static int	use_comma;      /* use comma as floats separator */
88 static char	**sel_users;	/* login array of particular users selected */
89 static char	domain[MAXHOSTNAMELEN];
90 static int	maxname = 8, maxline = 3, maxhost = 16;
91 
92 /*
93  * One of these per active utmpx entry.
94  */
95 static struct entry {
96 	struct	entry *next;
97 	char	name[UTX_USERSIZE + 1];
98 	char	line[UTX_LINESIZE + 1];
99 	char	host[UTX_HOSTSIZE + 1];
100 	char	type[2];
101 	struct timeval tv;
102 	dev_t	tdev;			/* dev_t of terminal */
103 	time_t	idle;			/* idle time of terminal in seconds */
104 	struct	kinfo_proc *kp;		/* `most interesting' proc */
105 	char	*args;			/* arg list of interesting process */
106 	struct	kinfo_proc *dkp;	/* debug option proc list */
107 	pid_t	pid;			/* pid or ~0 if not known */
108 } *ep, *ehead = NULL, **nextp = &ehead;
109 
110 #define debugproc(p) *((struct kinfo_proc **)&(p)->kp_spare[0])
111 
112 static void		 pr_header(time_t *, int);
113 static struct stat	*ttystat(char *, int);
114 static void		 process(struct entry *);
115 static void		 usage(int);
116 static int		 this_is_uptime(const char *s);
117 
118 char *fmt_argv(char **, char *, int);	/* ../../bin/ps/fmt.c */
119 
120 int
121 main(int argc, char **argv)
122 {
123 	struct kinfo_proc *kp;
124 	struct kinfo_proc *dkp;
125 	struct hostent *hp;
126 	in_addr_t l;
127 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
128 	char *memf, *nlistf, *p, *x;
129 	struct utmpx *utx;
130 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
131 
132 	(void)setlocale(LC_ALL, "");
133 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
134 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
135 
136 	/* Are we w(1) or uptime(1)? */
137 	if (this_is_uptime(argv[0]) == 0) {
138 		wcmd = 0;
139 		p = "";
140 	} else {
141 		wcmd = 1;
142 		p = "dhiflM:N:nsuw";
143 	}
144 
145 	dropgid = 0;
146 	memf = nlistf = _PATH_DEVNULL;
147 	while ((ch = getopt(argc, argv, p)) != -1)
148 		switch (ch) {
149 		case 'd':
150 			dflag = 1;
151 			break;
152 		case 'h':
153 			header = 0;
154 			break;
155 		case 'i':
156 			sortidle = 1;
157 			break;
158 		case 'M':
159 			header = 0;
160 			memf = optarg;
161 			dropgid = 1;
162 			break;
163 		case 'N':
164 			nlistf = optarg;
165 			dropgid = 1;
166 			break;
167 		case 'n':
168 			nflag = 1;
169 			break;
170 		case 'f': case 'l': case 's': case 'u': case 'w':
171 			warnx("[-flsuw] no longer supported");
172 			/* FALLTHROUGH */
173 		case '?':
174 		default:
175 			usage(wcmd);
176 		}
177 	argc -= optind;
178 	argv += optind;
179 
180 	if (!(_res.options & RES_INIT))
181 		res_init();
182 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
183 	_res.retry = 1;		/* only try once.. */
184 
185 	/*
186 	 * Discard setgid privileges if not the running kernel so that bad
187 	 * guys can't print interesting stuff from kernel memory.
188 	 */
189 	if (dropgid)
190 		setgid(getgid());
191 
192 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
193 		errx(1, "%s", errbuf);
194 
195 	(void)time(&now);
196 	setutxent();
197 
198 	if (*argv)
199 		sel_users = argv;
200 
201 	nusers = 0;
202 	while ((utx = getutxent()) != NULL) {
203 		if (utx->ut_type != USER_PROCESS)
204 			continue;
205 		++nusers;
206 
207 		if (sel_users) {
208 			int usermatch;
209 			char **user;
210 
211 			usermatch = 0;
212 			for (user = sel_users; !usermatch && *user; user++)
213 				if (!strncmp(utx->ut_name, *user, UTX_USERSIZE))
214 					usermatch = 1;
215 			if (!usermatch)
216 				continue;
217 		}
218 
219 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
220 			err(1, NULL);
221 		(void)memcpy(ep->name, utx->ut_name, sizeof(utx->ut_name));
222 		(void)memcpy(ep->line, utx->ut_line, sizeof(utx->ut_line));
223 		(void)memcpy(ep->host, utx->ut_host, sizeof(utx->ut_host));
224 		ep->name[sizeof(utx->ut_name)] = '\0';
225 		ep->line[sizeof(utx->ut_line)] = '\0';
226 		ep->host[sizeof(utx->ut_host)] = '\0';
227 #if 1
228 		/* XXX: Actually we don't support the utx->ut_ss stuff yet */
229 		if (!nflag || getnameinfo((struct sockaddr *)&utx->ut_ss,
230 		    utx->ut_ss.ss_len, ep->host, sizeof(ep->host), NULL, 0,
231 		    NI_NUMERICHOST) != 0) {
232 			(void)memcpy(ep->host, utx->ut_host,
233 			    sizeof(utx->ut_host));
234 			ep->host[sizeof(utx->ut_host)] = '\0';
235 		}
236 #endif
237 		ep->type[0] = 'x';
238 		ep->tv = utx->ut_tv;
239 		ep->pid = utx->ut_pid;
240 
241 		*nextp = ep;
242 		nextp = &(ep->next);
243 		if (wcmd != 0)
244 			process(ep);
245 	}
246 	endutxent();
247 
248 	if (header || wcmd == 0) {
249 		pr_header(&now, nusers);
250 		if (wcmd == 0) {
251 			(void)kvm_close(kd);
252 			exit(0);
253 		}
254 
255 #define HEADER_USER		"USER"
256 #define HEADER_TTY		"TTY"
257 #define HEADER_FROM		"FROM"
258 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
259 #define HEADER_WHAT		"WHAT\n"
260 #define WUSED  (maxname + maxline + maxhost + \
261 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
262 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
263 				maxname, maxname, HEADER_USER,
264 				maxline, maxline, HEADER_TTY,
265 				maxhost, maxhost, HEADER_FROM,
266 				HEADER_LOGIN_IDLE HEADER_WHAT);
267 	}
268 
269 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
270 		err(1, "%s", kvm_geterr(kd));
271 	for (i = 0; i < nentries; i++, kp++) {
272 		/*
273 		 * login(1) is a special case.
274 		 */
275 		if (strcmp(kp->kp_comm, "login") == 0)
276 			continue;
277 		if (kp->kp_stat == SIDL || kp->kp_stat == SZOMB)
278 			continue;
279 		if (kp->kp_sid != kp->kp_tsid)
280 			continue;
281 		for (ep = ehead; ep != NULL; ep = ep->next) {
282 			if (ep->tdev == kp->kp_tdev) {
283 				/*
284 				 * proc is associated with this terminal
285 				 */
286 				if (ep->kp == NULL && kp->kp_pgid == kp->kp_tpgid) {
287 					/*
288 					 * Proc is 'most interesting'
289 					 */
290 					if (proc_compare(ep->kp, kp))
291 						ep->kp = kp;
292 				}
293 				/*
294 				 * Proc debug option info; add to debug
295 				 * list using kinfo_proc kp_eproc.e_spare
296 				 * as next pointer; ptr to ptr avoids the
297 				 * ptr = long assumption.
298 				 */
299 				dkp = ep->dkp;
300 				ep->dkp = kp;
301 				debugproc(kp) = dkp;
302 			}
303 			if (ep->pid != 0 && ep->pid == kp->kp_pid) {
304 				ep->kp = kp;
305 				break;
306 			}
307 		}
308 	}
309 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
310 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
311 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
312 	       ttywidth = 79;
313         else
314 	       ttywidth = ws.ws_col - 1;
315 	argwidth = ttywidth - WUSED;
316 	if (argwidth < 4)
317 		argwidth = 8;
318 	for (ep = ehead; ep != NULL; ep = ep->next) {
319 		if (ep->kp == NULL) {
320 			ep->args = "-";
321 			continue;
322 		}
323 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
324 		    ep->kp->kp_comm, MAXCOMLEN);
325 		if (ep->args == NULL)
326 			err(1, NULL);
327 	}
328 	/* sort by idle time */
329 	if (sortidle && ehead != NULL) {
330 		struct entry *from, *save;
331 
332 		from = ehead;
333 		ehead = NULL;
334 		while (from != NULL) {
335 			for (nextp = &ehead;
336 			    (*nextp) && from->idle >= (*nextp)->idle;
337 			    nextp = &(*nextp)->next)
338 				continue;
339 			save = from;
340 			from = from->next;
341 			save->next = *nextp;
342 			*nextp = save;
343 		}
344 	} else if (ehead != NULL) {
345 		struct entry *from = ehead, *save;
346 
347 		ehead = NULL;
348 		while (from != NULL) {
349 			for (nextp = &ehead;
350 			    (*nextp) && strcmp(from->line, (*nextp)->line) > 0;
351 			    nextp = &(*nextp)->next)
352 				continue;
353 			save = from;
354 			from = from->next;
355 			save->next = *nextp;
356 			*nextp = save;
357 		}
358 	}
359 
360 	if (!nflag) {
361 		if (gethostname(domain, sizeof(domain)) < 0 ||
362 		    (p = strchr(domain, '.')) == NULL)
363 			domain[0] = '\0';
364 		else {
365 			domain[sizeof(domain) - 1] = '\0';
366 			memmove(domain, p, strlen(p) + 1);
367 		}
368 	}
369 
370 	for (ep = ehead; ep != NULL; ep = ep->next) {
371 		char host_buf[UTX_HOSTSIZE + 1];
372 
373 		host_buf[UTX_HOSTSIZE] = '\0';
374 		strncpy(host_buf, ep->host, maxhost);
375 		p = *host_buf ? host_buf : "-";
376 		if ((x = strchr(p, ':')) != NULL)
377 			*x++ = '\0';
378 		if (!nflag && isdigit(*p) &&
379 		    (l = inet_addr(p)) != INADDR_NONE &&
380 		    (hp = gethostbyaddr(&l, sizeof(l), AF_INET))) {
381 			if (domain[0] != '\0') {
382 				p = hp->h_name;
383 				p += strlen(hp->h_name);
384 				p -= strlen(domain);
385 				if (p > hp->h_name &&
386 				    strcasecmp(p, domain) == 0)
387 					*p = '\0';
388 			}
389 			p = hp->h_name;
390 		}
391 		if (nflag && *p && strcmp(p, "-") &&
392 		    inet_addr(p) == INADDR_NONE) {
393 			hp = gethostbyname(p);
394 
395 			if (hp != NULL) {
396 				struct in_addr in;
397 
398 				memmove(&in, hp->h_addr, sizeof(in));
399 				p = inet_ntoa(in);
400 			}
401 		}
402 		if (x) {
403 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
404 			p = buf;
405 		}
406 		if (dflag) {
407 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
408 				char *ptr;
409 
410 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
411 				    dkp->kp_comm, MAXCOMLEN);
412 				if (ptr == NULL)
413 					ptr = "-";
414 				(void)printf("\t\t%-9d %s\n",
415 				    dkp->kp_pid, ptr);
416 			}
417 		}
418 		(void)printf("%-*.*s %-*.*s %-*.*s ",
419 		    maxname, maxname, ep->name,
420 		    maxline, maxline,
421 		    strncmp(ep->line, "tty", 3) &&
422 		    strncmp(ep->line, "cua", 3) ?
423 		    ep->line : ep->line + 3,
424 		    maxhost, maxhost, *p ? p : "-");
425 		then = (time_t)ep->tv.tv_sec;
426 		pr_attime(&then, &now);
427 		longidle = pr_idle(ep->idle);
428 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
429 	}
430 	(void)kvm_close(kd);
431 	exit(0);
432 }
433 
434 static void
435 pr_header(time_t *nowp, int nusers)
436 {
437 	struct timespec boot_ts;
438 	double avenrun[3];
439 	time_t uptime;
440 	int days, hrs, i, mins, secs;
441 	char buf[256];
442 
443 	/*
444 	 * Print time of day. (use "AM"/"PM" for all locales)
445 	 */
446 	(void)strftime_l(buf, sizeof(buf) - 1,
447 		       use_ampm	? "%l:%M%p" : "%k:%M",
448 		       localtime(nowp), NULL);
449 	buf[sizeof(buf) - 1] = '\0';
450 	(void)printf("%s ", buf);
451 
452 	/*
453 	 * Print how long system has been up.
454 	 *
455 	 * Use clock_gettime() rather than trying to calculate
456 	 * a realtime delta that would be subject to time and date
457 	 * changes.
458 	 */
459 	if (clock_gettime(CLOCK_UPTIME, &boot_ts) == 0) {
460 		uptime = boot_ts.tv_sec;
461 		if (uptime > 60)
462 			uptime += 30;
463 		days = uptime / 86400;
464 		uptime %= 86400;
465 		hrs = uptime / 3600;
466 		uptime %= 3600;
467 		mins = uptime / 60;
468 		secs = uptime % 60;
469 		(void)printf(" up");
470 		if (days > 0)
471 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
472 		if (hrs > 0 && mins > 0)
473 			(void)printf(" %2d:%02d,", hrs, mins);
474 		else if (hrs > 0)
475 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
476 		else if (mins > 0)
477 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
478 		else
479 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
480 	}
481 
482 	/* Print number of users logged in on system */
483 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
484 
485 	/*
486 	 * Print 1, 5, and 15 minute load averages.
487 	 */
488 	if (getloadavg(avenrun, NELEM(avenrun)) == -1)
489 		(void)printf(", no load average information available\n");
490 	else {
491 		(void)printf(", load averages:");
492 		for (i = 0; i < (int)NELEM(avenrun); i++) {
493 			if (use_comma && i > 0)
494 				(void)printf(",");
495 			(void)printf(" %.2f", avenrun[i]);
496 		}
497 		(void)printf("\n");
498 	}
499 }
500 
501 static struct stat *
502 ttystat(char *line, int sz)
503 {
504 	static struct stat sb;
505 	char ttybuf[MAXPATHLEN];
506 
507 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
508 	if (stat(ttybuf, &sb)) {
509 		warn("%s", ttybuf);
510 		return (NULL);
511 	}
512 	return (&sb);
513 }
514 
515 static void
516 usage(int wcmd)
517 {
518 	if (wcmd)
519 		(void)fprintf(stderr,
520 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
521 	else
522 		(void)fprintf(stderr, "usage: uptime\n");
523 	exit(1);
524 }
525 
526 static int
527 this_is_uptime(const char *s)
528 {
529 	const char *u;
530 
531 	if ((u = strrchr(s, '/')) != NULL)
532 		++u;
533 	else
534 		u = s;
535 	if (strcmp(u, "uptime") == 0)
536 		return (0);
537 	return (-1);
538 }
539 
540 static void
541 process(struct entry *ep)
542 {
543 	struct stat *stp;
544 	time_t touched;
545 	int max;
546 
547 	if ((max = strlen(ep->name)) > maxname)
548 		maxname = max;
549 	if ((max = strlen(ep->line)) > maxline)
550 		maxline = max;
551 	if ((max = strlen(ep->host)) > maxhost)
552 		maxhost = max;
553 
554 	ep->tdev = 0;
555 	ep->idle = (time_t)-1;
556 
557 	if (!(stp = ttystat(ep->line, maxline)))
558 		return;	/* corrupted record */
559 
560 	ep->tdev = stp->st_rdev;
561 #ifdef CPU_CONSDEV
562 	/*
563 	 * If this is the console device, attempt to ascertain
564 	 * the true console device dev_t.
565 	 */
566 	if (ep->tdev == 0) {
567 		int mib[2];
568 		size_t size;
569 
570 		mib[0] = CTL_MACHDEP;
571 		mib[1] = CPU_CONSDEV;
572 		size = sizeof(dev_t);
573 		(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
574 	}
575 #endif
576 
577 	touched = stp->st_atime;
578 	if (touched < ep->tv.tv_sec) {
579 		/* tty untouched since before login */
580 		touched = ep->tv.tv_sec;
581 	}
582 	if ((ep->idle = now - touched) < 0)
583 		ep->idle = 0;
584 }
585