xref: /netbsd/usr.bin/w/w.c (revision bf9ec67e)
1 /*	$NetBSD: w.c,v 1.47 2001/11/05 03:35:49 enami 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.47 2001/11/05 03:35:49 enami 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 &&
355 				    strcasecmp(p, domain) == 0)
356 					*p = '\0';
357 			}
358 			p = hp->h_name;
359 		}
360 		if (x) {
361 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
362 			p = buf;
363 		}
364 		if (ep->kp == NULL) {
365 			warnx("Stale utmp entry: %.*s %.*s %.*s",
366 			    UT_NAMESIZE, ep->utmp.ut_name,
367 			    UT_LINESIZE, ep->utmp.ut_line,
368 			    UT_HOSTSIZE, ep->utmp.ut_host);
369 			continue;
370 		}
371 		(void)printf("%-*s %-2.2s %-*.*s ",
372 		    lognamelen, ep->kp->p_login,
373 		    (strncmp(ep->utmp.ut_line, "tty", 3) &&
374 		    strncmp(ep->utmp.ut_line, "dty", 3)) ?
375 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
376 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
377 		pr_attime(&ep->utmp.ut_time, &now);
378 		pr_idle(ep->idle);
379 		pr_args(ep->kp);
380 		(void)printf("\n");
381 	}
382 	exit(0);
383 }
384 
385 static void
386 pr_args(struct kinfo_proc2 *kp)
387 {
388 	char **argv;
389 	int left;
390 
391 	if (kp == 0)
392 		goto nothing;
393 	left = argwidth;
394 	argv = kvm_getargv2(kd, kp, argwidth);
395 	if (argv == 0)
396 		goto nothing;
397 	while (*argv) {
398 		fmt_puts(*argv, &left);
399 		argv++;
400 		fmt_putc(' ', &left);
401 	}
402 	return;
403 nothing:
404 	putchar('-');
405 }
406 
407 static void
408 pr_header(time_t *nowp, int nusers)
409 {
410 	double avenrun[3];
411 	time_t uptime;
412 	int days, hrs, i, mins;
413 	int mib[2];
414 	size_t size;
415 	char buf[256];
416 
417 	/*
418 	 * Print time of day.
419 	 *
420 	 * SCCS forces the string manipulation below, as it replaces
421 	 * %, M, and % in a character string with the file name.
422 	 */
423 	(void)strftime(buf, sizeof(buf), "%l:%" "M%p", localtime(nowp));
424 	buf[sizeof(buf) - 1] = '\0';
425 	(void)printf("%s ", buf);
426 
427 	/*
428 	 * Print how long system has been up.
429 	 * (Found by looking getting "boottime" from the kernel)
430 	 */
431 	mib[0] = CTL_KERN;
432 	mib[1] = KERN_BOOTTIME;
433 	size = sizeof(boottime);
434 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
435 	    boottime.tv_sec != 0) {
436 		uptime = now - boottime.tv_sec;
437 		uptime += 30;
438 		if (uptime > SECSPERMIN) {
439 			days = uptime / SECSPERDAY;
440 			uptime %= SECSPERDAY;
441 			hrs = uptime / SECSPERHOUR;
442 			uptime %= SECSPERHOUR;
443 			mins = uptime / SECSPERMIN;
444 			(void)printf(" up");
445 			if (days > 0)
446 				(void)printf(" %d day%s,", days,
447 				    days > 1 ? "s" : "");
448 			if (hrs > 0 && mins > 0)
449 				(void)printf(" %2d:%02d,", hrs, mins);
450 			else {
451 				if (hrs > 0)
452 					(void)printf(" %d hr%s,",
453 					    hrs, hrs > 1 ? "s" : "");
454 				if (mins > 0)
455 					(void)printf(" %d min%s,",
456 					    mins, mins > 1 ? "s" : "");
457 			}
458 		}
459 	}
460 
461 	/* Print number of users logged in to system */
462 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
463 
464 	/*
465 	 * Print 1, 5, and 15 minute load averages.
466 	 */
467 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
468 		(void)printf(", no load average information available\n");
469 	else {
470 		(void)printf(", load averages:");
471 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
472 			if (i > 0)
473 				(void)printf(",");
474 			(void)printf(" %.2f", avenrun[i]);
475 		}
476 		(void)printf("\n");
477 	}
478 }
479 
480 static struct stat *
481 ttystat(char *line, size_t sz)
482 {
483 	static struct stat sb;
484 	char ttybuf[MAXPATHLEN];
485 
486 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, (int) sz,
487 	    line);
488 	if (stat(ttybuf, &sb))
489 		return (NULL);
490 	return (&sb);
491 }
492 
493 static void
494 usage(int wcmd)
495 {
496 
497 	if (wcmd)
498 		(void)fprintf(stderr,
499 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
500 	else
501 		(void)fprintf(stderr, "uptime\n");
502 	exit(1);
503 }
504