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