xref: /openbsd-src/usr.bin/w/w.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
1 /*	$OpenBSD: w.c,v 1.39 2003/06/03 02:56:22 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.39 2003/06/03 02:56:22 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 time_t		uptime;		/* time of last reboot & elapsed time since */
91 int		ttywidth;	/* width of tty */
92 int		argwidth;	/* width of tty */
93 int		header = 1;	/* true if -h flag: don't print heading */
94 int		nflag = 1;	/* true if -n flag: don't convert addrs */
95 int		sortidle;	/* sort bu idle time */
96 char	       *sel_user;	/* login of particular user selected */
97 char		domain[MAXHOSTNAMELEN];
98 
99 #define	NAME_WIDTH	8
100 #define HOST_WIDTH	16
101 
102 /*
103  * One of these per active utmp entry.
104  */
105 struct	entry {
106 	struct	entry *next;
107 	struct	utmp utmp;
108 	dev_t	tdev;		/* dev_t of terminal */
109 	time_t	idle;		/* idle time of terminal in seconds */
110 	struct	kinfo_proc *kp;	/* `most interesting' proc */
111 } *ep, *ehead = NULL, **nextp = &ehead;
112 
113 static void	 pr_args(struct kinfo_proc *);
114 static void	 pr_header(time_t *, int);
115 static struct stat
116 		*ttystat(char *);
117 static void	 usage(int);
118 
119 int
120 main(int argc, char *argv[])
121 {
122 	extern char *__progname;
123 	struct kinfo_proc *kp;
124 	struct hostent *hp;
125 	struct stat *stp;
126 	FILE *ut;
127 	struct in_addr addr;
128 	int ch, i, nentries, nusers, wcmd;
129 	char *memf, *nlistf, *p, *x;
130 	char buf[MAXHOSTNAMELEN], errbuf[_POSIX2_LINE_MAX];
131 
132 	/* Are we w(1) or uptime(1)? */
133 	p = __progname;
134 	if (*p == '-')
135 		p++;
136 	if (p[0] == 'w' && p[1] == '\0') {
137 		wcmd = 1;
138 		p = "hiflM:N:asuw";
139 	} else if (!strcmp(p, "uptime")) {
140 		wcmd = 0;
141 		p = "M:N:";
142 	} else
143 		errx(1,
144 		 "this program should be invoked only as \"w\" or \"uptime\"");
145 
146 	memf = nlistf = NULL;
147 	while ((ch = getopt(argc, argv, p)) != -1)
148 		switch (ch) {
149 		case 'h':
150 			header = 0;
151 			break;
152 		case 'i':
153 			sortidle = 1;
154 			break;
155 		case 'M':
156 			header = 0;
157 			memf = optarg;
158 			break;
159 		case 'N':
160 			nlistf = optarg;
161 			break;
162 		case 'a':
163 			nflag = 0;
164 			break;
165 		case 'f': case 'l': case 's': case 'u': case 'w':
166 			warnx("[-flsuw] no longer supported");
167 			/* FALLTHROUGH */
168 		case '?':
169 		default:
170 			usage(wcmd);
171 		}
172 	argc -= optind;
173 	argv += optind;
174 
175 	if (nlistf == NULL && memf == NULL) {
176 		if ((kd = kvm_openfiles(nlistf, memf, NULL, KVM_NO_FILES,
177 		    errbuf)) == NULL)
178 			errx(1, "%s", errbuf);
179 	} else {
180 		if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
181 			errx(1, "%s", errbuf);
182 	}
183 
184 	(void)time(&now);
185 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
186 		err(1, "%s", _PATH_UTMP);
187 
188 	if (*argv)
189 		sel_user = *argv;
190 
191 	for (nusers = 0; 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(*ep))) == NULL)
199 			err(1, NULL);
200 		*nextp = ep;
201 		nextp = &(ep->next);
202 		memcpy(&(ep->utmp), &utmp, sizeof(utmp));
203 		if (!(stp = ttystat(ep->utmp.ut_line)))
204 			continue;
205 		ep->tdev = stp->st_rdev;
206 #ifdef CPU_CONSDEV
207 		/*
208 		 * If this is the console device, attempt to ascertain
209 		 * the true console device dev_t.
210 		 */
211 		if (ep->tdev == 0) {
212 			int mib[2];
213 			size_t size;
214 
215 			mib[0] = CTL_MACHDEP;
216 			mib[1] = CPU_CONSDEV;
217 			size = sizeof(dev_t);
218 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
219 		}
220 #endif
221 		if ((ep->idle = now - stp->st_atime) < 0)
222 			ep->idle = 0;
223 	}
224 	(void)fclose(ut);
225 
226 	if (header || wcmd == 0) {
227 		pr_header(&now, nusers);
228 		if (wcmd == 0)
229 			exit (0);
230 	}
231 
232 #define HEADER	"USER    TTY FROM              LOGIN@  IDLE WHAT"
233 #define WUSED	(sizeof(HEADER) - sizeof("WHAT"))
234 	(void)puts(HEADER);
235 
236 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
237 		errx(1, "%s", kvm_geterr(kd));
238 	for (i = 0; i < nentries; i++, kp++) {
239 		struct proc *p = &kp->kp_proc;
240 		struct eproc *e;
241 
242 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
243 			continue;
244 		e = &kp->kp_eproc;
245 		for (ep = ehead; ep != NULL; ep = ep->next) {
246 			/* ftp is a special case. */
247 			if (strncmp(ep->utmp.ut_line, "ftp", 3) == 0) {
248 				char pidstr[UT_LINESIZE-2];
249 				pid_t fp;
250 
251 				(void)strncpy(pidstr, &ep->utmp.ut_line[3],
252 				    sizeof(pidstr) - 1);
253 				pidstr[sizeof(pidstr) - 1] = '\0';
254 				fp = (pid_t)strtol(pidstr, NULL, 10);
255 				if (p->p_pid == fp) {
256 					ep->kp = kp;
257 					break;
258 				}
259 			} else if (ep->tdev == e->e_tdev &&
260 			    e->e_pgid == e->e_tpgid) {
261 				/*
262 				 * Proc is in foreground of this terminal
263 				 */
264 				if (proc_compare(&ep->kp->kp_proc, p))
265 					ep->kp = kp;
266 				break;
267 			}
268 		}
269 	}
270 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
271 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
272 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
273 	       ttywidth = 79;
274         else
275 	       ttywidth = ws.ws_col - 1;
276 	argwidth = ttywidth - WUSED;
277 	if (argwidth < 4)
278 		argwidth = 8;
279 	/* sort by idle time */
280 	if (sortidle && ehead != NULL) {
281 		struct entry *from = ehead, *save;
282 
283 		ehead = NULL;
284 		while (from != NULL) {
285 			for (nextp = &ehead;
286 			    (*nextp) && from->idle >= (*nextp)->idle;
287 			    nextp = &(*nextp)->next)
288 				continue;
289 			save = from;
290 			from = from->next;
291 			save->next = *nextp;
292 			*nextp = save;
293 		}
294 	}
295 
296 	if (!nflag) {
297 		if (gethostname(domain, sizeof(domain)) < 0 ||
298 		    (p = strchr(domain, '.')) == 0)
299 			domain[0] = '\0';
300 		else {
301 			domain[sizeof(domain) - 1] = '\0';
302 			memmove(domain, p, strlen(p) + 1);
303 		}
304 	}
305 
306 	for (ep = ehead; ep != NULL; ep = ep->next) {
307 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
308 		for (x = NULL, i = 0; p[i] != '\0' && i < UT_HOSTSIZE; i++)
309 			if (p[i] == ':') {
310 				x = &p[i];
311 				*x++ = '\0';
312 				break;
313 			}
314 		if (!nflag && inet_aton(p, &addr) &&
315 		    (hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET))) {
316 			if (domain[0] != '\0') {
317 				p = hp->h_name;
318 				p += strlen(hp->h_name);
319 				p -= strlen(domain);
320 				if (p > hp->h_name &&
321 				    strcasecmp(p, domain) == 0)
322 					*p = '\0';
323 			}
324 			p = hp->h_name;
325 		}
326 		if (x) {
327 			(void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
328 			    (int)(ep->utmp.ut_host + UT_HOSTSIZE - x), x);
329 			p = buf;
330 		}
331 		(void)printf("%-*.*s %-2.2s %-*.*s ",
332 		    NAME_WIDTH, UT_NAMESIZE, ep->utmp.ut_name,
333 		    strncmp(ep->utmp.ut_line, "tty", 3) ?
334 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
335 		    HOST_WIDTH, HOST_WIDTH, *p ? p : "-");
336 		pr_attime(&ep->utmp.ut_time, &now);
337 		pr_idle(ep->idle);
338 		pr_args(ep->kp);
339 		printf("\n");
340 	}
341 	exit(0);
342 }
343 
344 static void
345 pr_args(struct kinfo_proc *kp)
346 {
347 	char **argv, *str;
348 	int left;
349 
350 	if (kp == NULL)
351 		goto nothing;
352 	left = argwidth;
353 	argv = kvm_getargv(kd, kp, argwidth+60);  /* +60 for ftpd snip */
354 	if (argv == NULL)
355 		goto nothing;
356 
357 	if (*argv == NULL || **argv == '\0') {
358 		/* Process has zeroed argv[0], display executable name. */
359 		fmt_putc('(', &left);
360 		fmt_puts(kp->kp_proc.p_comm, &left);
361 		fmt_putc(')', &left);
362 	}
363 	while (*argv) {
364 		/* ftp is a special case... */
365 		if (strncmp(*argv, "ftpd:", 5) == 0) {
366 			str = strrchr(*argv, ':');
367 			if (str != (char *)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 	 * SCCS forces the string manipulation below, as it replaces
397 	 * %, M, and % in a character string with the file name.
398 	 */
399 	(void)strftime(buf, sizeof(buf) - 1,
400 	    __CONCAT("%l:%","M%p"), localtime(nowp));
401 	buf[sizeof(buf) - 1] = '\0';
402 	(void)printf("%s ", buf);
403 
404 	/*
405 	 * Print how long system has been up.
406 	 * (Found by looking getting "boottime" from the kernel)
407 	 */
408 	mib[0] = CTL_KERN;
409 	mib[1] = KERN_BOOTTIME;
410 	size = sizeof(boottime);
411 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) {
412 		uptime = now - boottime.tv_sec;
413 		if (uptime > 59) {
414 			uptime += 30;
415 			days = uptime / SECSPERDAY;
416 			uptime %= SECSPERDAY;
417 			hrs = uptime / SECSPERHOUR;
418 			uptime %= SECSPERHOUR;
419 			mins = uptime / SECSPERMIN;
420 			(void)printf(" up");
421 			if (days > 0)
422 				(void)printf(" %d day%s,", days,
423 				    days > 1 ? "s" : "");
424 			if (hrs > 0 && mins > 0)
425 				(void)printf(" %2d:%02d,", hrs, mins);
426 			else {
427 				if (hrs > 0)
428 					(void)printf(" %d hr%s,",
429 					    hrs, hrs > 1 ? "s" : "");
430 				if (mins > 0 || (days == 0 && hrs == 0))
431 					(void)printf(" %d min%s,",
432 					    mins, mins != 1 ? "s" : "");
433 			}
434 		} else
435 			printf(" %d secs,", uptime);
436 	}
437 
438 	/* Print number of users logged in to system */
439 	(void)printf(" %d user%s", nusers, nusers != 1 ? "s" : "");
440 
441 	/*
442 	 * Print 1, 5, and 15 minute load averages.
443 	 */
444 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
445 		(void)printf(", no load average information available\n");
446 	else {
447 		(void)printf(", load averages:");
448 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
449 			if (i > 0)
450 				(void)printf(",");
451 			(void)printf(" %.2f", avenrun[i]);
452 		}
453 		(void)printf("\n");
454 	}
455 }
456 
457 static struct stat *
458 ttystat(char *line)
459 {
460 	static struct stat sb;
461 	char ttybuf[sizeof(_PATH_DEV) + UT_LINESIZE];
462 
463 	/* Note, line may not be NUL-terminated */
464 	(void)strlcpy(ttybuf, _PATH_DEV, sizeof(ttybuf));
465 	(void)strncat(ttybuf, line, sizeof(ttybuf) - 1 - strlen(ttybuf));
466 	if (stat(ttybuf, &sb))
467 		return (NULL);
468 	return (&sb);
469 }
470 
471 static void
472 usage(int wcmd)
473 {
474 	if (wcmd)
475 		(void)fprintf(stderr,
476 		    "usage: w [-hia] [-M core] [-N system] [user]\n");
477 	else
478 		(void)fprintf(stderr,
479 		    "usage: uptime [-M core] [-N system]\n");
480 	exit (1);
481 }
482