xref: /freebsd/usr.bin/w/w.c (revision ce4946daa5ce852d28008dac492029500ab2ee95)
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/lock.h>
56 #include <sys/time.h>
57 #include <sys/stat.h>
58 #include <sys/sysctl.h>
59 #include <sys/proc.h>
60 #include <sys/user.h>
61 #include <sys/ioctl.h>
62 #include <sys/socket.h>
63 #include <sys/tty.h>
64 
65 #include <machine/cpu.h>
66 #include <netinet/in.h>
67 #include <arpa/inet.h>
68 
69 #include <ctype.h>
70 #include <err.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <kvm.h>
74 #include <langinfo.h>
75 #include <locale.h>
76 #include <netdb.h>
77 #include <nlist.h>
78 #include <paths.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <unistd.h>
83 #include <utmp.h>
84 #include <vis.h>
85 
86 #include <arpa/nameser.h>
87 #include <resolv.h>
88 
89 #include "extern.h"
90 
91 struct timeval	boottime;
92 struct utmp	utmp;
93 struct winsize	ws;
94 kvm_t	       *kd;
95 time_t		now;		/* the current time of day */
96 time_t		uptime;		/* time of last reboot & elapsed time since */
97 int		ttywidth;	/* width of tty */
98 int		argwidth;	/* width of tty */
99 int		header = 1;	/* true if -h flag: don't print heading */
100 int		nflag;		/* true if -n flag: don't convert addrs */
101 int		dflag;		/* true if -d flag: output debug info */
102 int		sortidle;	/* sort by idle time */
103 int		use_ampm;	/* use AM/PM time */
104 int             use_comma;      /* use comma as floats separator */
105 char	      **sel_users;	/* login array of particular users selected */
106 char		domain[MAXHOSTNAMELEN];
107 
108 /*
109  * One of these per active utmp entry.
110  */
111 struct	entry {
112 	struct	entry *next;
113 	struct	utmp utmp;
114 	dev_t	tdev;			/* dev_t of terminal */
115 	time_t	idle;			/* idle time of terminal in seconds */
116 	struct	kinfo_proc *kp;		/* `most interesting' proc */
117 	char	*args;			/* arg list of interesting process */
118 	struct	kinfo_proc *dkp;	/* debug option proc list */
119 } *ep, *ehead = NULL, **nextp = &ehead;
120 
121 #define debugproc(p) *((struct kinfo_proc **)&(p)->ki_spare[0])
122 
123 static void		 pr_header __P((time_t *, int));
124 static struct stat	*ttystat __P((char *, int));
125 static void		 usage __P((int));
126 static int		 this_is_uptime __P((const char *s));
127 
128 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
129 
130 int
131 main(argc, argv)
132 	int argc;
133 	char **argv;
134 {
135 	struct kinfo_proc *kp;
136 	struct kinfo_proc *dkp;
137 	struct hostent *hp;
138 	struct stat *stp;
139 	FILE *ut;
140 	u_long l;
141 	time_t touched;
142 	int ch, i, nentries, nusers, wcmd, longidle, dropgid;
143 	char *memf, *nlistf, *p, *x;
144 	char buf[MAXHOSTNAMELEN], errbuf[256];
145 
146 	(void)setlocale(LC_ALL, "");
147 	use_ampm = (*nl_langinfo(T_FMT_AMPM) != '\0');
148 	use_comma = (*nl_langinfo(RADIXCHAR) != ',');
149 
150 	/* Are we w(1) or uptime(1)? */
151 	if (this_is_uptime(argv[0]) == 0) {
152 		wcmd = 0;
153 		p = "";
154 	} else {
155 		wcmd = 1;
156 		p = "dhiflM:N:nsuw";
157 	}
158 
159 	dropgid = 0;
160 	memf = nlistf = _PATH_DEVNULL;
161 	while ((ch = getopt(argc, argv, p)) != -1)
162 		switch (ch) {
163 		case 'd':
164 			dflag = 1;
165 			break;
166 		case 'h':
167 			header = 0;
168 			break;
169 		case 'i':
170 			sortidle = 1;
171 			break;
172 		case 'M':
173 			header = 0;
174 			memf = optarg;
175 			dropgid = 1;
176 			break;
177 		case 'N':
178 			nlistf = optarg;
179 			dropgid = 1;
180 			break;
181 		case 'n':
182 			nflag = 1;
183 			break;
184 		case 'f': case 'l': case 's': case 'u': case 'w':
185 			warnx("[-flsuw] no longer supported");
186 			/* FALLTHROUGH */
187 		case '?':
188 		default:
189 			usage(wcmd);
190 		}
191 	argc -= optind;
192 	argv += optind;
193 
194 	if (!(_res.options & RES_INIT))
195 		res_init();
196 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
197 	_res.retry = 1;		/* only try once.. */
198 
199 	/*
200 	 * Discard setgid privileges if not the running kernel so that bad
201 	 * guys can't print interesting stuff from kernel memory.
202 	 */
203 	if (dropgid)
204 		setgid(getgid());
205 
206 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
207 		errx(1, "%s", errbuf);
208 
209 	(void)time(&now);
210 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
211 		err(1, "%s", _PATH_UTMP);
212 
213 	if (*argv)
214 		sel_users = argv;
215 
216 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
217 		if (utmp.ut_name[0] == '\0')
218 			continue;
219 		if (!(stp = ttystat(utmp.ut_line, UT_LINESIZE)))
220 			continue;	/* corrupted record */
221 		++nusers;
222 		if (wcmd == 0)
223 			continue;
224 		if (sel_users) {
225 			int usermatch;
226 			char **user;
227 
228 			usermatch = 0;
229 			for (user = sel_users; !usermatch && *user; user++)
230 				if (!strncmp(utmp.ut_name, *user, UT_NAMESIZE))
231 					usermatch = 1;
232 			if (!usermatch)
233 				continue;
234 		}
235 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
236 			errx(1, "calloc");
237 		*nextp = ep;
238 		nextp = &ep->next;
239 		memmove(&ep->utmp, &utmp, sizeof(struct utmp));
240 		ep->tdev = stp->st_rdev;
241 #ifdef CPU_CONSDEV
242 		/*
243 		 * If this is the console device, attempt to ascertain
244 		 * the true console device dev_t.
245 		 */
246 		if (ep->tdev == 0) {
247 			int mib[2];
248 			size_t size;
249 
250 			mib[0] = CTL_MACHDEP;
251 			mib[1] = CPU_CONSDEV;
252 			size = sizeof(dev_t);
253 			(void)sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
254 		}
255 #endif
256 		touched = stp->st_atime;
257 		if (touched < ep->utmp.ut_time) {
258 			/* tty untouched since before login */
259 			touched = ep->utmp.ut_time;
260 		}
261 		if ((ep->idle = now - touched) < 0)
262 			ep->idle = 0;
263 	}
264 	(void)fclose(ut);
265 
266 	if (header || wcmd == 0) {
267 		pr_header(&now, nusers);
268 		if (wcmd == 0)
269 			exit(0);
270 
271 #define HEADER_USER		"USER"
272 #define HEADER_TTY		"TTY"
273 #define HEADER_FROM		"FROM"
274 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
275 #define HEADER_WHAT		"WHAT\n"
276 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
277 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
278 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
279 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
280 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
281 				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
282 				HEADER_LOGIN_IDLE HEADER_WHAT);
283 	}
284 
285 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
286 		err(1, "%s", kvm_geterr(kd));
287 	for (i = 0; i < nentries; i++, kp++) {
288 		if (kp->ki_stat == SIDL || kp->ki_stat == SZOMB)
289 			continue;
290 		for (ep = ehead; ep != NULL; ep = ep->next) {
291 			if (ep->tdev == kp->ki_tdev) {
292 				/*
293 				 * proc is associated with this terminal
294 				 */
295 				if (ep->kp == NULL && kp->ki_pgid == kp->ki_tpgid) {
296 					/*
297 					 * Proc is 'most interesting'
298 					 */
299 					if (proc_compare(ep->kp, kp))
300 						ep->kp = kp;
301 				}
302 				/*
303 				 * Proc debug option info; add to debug
304 				 * list using kinfo_proc ki_spare[0]
305 				 * as next pointer; ptr to ptr avoids the
306 				 * ptr = long assumption.
307 				 */
308 				dkp = ep->dkp;
309 				ep->dkp = kp;
310 				debugproc(kp) = dkp;
311 			}
312 		}
313 	}
314 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
315 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
316 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
317 	       ttywidth = 79;
318         else
319 	       ttywidth = ws.ws_col - 1;
320 	argwidth = ttywidth - WUSED;
321 	if (argwidth < 4)
322 		argwidth = 8;
323 	for (ep = ehead; ep != NULL; ep = ep->next) {
324 		if (ep->kp == NULL) {
325 			ep->args = "-";
326 			continue;
327 		}
328 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
329 		    ep->kp->ki_comm, MAXCOMLEN);
330 		if (ep->args == NULL)
331 			err(1, NULL);
332 	}
333 	/* sort by idle time */
334 	if (sortidle && ehead != NULL) {
335 		struct entry *from, *save;
336 
337 		from = ehead;
338 		ehead = NULL;
339 		while (from != NULL) {
340 			for (nextp = &ehead;
341 			    (*nextp) && from->idle >= (*nextp)->idle;
342 			    nextp = &(*nextp)->next)
343 				continue;
344 			save = from;
345 			from = from->next;
346 			save->next = *nextp;
347 			*nextp = save;
348 		}
349 	}
350 
351 	if (!nflag) {
352 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
353 		    (p = strchr(domain, '.')) == NULL)
354 			domain[0] = '\0';
355 		else {
356 			domain[sizeof(domain) - 1] = '\0';
357 			memmove(domain, p, strlen(p) + 1);
358 		}
359 	}
360 
361 	for (ep = ehead; ep != NULL; ep = ep->next) {
362 		char host_buf[UT_HOSTSIZE + 1];
363 
364 		host_buf[UT_HOSTSIZE] = '\0';
365 		strncpy(host_buf, ep->utmp.ut_host, UT_HOSTSIZE);
366 		p = *host_buf ? host_buf : "-";
367 		if ((x = strchr(p, ':')) != NULL)
368 			*x++ = '\0';
369 		if (!nflag && isdigit(*p) && (l = inet_addr(p)) != -1 &&
370 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
371 			if (domain[0] != '\0') {
372 				p = hp->h_name;
373 				p += strlen(hp->h_name);
374 				p -= strlen(domain);
375 				if (p > hp->h_name &&
376 				    strcasecmp(p, domain) == 0)
377 					*p = '\0';
378 			}
379 			p = hp->h_name;
380 		}
381 		if (nflag && *p && strcmp(p, "-") &&
382 		    inet_addr(p) == INADDR_NONE) {
383 			hp = gethostbyname(p);
384 
385 			if (hp != NULL) {
386 				struct in_addr in;
387 
388 				memmove(&in, hp->h_addr, sizeof(in));
389 				p = inet_ntoa(in);
390 			}
391 		}
392 		if (x) {
393 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
394 			p = buf;
395 		}
396 		if (dflag) {
397 			for (dkp = ep->dkp; dkp != NULL; dkp = debugproc(dkp)) {
398 				char *ptr;
399 
400 				ptr = fmt_argv(kvm_getargv(kd, dkp, argwidth),
401 				    dkp->ki_comm, MAXCOMLEN);
402 				if (ptr == NULL)
403 					ptr = "-";
404 				(void)printf("\t\t%-9d %s\n",
405 				    dkp->ki_pid, ptr);
406 			}
407 		}
408 		(void)printf("%-*.*s %-*.*s %-*.*s ",
409 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
410 		    UT_LINESIZE, UT_LINESIZE,
411 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
412 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
413 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
414 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
415 		pr_attime(&ep->utmp.ut_time, &now);
416 		longidle = pr_idle(ep->idle);
417 		(void)printf("%.*s\n", argwidth - longidle, ep->args);
418 	}
419 	exit(0);
420 }
421 
422 static void
423 pr_header(nowp, nusers)
424 	time_t *nowp;
425 	int nusers;
426 {
427 	double avenrun[3];
428 	time_t uptime;
429 	int days, hrs, i, mins, secs;
430 	int mib[2];
431 	size_t size;
432 	char buf[256];
433 
434 	/*
435 	 * Print time of day.
436 	 */
437 	(void)strftime(buf, sizeof(buf)	- 1,
438 		       use_ampm	? "%l:%M%p" : "%k:%M", localtime(nowp));
439 	buf[sizeof(buf) - 1] = '\0';
440 	(void)printf("%s ", buf);
441 
442 	/*
443 	 * Print how long system has been up.
444 	 * (Found by looking getting "boottime" from the kernel)
445 	 */
446 	mib[0] = CTL_KERN;
447 	mib[1] = KERN_BOOTTIME;
448 	size = sizeof(boottime);
449 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
450 	    boottime.tv_sec != 0) {
451 		uptime = now - boottime.tv_sec;
452 		uptime += 30;
453 		days = uptime / 86400;
454 		uptime %= 86400;
455 		hrs = uptime / 3600;
456 		uptime %= 3600;
457 		mins = uptime / 60;
458 		secs = uptime % 60;
459 		(void)printf(" up");
460 		if (days > 0)
461 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
462 		if (hrs > 0 && mins > 0)
463 			(void)printf(" %2d:%02d,", hrs, mins);
464 		else if (hrs > 0)
465 			(void)printf(" %d hr%s,", hrs, hrs > 1 ? "s" : "");
466 		else if (mins > 0)
467 			(void)printf(" %d min%s,", mins, mins > 1 ? "s" : "");
468 		else
469 			(void)printf(" %d sec%s,", secs, secs > 1 ? "s" : "");
470 	}
471 
472 	/* Print number of users logged in to system */
473 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
474 
475 	/*
476 	 * Print 1, 5, and 15 minute load averages.
477 	 */
478 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
479 		(void)printf(", no load average information available\n");
480 	else {
481 		(void)printf(", load averages:");
482 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
483 			if (use_comma && i > 0)
484 				(void)printf(",");
485 			(void)printf(" %.2f", avenrun[i]);
486 		}
487 		(void)printf("\n");
488 	}
489 }
490 
491 static struct stat *
492 ttystat(line, sz)
493 	char *line;
494 	int sz;
495 {
496 	static struct stat sb;
497 	char ttybuf[MAXPATHLEN];
498 
499 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
500 	if (stat(ttybuf, &sb)) {
501 		warn("%s", ttybuf);
502 		return (NULL);
503 	}
504 	return (&sb);
505 }
506 
507 static void
508 usage(wcmd)
509 	int wcmd;
510 {
511 	if (wcmd)
512 		(void)fprintf(stderr,
513 		    "usage: w [-dhin] [-M core] [-N system] [user ...]\n");
514 	else
515 		(void)fprintf(stderr, "usage: uptime\n");
516 	exit(1);
517 }
518 
519 static int
520 this_is_uptime(s)
521 	const char *s;
522 {
523 	const char *u;
524 
525 	if ((u = strrchr(s, '/')) != NULL)
526 		++u;
527 	else
528 		u = s;
529 	if (strcmp(u, "uptime") == 0)
530 		return (0);
531 	return (-1);
532 }
533