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