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