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