xref: /dragonfly/usr.bin/w/w.c (revision 1d1731fa)
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  * @(#) Copyright (c) 1980, 1991, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)w.c	8.4 (Berkeley) 4/16/94
35  * $FreeBSD: src/usr.bin/w/w.c,v 1.38.2.6 2002/03/12 19:51:51 phantom Exp $
36  * $DragonFly: src/usr.bin/w/w.c,v 1.4 2003/10/04 20:36:54 hmp Exp $
37  */
38 
39 /*
40  * w - print system status (who and what)
41  *
42  * This program is similar to the systat command on Tenex/Tops 10/20
43  *
44  */
45 #include <sys/param.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/sysctl.h>
49 #include <sys/proc.h>
50 #include <sys/user.h>
51 #include <sys/ioctl.h>
52 #include <sys/socket.h>
53 #include <sys/tty.h>
54 
55 #include <machine/cpu.h>
56 #include <netinet/in.h>
57 #include <arpa/inet.h>
58 
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <kvm.h>
64 #include <limits.h>
65 #include <langinfo.h>
66 #include <locale.h>
67 #include <netdb.h>
68 #include <nlist.h>
69 #include <paths.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74 #include <utmp.h>
75 #include <vis.h>
76 
77 #include <arpa/nameser.h>
78 #include <resolv.h>
79 
80 #include "extern.h"
81 
82 struct timeval	boottime;
83 struct utmp	utmp;
84 struct winsize	ws;
85 kvm_t	       *kd;
86 time_t		now;		/* the current time of day */
87 time_t		uptime;		/* time of last reboot & elapsed time since */
88 int		ttywidth;	/* width of tty */
89 int		argwidth;	/* width of tty */
90 int		header = 1;	/* true if -h flag: don't print heading */
91 int		nflag;		/* true if -n flag: don't convert addrs */
92 int		dflag;		/* true if -d flag: output debug info */
93 int		sortidle;	/* sort by idle time */
94 int		use_ampm;	/* use AM/PM time */
95 int             use_comma;      /* use comma as floats separator */
96 char	      **sel_users;	/* login array of particular users selected */
97 char		domain[MAXHOSTNAMELEN];
98 
99 /*
100  * One of these per active utmp entry.
101  */
102 struct	entry {
103 	struct	entry *next;
104 	struct	utmp utmp;
105 	dev_t	tdev;			/* dev_t of terminal */
106 	time_t	idle;			/* idle time of terminal in seconds */
107 	struct	kinfo_proc *kp;		/* `most interesting' proc */
108 	char	*args;			/* arg list of interesting process */
109 	struct	kinfo_proc *dkp;	/* debug option proc list */
110 } *ep, *ehead = NULL, **nextp = &ehead;
111 
112 #define debugproc(p) *((struct kinfo_proc **)&(p)->kp_eproc.e_spare[0])
113 
114 static void		 pr_header(time_t *, int);
115 static struct stat	*ttystat(char *, int);
116 static void		 usage(int);
117 static int		 this_is_uptime(const char *s);
118 
119 char *fmt_argv(char **, char *, int);	/* ../../bin/ps/fmt.c */
120 
121 int
122 main(int argc, char **argv)
123 {
124 	struct kinfo_proc *kp;
125 	struct kinfo_proc *dkp;
126 	struct hostent *hp;
127 	struct stat *stp;
128 	FILE *ut;
129 	in_addr_t l;
130 	time_t touched;
131 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
132 	char *memf, *nlistf, *p, *x;
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 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
200 		err(1, "%s", _PATH_UTMP);
201 
202 	if (*argv)
203 		sel_users = argv;
204 
205 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
206 		if (utmp.ut_name[0] == '\0')
207 			continue;
208 		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
209 			continue;	/* corrupted record */
210 		++nusers;
211 		if (wcmd == 0)
212 			continue;
213 		if (sel_users) {
214 			int usermatch;
215 			char **user;
216 
217 			usermatch = 0;
218 			for (user = sel_users; !usermatch && *user; user++)
219 				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
220 					usermatch = 1;
221 			if (!usermatch)
222 				continue;
223 		}
224 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
225 			errx(1, "calloc");
226 		*nextp = ep;
227 		nextp = &ep->next;
228 		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
229 		ep->tdev = stp->st_rdev;
230 #ifdef CPU_CONSDEV
231 		/*
232 		 * If this is the console device, attempt to ascertain
233 		 * the true console device dev_t.
234 		 */
235 		if (ep->tdev == 0) {
236 			int mib[2];
237 			size_t size;
238 
239 			mib[0] = CTL_MACHDEP;
240 			mib[1] = CPU_CONSDEV;
241 			size = sizeof(dev_t);
242 			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
243 		}
244 #endif
245 		touched = stp->st_atime;
246 		if (touched < ep->utmp.ut_time) {
247 			/* tty untouched since before login */
248 			touched = ep->utmp.ut_time;
249 		}
250 		if ((ep->idle = now - touched) < 0)
251 			ep->idle = 0;
252 	}
253 	(void)fclose(ut);
254 
255 	if (header || wcmd == 0) {
256 		pr_header(&now, nusers);
257 		if (wcmd == 0) {
258 			(void)kvm_close(kd);
259 			exit(0);
260 		}
261 
262 #define HEADER_USER		"USER"
263 #define HEADER_TTY		"TTY"
264 #define HEADER_FROM		"FROM"
265 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
266 #define HEADER_WHAT		"WHAT\n"
267 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
268 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
269 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
270 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
271 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
272 				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
273 				HEADER_LOGIN_IDLE HEADER_WHAT);
274 	}
275 
276 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
277 		err(1, "%s", kvm_geterr(kd));
278 	for (i = 0; i < nentries; i++, kp++) {
279 		struct proc *pr = &kp->kp_proc;
280 		struct eproc *e;
281 
282 		if (pr->p_stat == SIDL || pr->p_stat == SZOMB)
283 			continue;
284 		e = &kp->kp_eproc;
285 		for (ep = ehead; ep != NULL; ep = ep->next) {
286 			if (ep->tdev == e->e_tdev) {
287 				/*
288 				 * proc is associated with this terminal
289 				 */
290 				if (ep->kp == NULL && e->e_pgid == e->e_tpgid) {
291 					/*
292 					 * Proc is 'most interesting'
293 					 */
294 					if (proc_compare(&ep->kp->kp_proc, pr))
295 						ep->kp = kp;
296 				}
297 				/*
298 				 * Proc debug option info; add to debug
299 				 * list using kinfo_proc kp_eproc.e_spare
300 				 * as next pointer; ptr to ptr avoids the
301 				 * ptr = long assumption.
302 				 */
303 				dkp = ep->dkp;
304 				ep->dkp = kp;
305 				debugproc(kp) = dkp;
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_thread.td_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 	}
345 
346 	if (!nflag) {
347 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
348 		    (p = strchr(domain, '.')) == NULL)
349 			domain[0] = '\0';
350 		else {
351 			domain[sizeof(domain) - 1] = '\0';
352 			memmove(domain, p, strlen(p) + 1);
353 		}
354 	}
355 
356 	for (ep = ehead; ep != NULL; ep = ep->next) {
357 		char host_buf[UT_HOSTSIZE + 1];
358 
359 		host_buf[UT_HOSTSIZE] = '\0';
360 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
361 		p = *host_buf ? host_buf : "-";
362 		if ((x = strchr(p, ':')) != NULL)
363 			*x++ = '\0';
364 		if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 &&
365 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
366 			if (domain[0] != '\0') {
367 				p = hp->h_name;
368 				p += strlen(hp->h_name);
369 				p -= strlen(domain);
370 				if (p > hp->h_name &&
371 				    strcasecmp(p, domain) == 0)
372 					*p = '\0';
373 			}
374 			p = hp->h_name;
375 		}
376 		if (nflag && *p && strcmp(p, "-") &&
377 		    inet_addr(p) == INADDR_NONE) {
378 			hp = gethostbyname(p);
379 
380 			if (hp != NULL) {
381 				struct in_addr in;
382 
383 				memmove(&in, hp->h_addr, sizeof(in));
384 				p = inet_ntoa(in);
385 			}
386 		}
387 		if (x) {
388 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
389 			p = buf;
390 		}
391 		if (dflag) {
392 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
393 				char *ptr;
394 
395 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
396 				    dkp->kp_thread.td_comm, MAXCOMLEN);
397 				if (ptr == NULL)
398 					ptr = "-";
399 				(void)printf("\t\t%-9d %s\n",
400 				    dkp->kp_proc.p_pid, ptr);
401 			}
402 		}
403 		(void)printf("%-*.*s %-*.*s %-*.*s ",
404 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
405 		    UT_LINESIZE, UT_LINESIZE,
406 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
407 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
408 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
409 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
410 		pr_attime(&ep->utmp.ut_time, &now);
411 		longidle = pr_idle(ep->idle);
412 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
413 	}
414 	(void)kvm_close(kd);
415 	exit(0);
416 }
417 
418 static void
419 pr_header(time_t *nowp, int nusers)
420 {
421 	double avenrun[3];
422 	time_t uptime;
423 	int days, hrs, i, mins, secs;
424 	int mib[2];
425 	size_t size;
426 	char buf[256];
427 
428 	/*
429 	 * Print time of day.
430 	 */
431 	(void)strftime(buf, sizeof(buf)	- 1,
432 		       use_ampm	? "%l:%M%p" : "%k:%M", localtime(nowp));
433 	buf[sizeof(buf) - 1] = '\0';
434 	(void)printf("%s ", buf);
435 
436 	/*
437 	 * Print how long system has been up.
438 	 * (Found by looking getting "boottime" from the kernel)
439 	 */
440 	mib[0] = CTL_KERN;
441 	mib[1] = KERN_BOOTTIME;
442 	size = sizeof(boottime);
443 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
444 	    boottime.tv_sec != 0) {
445 		uptime = now - boottime.tv_sec;
446 		if (uptime > 60)
447 			uptime += 30;
448 		days = uptime / 86400;
449 		uptime %= 86400;
450 		hrs = uptime / 3600;
451 		uptime %= 3600;
452 		mins = uptime / 60;
453 		secs = uptime % 60;
454 		(void)printf(" up");
455 		if (days > 0)
456 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
457 		if (hrs > 0 && mins > 0)
458 			(void)printf(" %2d:%02d,", hrs, mins);
459 		else if (hrs > 0)
460 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
461 		else if (mins > 0)
462 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
463 		else
464 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
465 	}
466 
467 	/* Print number of users logged in to system */
468 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
469 
470 	/*
471 	 * Print 1, 5, and 15 minute load averages.
472 	 */
473 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
474 		(void)printf(", no load average information available\n");
475 	else {
476 		(void)printf(", load averages:");
477 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
478 			if (use_comma && i > 0)
479 				(void)printf(",");
480 			(void)printf(" %.2f", avenrun[i]);
481 		}
482 		(void)printf("\n");
483 	}
484 }
485 
486 static struct stat *
487 ttystat(char *line, int sz)
488 {
489 	static struct stat sb;
490 	char ttybuf[MAXPATHLEN];
491 
492 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
493 	if (stat(ttybuf, &sb)) {
494 		warn("%s", ttybuf);
495 		return (NULL);
496 	}
497 	return (&sb);
498 }
499 
500 static void
501 usage(int wcmd)
502 {
503 	if (wcmd)
504 		(void)fprintf(stderr,
505 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
506 	else
507 		(void)fprintf(stderr, "usage: uptime\n");
508 	exit(1);
509 }
510 
511 static int
512 this_is_uptime(const char *s)
513 {
514 	const char *u;
515 
516 	if ((u = strrchr(s, '/')) != NULL)
517 		++u;
518 	else
519 		u = s;
520 	if (strcmp(u, "uptime") == 0)
521 		return (0);
522 	return (-1);
523 }
524