xref: /freebsd/usr.bin/w/w.c (revision c68159a6d8eede11766cf13896d0f7670dbd51aa)
1 /*-
2  * Copyright (c) 1980, 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1980, 1991, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 /*
49  * w - print system status (who and what)
50  *
51  * This program is similar to the systat command on Tenex/Tops 10/20
52  *
53  */
54 #include <sys/param.h>
55 #include <sys/time.h>
56 #include <sys/stat.h>
57 #include <sys/sysctl.h>
58 #include <sys/proc.h>
59 #include <sys/user.h>
60 #include <sys/ioctl.h>
61 #include <sys/socket.h>
62 #include <sys/tty.h>
63 
64 #include <machine/cpu.h>
65 #include <netinet/in.h>
66 #include <arpa/inet.h>
67 
68 #include <ctype.h>
69 #include <err.h>
70 #include <errno.h>
71 #include <fcntl.h>
72 #include <kvm.h>
73 #include <netdb.h>
74 #include <nlist.h>
75 #include <paths.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <unistd.h>
80 #include <utmp.h>
81 #include <vis.h>
82 #include <locale.h>
83 
84 #include <arpa/nameser.h>
85 #include <resolv.h>
86 
87 #include "extern.h"
88 
89 struct timeval	boottime;
90 struct utmp	utmp;
91 struct winsize	ws;
92 kvm_t	       *kd;
93 time_t		now;		/* the current time of day */
94 time_t		uptime;		/* time of last reboot & elapsed time since */
95 int		ttywidth;	/* width of tty */
96 int		argwidth;	/* width of tty */
97 int		header = 1;	/* true if -h flag: don't print heading */
98 int		nflag;		/* true if -n flag: don't convert addrs */
99 int		dflag;		/* true if -d flag: output debug info */
100 int		sortidle;	/* sort by idle time */
101 char	      **sel_users;	/* login array of particular users selected */
102 char		domain[MAXHOSTNAMELEN];
103 
104 /*
105  * One of these per active utmp entry.
106  */
107 struct	entry {
108 	struct	entry *next;
109 	struct	utmp utmp;
110 	dev_t	tdev;			/* dev_t of terminal */
111 	time_t	idle;			/* idle time of terminal in seconds */
112 	struct	kinfo_proc *kp;		/* `most interesting' proc */
113 	char	*args;			/* arg list of interesting process */
114 	struct	kinfo_proc *dkp;	/* debug option proc list */
115 } *ep, *ehead = NULL, **nextp = &ehead;
116 
117 #define debugproc(p) *((struct kinfo_proc **)&(p)->ki_spare[0])
118 
119 static void		 pr_header __P((time_t *, int));
120 static struct stat	*ttystat __P((char *, int));
121 static void		 usage __P((int));
122 static int		 this_is_uptime __P((const char *s));
123 
124 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
125 
126 int
127 main(argc, argv)
128 	int argc;
129 	char **argv;
130 {
131 	struct kinfo_proc *kp;
132 	struct kinfo_proc *dkp;
133 	struct hostent *hp;
134 	struct stat *stp;
135 	FILE *ut;
136 	u_long l;
137 	time_t touched;
138 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
139 	char *memf, *nlistf, *p, *x;
140 	char buf[MAXHOSTNAMELEN], errbuf[256];
141 
142 	(void)setlocale(LC_ALL, "");
143 
144 	/* Are we w(1) or uptime(1)? */
145 	if (this_is_uptime(argv[0]) == 0) {
146 		wcmd = 0;
147 		p = "";
148 	} else {
149 		wcmd = 1;
150 		p = "dhiflM:N:nsuw";
151 	}
152 
153 	dropgid = 0;
154 	memf = nlistf = _PATH_DEVNULL;
155 	while ((ch = getopt(argc, argv, p)) != -1)
156 		switch (ch) {
157 		case 'd':
158 			dflag = 1;
159 			break;
160 		case 'h':
161 			header = 0;
162 			break;
163 		case 'i':
164 			sortidle = 1;
165 			break;
166 		case 'M':
167 			header = 0;
168 			memf = optarg;
169 			dropgid = 1;
170 			break;
171 		case 'N':
172 			nlistf = optarg;
173 			dropgid = 1;
174 			break;
175 		case 'n':
176 			nflag = 1;
177 			break;
178 		case 'f': case 'l': case 's': case 'u': case 'w':
179 			warnx("[-flsuw] no longer supported");
180 			/* FALLTHROUGH */
181 		case '?':
182 		default:
183 			usage(wcmd);
184 		}
185 	argc -= optind;
186 	argv += optind;
187 
188 	if (!(_res.options & RES_INIT))
189 		res_init();
190 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
191 	_res.retry = 1;		/* only try once.. */
192 
193 	/*
194 	 * Discard setgid privileges if not the running kernel so that bad
195 	 * guys can't print interesting stuff from kernel memory.
196 	 */
197 	if (dropgid)
198 		setgid(getgid());
199 
200 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
201 		errx(1, "%s", errbuf);
202 
203 	(void)time(&now);
204 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
205 		err(1, "%s", _PATH_UTMP);
206 
207 	if (*argv)
208 		sel_users = argv;
209 
210 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
211 		if (utmp.ut_name[0] == '\0')
212 			continue;
213 		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
214 			continue;	/* corrupted record */
215 		++nusers;
216 		if (wcmd == 0)
217 			continue;
218 		if (sel_users) {
219 			int usermatch;
220 			char **user;
221 
222 			usermatch = 0;
223 			for (user = sel_users; !usermatch && *user; user++)
224 				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
225 					usermatch = 1;
226 			if (!usermatch)
227 				continue;
228 		}
229 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
230 			errx(1, "calloc");
231 		*nextp = ep;
232 		nextp = &ep->next;
233 		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
234 		ep->tdev = stp->st_rdev;
235 #ifdef CPU_CONSDEV
236 		/*
237 		 * If this is the console device, attempt to ascertain
238 		 * the true console device dev_t.
239 		 */
240 		if (ep->tdev == 0) {
241 			int mib[2];
242 			size_t size;
243 
244 			mib[0] = CTL_MACHDEP;
245 			mib[1] = CPU_CONSDEV;
246 			size = sizeof(dev_t);
247 			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
248 		}
249 #endif
250 		touched = stp->st_atime;
251 		if (touched < ep->utmp.ut_time) {
252 			/* tty untouched since before login */
253 			touched = ep->utmp.ut_time;
254 		}
255 		if ((ep->idle = now - touched) < 0)
256 			ep->idle = 0;
257 	}
258 	(void)fclose(ut);
259 
260 	if (header || wcmd == 0) {
261 		pr_header(&now, nusers);
262 		if (wcmd == 0)
263 			exit(0);
264 
265 #define HEADER_USER		"USER"
266 #define HEADER_TTY		"TTY"
267 #define HEADER_FROM		"FROM"
268 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
269 #define HEADER_WHAT		"WHAT\n"
270 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
271 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
272 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
273 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
274 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
275 				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
276 				HEADER_LOGIN_IDLE HEADER_WHAT);
277 	}
278 
279 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
280 		err(1, "%s", kvm_geterr(kd));
281 	for (i = 0; i < nentries; i++, kp++) {
282 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
283 			continue;
284 		for (ep = ehead; ep != NULL; ep = ep->next) {
285 			if (ep->tdev == kp->ki_tdev) {
286 				/*
287 				 * proc is associated with this terminal
288 				 */
289 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
290 					/*
291 					 * Proc is 'most interesting'
292 					 */
293 					if (proc_compare(ep->kp, kp))
294 						ep->kp = kp;
295 				}
296 				/*
297 				 * Proc debug option info; add to debug
298 				 * list using kinfo_proc ki_spare[0]
299 				 * as next pointer; ptr to ptr avoids the
300 				 * ptr = long assumption.
301 				 */
302 				dkp = ep->dkp;
303 				ep->dkp = kp;
304 				debugproc(kp) = dkp;
305 			}
306 		}
307 	}
308 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
309 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
310 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
311 	       ttywidth = 79;
312         else
313 	       ttywidth = ws.ws_col - 1;
314 	argwidth = ttywidth - WUSED;
315 	if (argwidth < 4)
316 		argwidth = 8;
317 	for (ep = ehead; ep != NULL; ep = ep->next) {
318 		if (ep->kp == NULL) {
319 			ep->args = "-";
320 			continue;
321 		}
322 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
323 		    ep->kp->ki_comm, MAXCOMLEN);
324 		if (ep->args == NULL)
325 			err(1, NULL);
326 	}
327 	/* sort by idle time */
328 	if (sortidle && ehead != NULL) {
329 		struct entry *from, *save;
330 
331 		from = ehead;
332 		ehead = NULL;
333 		while (from != NULL) {
334 			for (nextp = &ehead;
335 			    (*nextp) && from->idle >= (*nextp)->idle;
336 			    nextp = &(*nextp)->next)
337 				continue;
338 			save = from;
339 			from = from->next;
340 			save->next = *nextp;
341 			*nextp = save;
342 		}
343 	}
344 
345 	if (!nflag) {
346 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
347 		    (p = strchr(domain, '.')) == NULL)
348 			domain[0] = '\0';
349 		else {
350 			domain[sizeof(domain) - 1] = '\0';
351 			memmove(domain, p, strlen(p) + 1);
352 		}
353 	}
354 
355 	for (ep = ehead; ep != NULL; ep = ep->next) {
356 		char host_buf[UT_HOSTSIZE + 1];
357 
358 		host_buf[UT_HOSTSIZE] = '\0';
359 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
360 		p = *host_buf ? host_buf : "-";
361 		if ((x = strchr(p, ':')) != NULL)
362 			*x++ = '\0';
363 		if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 &&
364 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
365 			if (domain[0] != '\0') {
366 				p = hp->h_name;
367 				p += strlen(hp->h_name);
368 				p -= strlen(domain);
369 				if (p > hp->h_name &&
370 				    strcasecmp(p, domain) == 0)
371 					*p = '\0';
372 			}
373 			p = hp->h_name;
374 		}
375 		if (nflag && *p && strcmp(p, "-") &&
376 		    inet_addr(p) == INADDR_NONE) {
377 			hp = gethostbyname(p);
378 
379 			if (hp != NULL) {
380 				struct in_addr in;
381 
382 				memmove(&in, hp->h_addr, sizeof(in));
383 				p = inet_ntoa(in);
384 			}
385 		}
386 		if (x) {
387 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
388 			p = buf;
389 		}
390 		if (dflag) {
391 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
392 				char *ptr;
393 
394 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
395 				    dkp->ki_comm, MAXCOMLEN);
396 				if (ptr == NULL)
397 					ptr = "-";
398 				(void)printf("\t\t%-9d %s\n",
399 				    dkp->ki_pid, ptr);
400 			}
401 		}
402 		(void)printf("%-*.*s %-*.*s %-*.*s ",
403 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
404 		    UT_LINESIZE, UT_LINESIZE,
405 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
406 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
407 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
408 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
409 		pr_attime(&ep->utmp.ut_time, &now);
410 		longidle = pr_idle(ep->idle);
411 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
412 	}
413 	exit(0);
414 }
415 
416 static void
417 pr_header(nowp, nusers)
418 	time_t *nowp;
419 	int nusers;
420 {
421 	double avenrun[3];
422 	time_t uptime;
423 	int days, hrs, i, mins, secs;
424 	int mib[2];
425 	size_t size;
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 	 * (Found by looking getting "boottime" from the kernel)
438 	 */
439 	mib[0] = CTL_KERN;
440 	mib[1] = KERN_BOOTTIME;
441 	size = sizeof(boottime);
442 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
443 	    boottime.tv_sec != 0) {
444 		uptime = now - boottime.tv_sec;
445 		uptime += 30;
446 		days = uptime / 86400;
447 		uptime %= 86400;
448 		hrs = uptime / 3600;
449 		uptime %= 3600;
450 		mins = uptime / 60;
451 		secs = uptime % 60;
452 		(void)printf(" up");
453 		if (days > 0)
454 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
455 		if (hrs > 0 && mins > 0)
456 			(void)printf(" %2d:%02d,", hrs, mins);
457 		else if (hrs > 0)
458 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
459 		else if (mins > 0)
460 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
461 		else
462 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
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 			(void)printf("%s %.2f", i > 0 ? "," : "", avenrun[i]);
477 		(void)printf("\n");
478 	}
479 }
480 
481 static struct stat *
482 ttystat(line, sz)
483 	char *line;
484 	int sz;
485 {
486 	static struct stat sb;
487 	char ttybuf[MAXPATHLEN];
488 
489 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
490 	if (stat(ttybuf, &sb)) {
491 		warn("%s", ttybuf);
492 		return (NULL);
493 	}
494 	return (&sb);
495 }
496 
497 static void
498 usage(wcmd)
499 	int wcmd;
500 {
501 	if (wcmd)
502 		(void)fprintf(stderr,
503 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
504 	else
505 		(void)fprintf(stderr, "usage: uptime\n");
506 	exit(1);
507 }
508 
509 static int
510 this_is_uptime(s)
511 	const char *s;
512 {
513 	const char *u;
514 
515 	if ((u = strrchr(s, '/')) != NULL)
516 		++u;
517 	else
518 		u = s;
519 	if (strcmp(u, "uptime") == 0)
520 		return (0);
521 	return (-1);
522 }
523