xref: /freebsd/usr.bin/w/w.c (revision 8e6b01171e30297084bb0b4457c4183c2746aacc)
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 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 static char sccsid[] = "@(#)w.c	8.4 (Berkeley) 4/16/94";
42 #endif /* not lint */
43 
44 /*
45  * w - print system status (who and what)
46  *
47  * This program is similar to the systat command on Tenex/Tops 10/20
48  *
49  */
50 #include <sys/param.h>
51 #include <sys/time.h>
52 #include <sys/stat.h>
53 #include <sys/sysctl.h>
54 #include <sys/proc.h>
55 #include <sys/user.h>
56 #include <sys/ioctl.h>
57 #include <sys/socket.h>
58 #include <sys/tty.h>
59 
60 #include <machine/cpu.h>
61 #include <netinet/in.h>
62 #include <arpa/inet.h>
63 
64 #include <ctype.h>
65 #include <err.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <kvm.h>
69 #include <netdb.h>
70 #include <nlist.h>
71 #include <paths.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <unistd.h>
76 #include <utmp.h>
77 #include <vis.h>
78 #include <locale.h>
79 
80 #include <arpa/nameser.h>
81 #include <resolv.h>
82 
83 #include "extern.h"
84 
85 struct timeval	boottime;
86 struct utmp	utmp;
87 struct winsize	ws;
88 kvm_t	       *kd;
89 time_t		now;		/* the current time of day */
90 time_t		uptime;		/* time of last reboot & elapsed time since */
91 int		ttywidth;	/* width of tty */
92 int		argwidth;	/* width of tty */
93 int		header = 1;	/* true if -h flag: don't print heading */
94 int		nflag;		/* true if -n flag: don't convert addrs */
95 int		sortidle;	/* sort bu idle time */
96 char	       *sel_user;	/* login of particular user selected */
97 char		domain[MAXHOSTNAMELEN];
98 
99 /*
100  * One of these per active utmp entry.
101  */
102 struct	entry {
103 	struct	entry *next;
104 	struct	utmp utmp;
105 	dev_t	tdev;		/* dev_t of terminal */
106 	time_t	idle;		/* idle time of terminal in seconds */
107 	struct	kinfo_proc *kp;	/* `most interesting' proc */
108 	char	*args;		/* arg list of interesting process */
109 } *ep, *ehead = NULL, **nextp = &ehead;
110 
111 static void	 pr_header __P((time_t *, int));
112 static struct stat
113 		*ttystat __P((char *));
114 static void	 usage __P((int));
115 
116 char *fmt_argv __P((char **, char *, int));	/* ../../bin/ps/fmt.c */
117 
118 int
119 main(argc, argv)
120 	int argc;
121 	char **argv;
122 {
123 	extern char *__progname;
124 	struct kinfo_proc *kp;
125 	struct hostent *hp;
126 	struct stat *stp;
127 	FILE *ut;
128 	u_long l;
129 	size_t arglen;
130 	int ch, i, nentries, nusers, wcmd;
131 	char *memf, *nlistf, *p, *vis_args, *x;
132 	char buf[MAXHOSTNAMELEN], errbuf[256];
133 
134 	(void) setlocale(LC_ALL, "");
135 
136 	/* Are we w(1) or uptime(1)? */
137 	p = __progname;
138 	if (*p == '-')
139 		p++;
140 	if (*p == 'u') {
141 		wcmd = 0;
142 		p = "";
143 	} else {
144 		wcmd = 1;
145 		p = "hiflM:N:nsuw";
146 	}
147 
148 	memf = nlistf = NULL;
149 	while ((ch = getopt(argc, argv, p)) != EOF)
150 		switch (ch) {
151 		case 'h':
152 			header = 0;
153 			break;
154 		case 'i':
155 			sortidle = 1;
156 			break;
157 		case 'M':
158 			header = 0;
159 			memf = optarg;
160 			break;
161 		case 'N':
162 			nlistf = optarg;
163 			break;
164 		case 'n':
165 			nflag = 1;
166 			break;
167 		case 'f': case 'l': case 's': case 'u': case 'w':
168 			warnx("[-flsuw] no longer supported");
169 			/* FALLTHROUGH */
170 		case '?':
171 		default:
172 			usage(wcmd);
173 		}
174 	argc -= optind;
175 	argv += optind;
176 
177 	if (!(_res.options & RES_INIT))
178 		res_init();
179 	_res.retrans = 2;	/* resolver timeout to 2 seconds per try */
180 	_res.retry = 1;		/* only try once.. */
181 
182 	if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf)) == NULL)
183 		errx(1, "%s", errbuf);
184 
185 	(void)time(&now);
186 	if ((ut = fopen(_PATH_UTMP, "r")) == NULL)
187 		err(1, "%s", _PATH_UTMP);
188 
189 	if (*argv)
190 		sel_user = *argv;
191 
192 	for (nusers = 0; fread(&utmp, sizeof(utmp), 1, ut);) {
193 		if (utmp.ut_name[0] == '\0')
194 			continue;
195 		++nusers;
196 		if (wcmd == 0 || (sel_user &&
197 		    strncmp(utmp.ut_name, sel_user, UT_NAMESIZE) != 0))
198 			continue;
199 		if ((ep = calloc(1, sizeof(struct entry))) == NULL)
200 			err(1, NULL);
201 		*nextp = ep;
202 		nextp = &(ep->next);
203 		memmove(&(ep->utmp), &utmp, sizeof(struct utmp));
204 		stp = ttystat(ep->utmp.ut_line);
205 		ep->tdev = stp->st_rdev;
206 #ifdef CPU_CONSDEV
207 		/*
208 		 * If this is the console device, attempt to ascertain
209 		 * the true console device dev_t.
210 		 */
211 		if (ep->tdev == 0) {
212 			int mib[2];
213 			size_t size;
214 
215 			mib[0] = CTL_MACHDEP;
216 			mib[1] = CPU_CONSDEV;
217 			size = sizeof(dev_t);
218 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
219 		}
220 #endif
221 		if ((ep->idle = now - stp->st_atime) < 0)
222 			ep->idle = 0;
223 	}
224 	(void)fclose(ut);
225 
226 	if (header || wcmd == 0) {
227 		pr_header(&now, nusers);
228 		if (wcmd == 0)
229 			exit (0);
230 
231 #define HEADER	"USER     TTY FROM              LOGIN@  IDLE WHAT\n"
232 #define WUSED	(sizeof (HEADER) - sizeof ("WHAT\n"))
233 		(void)printf(HEADER);
234 	}
235 
236 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
237 		err(1, "%s", kvm_geterr(kd));
238 	for (i = 0; i < nentries; i++, kp++) {
239 		struct proc *p = &kp->kp_proc;
240 		struct eproc *e;
241 
242 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
243 			continue;
244 		e = &kp->kp_eproc;
245 		for (ep = ehead; ep != NULL; ep = ep->next) {
246 			if (ep->tdev == e->e_tdev && e->e_pgid == e->e_tpgid) {
247 				/*
248 				 * Proc is in foreground of this terminal
249 				 */
250 				if (proc_compare(&ep->kp->kp_proc, p))
251 					ep->kp = kp;
252 				break;
253 			}
254 		}
255 	}
256 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
257 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
258 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
259 	       ttywidth = 79;
260         else
261 	       ttywidth = ws.ws_col - 1;
262 	argwidth = ttywidth - WUSED;
263 	if (argwidth < 4)
264 		argwidth = 8;
265 	for (ep = ehead; ep != NULL; ep = ep->next) {
266 		if (ep->kp == NULL) {
267 			ep->args = "-";
268 			continue;
269 		}
270 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
271 		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
272 		if (ep->args == NULL)
273 			err(1, NULL);
274 	}
275 	/* sort by idle time */
276 	if (sortidle && ehead != NULL) {
277 		struct entry *from = ehead, *save;
278 
279 		ehead = NULL;
280 		while (from != NULL) {
281 			for (nextp = &ehead;
282 			    (*nextp) && from->idle >= (*nextp)->idle;
283 			    nextp = &(*nextp)->next)
284 				continue;
285 			save = from;
286 			from = from->next;
287 			save->next = *nextp;
288 			*nextp = save;
289 		}
290 	}
291 
292 	if (!nflag)
293 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
294 		    (p = strchr(domain, '.')) == 0)
295 			domain[0] = '\0';
296 		else {
297 			domain[sizeof(domain) - 1] = '\0';
298 			memmove(domain, p, strlen(p) + 1);
299 		}
300 
301 	if ((vis_args = malloc(argwidth * 4 + 1)) == NULL)
302 		err(1, NULL);
303 	for (ep = ehead; ep != NULL; ep = ep->next) {
304 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
305 		if ((x = strchr(p, ':')) != NULL)
306 			*x++ = '\0';
307 		if (!nflag && isdigit(*p) &&
308 		    (long)(l = inet_addr(p)) != -1 &&
309 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
310 			if (domain[0] != '\0') {
311 				p = hp->h_name;
312 				p += strlen(hp->h_name);
313 				p -= strlen(domain);
314 				if (p > hp->h_name && strcmp(p, domain) == 0)
315 					*p = '\0';
316 			}
317 			p = hp->h_name;
318 		}
319 		if (x) {
320 			(void)snprintf(buf, sizeof(buf), "%s:%.*s", p,
321 			    ep->utmp.ut_host + UT_HOSTSIZE - x, x);
322 			p = buf;
323 		}
324 		(void)printf("%-*.*s %-3.3s %-*.*s ",
325 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
326 		    strncmp(ep->utmp.ut_line, "tty", 3) &&
327 		    strncmp(ep->utmp.ut_line, "cua", 3) ?
328 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
329 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
330 		pr_attime(&ep->utmp.ut_time, &now);
331 		pr_idle(ep->idle);
332 		if (ep->args != NULL) {
333 			arglen = strlen(ep->args);
334 			strvisx(vis_args, ep->args,
335 			    arglen > argwidth ? argwidth : arglen,
336 			    VIS_TAB | VIS_NL | VIS_NOSLASH);
337 		}
338 		(void)printf("%.*s\n", argwidth, ep->args);
339 	}
340 	exit(0);
341 }
342 
343 static void
344 pr_header(nowp, nusers)
345 	time_t *nowp;
346 	int nusers;
347 {
348 	double avenrun[3];
349 	time_t uptime;
350 	int days, hrs, i, mins;
351 	int mib[2];
352 	size_t size;
353 	char buf[256];
354 
355 	/*
356 	 * Print time of day.
357 	 *
358 	 * SCCS forces the string manipulation below, as it replaces
359 	 * %, M, and % in a character string with the file name.
360 	 */
361 	(void)strftime(buf, sizeof(buf),
362 	    __CONCAT("%l:%","M%p"), localtime(nowp));
363 	(void)printf("%s ", buf);
364 
365 	/*
366 	 * Print how long system has been up.
367 	 * (Found by looking getting "boottime" from the kernel)
368 	 */
369 	mib[0] = CTL_KERN;
370 	mib[1] = KERN_BOOTTIME;
371 	size = sizeof(boottime);
372 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
373 	    boottime.tv_sec != 0) {
374 		uptime = now - boottime.tv_sec;
375 		uptime += 30;
376 		days = uptime / 86400;
377 		uptime %= 86400;
378 		hrs = uptime / 3600;
379 		uptime %= 3600;
380 		mins = uptime / 60;
381 		(void)printf(" up");
382 		if (days > 0)
383 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
384 		if (hrs > 0 && mins > 0)
385 			(void)printf(" %2d:%02d,", hrs, mins);
386 		else {
387 			if (hrs > 0)
388 				(void)printf(" %d hr%s,",
389 				    hrs, hrs > 1 ? "s" : "");
390 			if (mins > 0)
391 				(void)printf(" %d min%s,",
392 				    mins, mins > 1 ? "s" : "");
393 		}
394 	}
395 
396 	/* Print number of users logged in to system */
397 	(void)printf(" %d user%s", nusers, nusers == 1 ? "" : "s");
398 
399 	/*
400 	 * Print 1, 5, and 15 minute load averages.
401 	 */
402 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
403 		(void)printf(", no load average information available\n");
404 	else {
405 		(void)printf(", load averages:");
406 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
407 			if (i > 0)
408 				(void)printf(",");
409 			(void)printf(" %.2f", avenrun[i]);
410 		}
411 		(void)printf("\n");
412 	}
413 }
414 
415 static struct stat *
416 ttystat(line)
417 	char *line;
418 {
419 	static struct stat sb;
420 	char ttybuf[MAXPATHLEN];
421 
422 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
423 	if (stat(ttybuf, &sb))
424 		err(1, "%s", ttybuf);
425 	return (&sb);
426 }
427 
428 static void
429 usage(wcmd)
430 	int wcmd;
431 {
432 	if (wcmd)
433 		(void)fprintf(stderr,
434 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
435 	else
436 		(void)fprintf(stderr, "uptime\n");
437 	exit (1);
438 }
439