xref: /freebsd/usr.bin/w/w.c (revision a8445737e740901f5f2c8d24c12ef7fc8b00134e)
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 	"$Id: w.c,v 1.27 1998/05/21 08:46:48 jkoshy Exp $";
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 bu idle time */
101 char	       *sel_user;	/* login of particular user 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 static void	 pr_header __P((time_t *, int));
118 static struct stat
119 		*ttystat __P((char *));
120 static void	 usage __P((int));
121 
122 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
123 
124 int
125 main(argc, argv)
126 	int argc;
127 	char **argv;
128 {
129 	extern char *__progname;
130 	struct kinfo_proc *kp;
131 	struct kinfo_proc *dkp;
132 	struct hostent *hp;
133 	struct stat *stp;
134 	FILE *ut;
135 	u_long l;
136 	size_t arglen;
137 	int ch, i, nentries, nusers, wcmd, longidle;
138 	char *memf, *nlistf, *p, *x;
139 	char buf[MAXHOSTNAMELEN], errbuf[256];
140 
141 	(void) setlocale(LC_ALL, "");
142 
143 	/* Are we w(1) or uptime(1)? */
144 	p = __progname;
145 	if (*p == '-')
146 		p++;
147 	if (*p == 'u') {
148 		wcmd = 0;
149 		p = "";
150 	} else {
151 		wcmd = 1;
152 		p = "dhiflM:N:nsuw";
153 	}
154 
155 	memf = nlistf = NULL;
156 	while ((ch = getopt(argc, argv, p)) != -1)
157 		switch (ch) {
158 		case 'd':
159 			dflag = 1;
160 			break;
161 		case 'h':
162 			header = 0;
163 			break;
164 		case 'i':
165 			sortidle = 1;
166 			break;
167 		case 'M':
168 			header = 0;
169 			memf = optarg;
170 			break;
171 		case 'N':
172 			nlistf = optarg;
173 			break;
174 		case 'n':
175 			nflag = 1;
176 			break;
177 		case 'f': case 'l': case 's': case 'u': case 'w':
178 			warnx("[-flsuw] no longer supported");
179 			/* FALLTHROUGH */
180 		case '?':
181 		default:
182 			usage(wcmd);
183 		}
184 	argc -= optind;
185 	argv += optind;
186 
187 	if (!(_res.options & RES_INIT))
188 		res_init();
189 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
190 	_res.retry = 1;		/* only try once.. */
191 
192 	/*
193 	 * Discard setgid privileges if not the running kernel so that bad
194 	 * guys can't print interesting stuff from kernel memory.
195 	 */
196 	if (nlistf != NULL || memf != NULL)
197 		setgid(getgid());
198 
199 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
200 		errx(1, "%s", errbuf);
201 
202 	(void)time(&now);
203 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
204 		err(1, "%s", _PATH_UTMP);
205 
206 	if (*argv)
207 		sel_user = *argv;
208 
209 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
210 		if (utmp.ut_name[0] == '\0')
211 			continue;
212 		if (!(stp = ttystat(utmp.ut_line))) /* corrupted record */
213 			continue;
214 		++nusers;
215 		if (wcmd == 0 || (sel_user &&
216 		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
217 			continue;
218 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
219 			errx(1, "calloc");
220 		*nextp = ep;
221 		nextp = &(ep->next);
222 		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
223 		ep->tdev = stp->st_rdev;
224 #ifdef CPU_CONSDEV
225 		/*
226 		 * If this is the console device, attempt to ascertain
227 		 * the true console device dev_t.
228 		 */
229 		if (ep->tdev == 0) {
230 			int mib[2];
231 			size_t size;
232 
233 			mib[0] = CTL_MACHDEP;
234 			mib[1] = CPU_CONSDEV;
235 			size = sizeof(dev_t);
236 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
237 		}
238 #endif
239 		if ((ep->idle = now - stp->st_atime) < 0)
240 			ep->idle = 0;
241 	}
242 	(void)fclose(ut);
243 
244 	if (header || wcmd == 0) {
245 		pr_header(&now, nusers);
246 		if (wcmd == 0)
247 			exit (0);
248 
249 #define HEADER_USER		"USER"
250 #define HEADER_TTY		"TTY"
251 #define HEADER_FROM		"FROM"
252 #define HEADER_LOGIN_IDLE	"LOGIN@  IDLE "
253 #define HEADER_WHAT		"WHAT\n"
254 #define WUSED  (UT_NAMESIZE + UT_LINESIZE + UT_HOSTSIZE + \
255 		sizeof(HEADER_LOGIN_IDLE) + 3)	/* header width incl. spaces */
256 		(void)printf("%-*.*s %-*.*s %-*.*s  %s",
257 				UT_NAMESIZE, UT_NAMESIZE, HEADER_USER,
258 				UT_LINESIZE, UT_LINESIZE, HEADER_TTY,
259 				UT_HOSTSIZE, UT_HOSTSIZE, HEADER_FROM,
260 				HEADER_LOGIN_IDLE HEADER_WHAT);
261 	}
262 
263 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
264 		err(1, "%s", kvm_geterr(kd));
265 	for (i = 0; i < nentries; i++, kp++) {
266 		struct proc *p = &kp->kp_proc;
267 		struct eproc *e;
268 
269 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
270 			continue;
271 		e = &kp->kp_eproc;
272 		for (ep = ehead; ep != NULL; ep = ep->next) {
273 			if (ep->tdev == e->e_tdev) {
274 				/*
275 				 * proc is associated with this terminal
276 				 */
277 				if (ep->kp == NULL && e->e_pgid == e->e_tpgid) {
278 					/*
279 					 * Proc is 'most interesting'
280 					 */
281 					if (proc_compare(&ep->kp->kp_proc, p))
282 						ep->kp = kp;
283 				}
284 				/*
285 				 * Proc debug option info; add to debug
286 				 * list using kinfo_proc kp_eproc.e_spare
287 				 * as next pointer; ptr to ptr avoids the
288 				 * ptr = long assumption.
289 				 */
290 				dkp = ep->dkp;
291 				ep->dkp = kp;
292 				*((struct kinfo_proc **)(&kp->kp_eproc.e_spare[ 0])) = dkp;
293 			}
294 		}
295 	}
296 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
297 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
298 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
299 	       ttywidth = 79;
300         else
301 	       ttywidth = ws.ws_col - 1;
302 	argwidth = ttywidth - WUSED;
303 	if (argwidth < 4)
304 		argwidth = 8;
305 	for (ep = ehead; ep != NULL; ep = ep->next) {
306 		if (ep->kp == NULL) {
307 			ep->args = "-";
308 			continue;
309 		}
310 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
311 		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
312 		if (ep->args == NULL)
313 			err(1, NULL);
314 	}
315 	/* sort by idle time */
316 	if (sortidle && ehead != NULL) {
317 		struct entry *from = ehead, *save;
318 
319 		ehead = NULL;
320 		while (from != NULL) {
321 			for (nextp = &ehead;
322 			    (*nextp) && from->idle >= (*nextp)->idle;
323 			    nextp = &(*nextp)->next)
324 				continue;
325 			save = from;
326 			from = from->next;
327 			save->next = *nextp;
328 			*nextp = save;
329 		}
330 	}
331 
332 	if (!nflag)
333 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
334 		    (p = strchr(domain, '.')) == 0)
335 			domain[0] = '\0';
336 		else {
337 			domain[sizeof(domain) - 1] = '\0';
338 			memmove(domain, p, strlen(p) + 1);
339 		}
340 
341 	for (ep = ehead; ep != NULL; ep = ep->next) {
342 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
343 		if ((x = strchr(p, ':')) != NULL)
344 			*x++ = '\0';
345 		if (!nflag && isdigit(*p) &&
346 		    (long)(l = inet_addr(p)) != -1 &&
347 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
348 			if (domain[0] != '\0') {
349 				p = hp->h_name;
350 				p += strlen(hp->h_name);
351 				p -= strlen(domain);
352 				if (p > hp->h_name && strcmp(p, domain) == 0)
353 					*p = '\0';
354 			}
355 			p = hp->h_name;
356 		}
357 		if (nflag && *p && strcmp(p, "-") && inet_addr(p) == INADDR_NONE) {
358 			hp = gethostbyname(p);
359 
360 			if (hp != NULL) {
361 				struct in_addr in;
362 
363 				memmove(&in, hp->h_addr, sizeof(in));
364 				p = inet_ntoa(in);
365 			}
366 		}
367 		if (x) {
368 			(void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
369 			    ep->utmp.ut_host + UT_HOSTSIZE - x, x);
370 			p = buf;
371 		}
372 		if( dflag) {
373 			for( dkp = ep->dkp; dkp != NULL; dkp = *((struct kinfo_proc **)(&dkp->kp_eproc.e_spare[ 0]))) {
374 				char *p;
375 				p = fmt_argv(kvm_getargv(kd, dkp, argwidth),
376 					    dkp->kp_proc.p_comm, MAXCOMLEN);
377 				if (p == NULL)
378 					p = "-";
379 				(void)printf( "\t\t%-9d %s\n", dkp->kp_proc.p_pid, p);
380 			}
381 		}
382 		(void)printf("%-*.*s %-*.*s %-*.*s ",
383 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
384 		    UT_LINESIZE, UT_LINESIZE,
385 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
386 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
387 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
388 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
389 		pr_attime(&ep->utmp.ut_time, &now);
390 		longidle=pr_idle(ep->idle);
391 		if (longidle)
392 			argwidth--;
393 		(void)printf("%.*s\n", argwidth, ep->args);
394 	}
395 	exit(0);
396 }
397 
398 static void
399 pr_header(nowp, nusers)
400 	time_t *nowp;
401 	int nusers;
402 {
403 	double avenrun[3];
404 	time_t uptime;
405 	int days, hrs, i, mins, secs;
406 	int mib[2];
407 	size_t size;
408 	char buf[256];
409 
410 	/*
411 	 * Print time of day.
412 	 *
413 	 * SCCS forces the string manipulation below, as it replaces
414 	 * %, M, and % in a character string with the file name.
415 	 */
416 	(void)strftime(buf, sizeof(buf) - 1,
417 	    __CONCAT("%l:%","M%p"), localtime(nowp));
418 	buf[sizeof(buf) - 1] = '\0';
419 	(void)printf("%s ", buf);
420 
421 	/*
422 	 * Print how long system has been up.
423 	 * (Found by looking getting "boottime" from the kernel)
424 	 */
425 	mib[0] = CTL_KERN;
426 	mib[1] = KERN_BOOTTIME;
427 	size = sizeof(boottime);
428 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
429 	    boottime.tv_sec != 0) {
430 		uptime = now - boottime.tv_sec;
431 		uptime += 30;
432 		days = uptime / 86400;
433 		uptime %= 86400;
434 		hrs = uptime / 3600;
435 		uptime %= 3600;
436 		mins = uptime / 60;
437 		secs = uptime % 60;
438 		(void)printf(" up");
439 		if (days > 0)
440 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
441 		if (hrs > 0 && mins > 0)
442 			(void)printf(" %2d:%02d,", hrs, mins);
443 		else if (hrs > 0)
444 			(void)printf(" %d hr%s,",
445 				     hrs, hrs > 1 ? "s" : "");
446 		else if (mins > 0)
447 			(void)printf(" %d min%s,",
448 				     mins, mins > 1 ? "s" : "");
449 		else
450 			(void)printf(" %d sec%s,",
451 				     secs, secs > 1 ? "s" : "");
452 	}
453 
454 	/* Print number of users logged in to system */
455 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
456 
457 	/*
458 	 * Print 1, 5, and 15 minute load averages.
459 	 */
460 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
461 		(void)printf(", no load average information available\n");
462 	else {
463 		(void)printf(", load averages:");
464 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
465 			if (i > 0)
466 				(void)printf(",");
467 			(void)printf(" %.2f", avenrun[i]);
468 		}
469 		(void)printf("\n");
470 	}
471 }
472 
473 static struct stat *
474 ttystat(line)
475 	char *line;
476 {
477 	static struct stat sb;
478 	char ttybuf[MAXPATHLEN];
479 
480 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
481 	if (stat(ttybuf, &sb)) {
482 		warn("%s", ttybuf);
483 		return NULL;
484 	}
485 	return (&sb);
486 }
487 
488 static void
489 usage(wcmd)
490 	int wcmd;
491 {
492 	if (wcmd)
493 		(void)fprintf(stderr,
494 		    "usage: w [-dhin] [-M core] [-N system] [user]\n");
495 	else
496 		(void)fprintf(stderr,
497 			"usage: uptime\n");
498 	exit (1);
499 }
500