xref: /netbsd-src/usr.bin/w/w.c (revision 3b01aba77a7a698587faaae455bbfe740923c1f5)
1 /*	$NetBSD: w.c,v 1.46 2001/02/19 23:03:52 cgd Exp $	*/
2 
3 /*-
4  * Copyright (c) 1980, 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
39 	The Regents of the University of California.  All rights reserved.\n");
40 #endif /* not lint */
41 
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)w.c	8.6 (Berkeley) 6/30/94";
45 #else
46 __RCSID("$NetBSD: w.c,v 1.46 2001/02/19 23:03:52 cgd Exp $");
47 #endif
48 #endif /* not lint */
49 
50 /*
51  * w - print system status (who and what)
52  *
53  * This program is similar to the systat command on Tenex/Tops 10/20
54  *
55  */
56 #include <sys/param.h>
57 #include <sys/types.h>
58 #include <sys/time.h>
59 #include <sys/stat.h>
60 #include <sys/sysctl.h>
61 #include <sys/proc.h>
62 #include <sys/user.h>
63 #include <sys/ioctl.h>
64 #include <sys/socket.h>
65 
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 
69 #include <ctype.h>
70 #include <err.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <kvm.h>
74 #include <limits.h>
75 #include <netdb.h>
76 #include <nlist.h>
77 #include <paths.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <time.h>
82 #include <tzfile.h>
83 #include <unistd.h>
84 #include <utmp.h>
85 #include <vis.h>
86 
87 #include "extern.h"
88 
89 #define	max(a,b)	(((a)>(b))?(a):(b))
90 
91 struct timeval	boottime;
92 struct utmp	utmp;
93 struct winsize	ws;
94 kvm_t	       *kd;
95 time_t		now;		/* the current time of day */
96 time_t		uptime;		/* time of last reboot & elapsed time since */
97 int		ttywidth;	/* width of tty */
98 int		argwidth;	/* width of tty left to print process args */
99 int		header = 1;	/* true if -h flag: don't print heading */
100 int		nflag;		/* true if -n flag: don't convert addrs */
101 int		sortidle;	/* sort bu idle time */
102 char	       *sel_user;	/* login of particular user selected */
103 char		domain[MAXHOSTNAMELEN + 1];
104 
105 /*
106  * One of these per active utmp entry.
107  */
108 struct	entry {
109 	struct	entry *next;
110 	struct	utmp utmp;
111 	dev_t	tdev;			/* dev_t of terminal */
112 	time_t	idle;			/* idle time of terminal in seconds */
113 	struct	kinfo_proc2 *kp;	/* `most interesting' proc */
114 #ifdef SUPPORT_FTPD_UTMP
115 	pid_t	ftpd_pid;		/* pid as extracted from ftpd's entry */
116 #endif
117 } *ep, *ehead = NULL, **nextp = &ehead;
118 
119 static void	 pr_args(struct kinfo_proc2 *);
120 static void	 pr_header(time_t *, int);
121 static struct stat *ttystat(char *, size_t);
122 static void	 usage(int);
123 int	main(int, char **);
124 
125 int
126 main(int argc, char **argv)
127 {
128 	struct kinfo_proc2 *kp;
129 	struct hostent *hp;
130 	struct stat *stp;
131 	FILE *ut;
132 	struct in_addr l;
133 	time_t touched;
134 	int ch, i, nentries, nusers, wcmd, lognamelen;
135 	char *memf, *nlistf, *p, *x;
136 	const char *progname;
137 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
138 
139 	/* Are we w(1) or uptime(1)? */
140 	progname = getprogname();
141 	if (*progname == '-')
142 		progname++;
143 	if (*progname == 'u') {
144 		wcmd = 0;
145 		p = "";
146 	} else {
147 		wcmd = 1;
148 		p = "hiflM:N:nsuw";
149 	}
150 
151 	memf = nlistf = NULL;
152 	while ((ch = getopt(argc, argv, p)) != -1)
153 		switch (ch) {
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 			break;
164 		case 'N':
165 			nlistf = optarg;
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 ((kd = kvm_openfiles(nlistf, memf, NULL,
181 	    memf == NULL ? KVM_NO_FILES : O_RDONLY, errbuf)) == NULL)
182 		errx(1, "%s", errbuf);
183 
184 	(void)time(&now);
185 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL && wcmd)
186 		err(1, "%s", _PATH_UTMP);
187 
188 	if (*argv)
189 		sel_user = *argv;
190 
191 	for (nusers = 0; ut && fread(&utmp, sizeof(utmp), 1, ut);) {
192 		if (utmp.ut_name[0] == '\0')
193 			continue;
194 		++nusers;
195 		if (wcmd == 0 || (sel_user &&
196 		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
197 			continue;
198 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
199 			err(1, NULL);
200 		*nextp = ep;
201 		nextp = &(ep->next);
202 		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
203 		if (!(stp = ttystat(ep->utmp.ut_line, UT_LINESIZE))) {
204 #ifdef SUPPORT_FTPD_UTMP
205 			/*
206 			 * Hack to recognize and correctly parse
207 			 * utmp entry made by ftpd. The "tty" used
208 			 * by ftpd is not a real tty, just identifier in
209 			 * form ftpPROCESS_ID. Pid parsed from the "tty name"
210 			 * is used later to match corresponding process.
211 			 */
212 			if (strncmp(ep->utmp.ut_line, "ftp", 3) == 0)
213 				ep->ftpd_pid =
214 					strtol(ep->utmp.ut_line + 3, NULL, 10);
215 #endif /* SUPPORT_FTPD_UTMP */
216 
217 			continue;
218 		}
219 		ep->tdev = stp->st_rdev;
220 		/*
221 		 * If this is the console device, attempt to ascertain
222 		 * the true console device dev_t.
223 		 */
224 		if (ep->tdev == 0) {
225 			int mib[2];
226 			size_t size;
227 
228 			mib[0] = CTL_KERN;
229 			mib[1] = KERN_CONSDEV;
230 			size = sizeof(dev_t);
231 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
232 		}
233 
234 		touched = stp->st_atime;
235 		if (touched < ep->utmp.ut_time) {
236 				/* tty untouched since before login */
237 				touched = ep->utmp.ut_time;
238 			}
239 	if ((ep->idle = now - touched) < 0)
240 			ep->idle = 0;
241 	}
242 	if (ut)
243 		(void)fclose(ut);
244 	else
245 		nusers = 1;
246 
247 	if (header || wcmd == 0) {
248 		pr_header(&now, nusers);
249 		if (wcmd == 0)
250 			exit (0);
251 	}
252 
253 	if ((kp = kvm_getproc2(kd, KERN_PROC_ALL, 0,
254 	    sizeof(struct kinfo_proc2), &nentries)) == NULL)
255 		errx(1, "%s", kvm_geterr(kd));
256 
257 	/* Include trailing space because TTY header starts one column early. */
258 	lognamelen = sizeof("USER ") - 1 /* NUL */;
259 	for (i = 0; i < nentries; i++, kp++) {
260 
261 		if (kp->p_stat == SIDL || kp->p_stat == SZOMB)
262 			continue;
263 
264 		for (ep = ehead; ep != NULL; ep = ep->next) {
265 			if (ep->tdev == kp->p_tdev
266 				&& kp->p__pgid == kp->p_tpgid) {
267 				/*
268 				 * Proc is in foreground of this terminal
269 				 */
270 				if (proc_compare(ep->kp, kp)) {
271 					ep->kp = kp;
272 					lognamelen = max(lognamelen,
273 					    strlen(kp->p_login));
274 				}
275 				break;
276 			}
277 #ifdef SUPPORT_FTPD_UTMP
278 			/*
279 			 * Hack to match process to ftp utmp entry.
280 			 */
281 			else if (ep->tdev == 0 && kp->p_tdev == NODEV
282 				 && ep->ftpd_pid == kp->p_pid) {
283 				ep->kp = kp;
284 				lognamelen = max(lognamelen,
285 					    strlen(kp->p_login));
286 			}
287 #endif /* SUPPORT_FTPD_UTMP */
288 		}
289 	}
290 
291 	argwidth = printf("%-*sTTY %-*s %*s  IDLE WHAT\n",
292 	    lognamelen, "USER", UT_HOSTSIZE, "FROM",
293 	    7 /* "dddhhXm" */, "LOGIN@");
294 	argwidth -= sizeof("WHAT\n") - 1 /* NUL */;
295 
296 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
297 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
298 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
299 	       ttywidth = 79;
300         else
301 	       ttywidth = ws.ws_col - 1;
302 	argwidth = ttywidth - argwidth;
303 	if (argwidth < 4)
304 		argwidth = 8;
305 	/* sort by idle time */
306 	if (sortidle && ehead != NULL) {
307 		struct entry *from = ehead, *save;
308 
309 		ehead = NULL;
310 		while (from != NULL) {
311 			for (nextp = &ehead;
312 			    (*nextp) && from->idle >= (*nextp)->idle;
313 			    nextp = &(*nextp)->next)
314 				continue;
315 			save = from;
316 			from = from->next;
317 			save->next = *nextp;
318 			*nextp = save;
319 		}
320 	}
321 
322 	if (!nflag) {
323 		int	rv;
324 
325 		rv = gethostname(domain, sizeof(domain));
326 		domain[sizeof(domain) - 1] = '\0';
327 		if (rv < 0 || (p = strchr(domain, '.')) == 0)
328 			domain[0] = '\0';
329 		else
330 			memmove(domain, p, strlen(p) + 1);
331 	}
332 
333 	for (ep = ehead; ep != NULL; ep = ep->next) {
334 		char host_buf[UT_HOSTSIZE + 1];
335 
336 		host_buf[UT_HOSTSIZE] = '\0';
337 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
338 		p = *host_buf ? host_buf : "-";
339 
340 		for (x = p; x < p + UT_HOSTSIZE; x++)
341 			if (*x == '\0' || *x == ':')
342 				break;
343 		if (x == p + UT_HOSTSIZE || *x != ':')
344 			x = NULL;
345 		else
346 			*x++ = '\0';
347 
348 		if (!nflag && inet_aton(p, &l) &&
349 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
350 			if (domain[0] != '\0') {
351 				p = hp->h_name;
352 				p += strlen(hp->h_name);
353 				p -= strlen(domain);
354 				if (p > hp->h_name && strcasecmp(p, domain) == 0)
355 					*p = '\0';
356 			}
357 			p = hp->h_name;
358 		}
359 		if (x) {
360 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
361 			p = buf;
362 		}
363 		if (ep->kp == NULL) {
364 		    warnx("Stale utmp entry: %.*s %.*s %.*s",
365 			UT_NAMESIZE, ep->utmp.ut_name,
366 			UT_LINESIZE, ep->utmp.ut_line,
367 			UT_HOSTSIZE, ep->utmp.ut_host);
368 		    continue;
369 		}
370 		(void)printf("%-*s %-2.2s %-*.*s ",
371 		    lognamelen, ep->kp->p_login,
372 		    (strncmp(ep->utmp.ut_line, "tty", 3) &&
373 		    strncmp(ep->utmp.ut_line, "dty", 3)) ?
374 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
375 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
376 		pr_attime(&ep->utmp.ut_time, &now);
377 		pr_idle(ep->idle);
378 		pr_args(ep->kp);
379 		(void)printf("\n");
380 	}
381 	exit(0);
382 }
383 
384 static void
385 pr_args(struct kinfo_proc2 *kp)
386 {
387 	char **argv;
388 	int left;
389 
390 	if (kp == 0)
391 		goto nothing;
392 	left = argwidth;
393 	argv = kvm_getargv2(kd, kp, argwidth);
394 	if (argv == 0)
395 		goto nothing;
396 	while (*argv) {
397 		fmt_puts(*argv, &left);
398 		argv++;
399 		fmt_putc(' ', &left);
400 	}
401 	return;
402 nothing:
403 	putchar('-');
404 }
405 
406 static void
407 pr_header(time_t *nowp, int nusers)
408 {
409 	double avenrun[3];
410 	time_t uptime;
411 	int days, hrs, i, mins;
412 	int mib[2];
413 	size_t size;
414 	char buf[256];
415 
416 	/*
417 	 * Print time of day.
418 	 *
419 	 * SCCS forces the string manipulation below, as it replaces
420 	 * %, M, and % in a character string with the file name.
421 	 */
422 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
423 	buf[sizeof(buf) - 1] = '\0';
424 	(void)printf("%s ", buf);
425 
426 	/*
427 	 * Print how long system has been up.
428 	 * (Found by looking getting "boottime" from the kernel)
429 	 */
430 	mib[0] = CTL_KERN;
431 	mib[1] = KERN_BOOTTIME;
432 	size = sizeof(boottime);
433 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
434 	    boottime.tv_sec != 0) {
435 		uptime = now - boottime.tv_sec;
436 		uptime += 30;
437 		if (uptime > SECSPERMIN) {
438 			days = uptime / SECSPERDAY;
439 			uptime %= SECSPERDAY;
440 			hrs = uptime / SECSPERHOUR;
441 			uptime %= SECSPERHOUR;
442 			mins = uptime / SECSPERMIN;
443 			(void)printf(" up");
444 			if (days > 0)
445 				(void)printf(" %d day%s,", days,
446 				    days > 1 ? "s" : "");
447 			if (hrs > 0 && mins > 0)
448 				(void)printf(" %2d:%02d,", hrs, mins);
449 			else {
450 				if (hrs > 0)
451 					(void)printf(" %d hr%s,",
452 					    hrs, hrs > 1 ? "s" : "");
453 				if (mins > 0)
454 					(void)printf(" %d min%s,",
455 					    mins, mins > 1 ? "s" : "");
456 			}
457 		}
458 	}
459 
460 	/* Print number of users logged in to system */
461 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
462 
463 	/*
464 	 * Print 1, 5, and 15 minute load averages.
465 	 */
466 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
467 		(void)printf(", no load average information available\n");
468 	else {
469 		(void)printf(", load averages:");
470 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
471 			if (i > 0)
472 				(void)printf(",");
473 			(void)printf(" %.2f", avenrun[i]);
474 		}
475 		(void)printf("\n");
476 	}
477 }
478 
479 static struct stat *
480 ttystat(char *line, size_t sz)
481 {
482 	static struct stat sb;
483 	char ttybuf[MAXPATHLEN];
484 
485 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, (int) sz, line);
486 	if (stat(ttybuf, &sb))
487 		return (NULL);
488 	return (&sb);
489 }
490 
491 static void
492 usage(int wcmd)
493 {
494 	if (wcmd)
495 		(void)fprintf(stderr,
496 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
497 	else
498 		(void)fprintf(stderr, "uptime\n");
499 	exit(1);
500 }
501