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