xref: /original-bsd/usr.bin/w/w.c (revision 7e5c8007)
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.4 (Berkeley) 04/16/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 		stp = ttystat(ep->utmp.ut_line);
169 		ep->tdev = stp->st_rdev;
170 #ifdef CPU_CONSDEV
171 		/*
172 		 * If this is the console device, attempt to ascertain
173 		 * the true console device dev_t.
174 		 */
175 		if (ep->tdev == 0) {
176 			int mib[2];
177 			size_t size;
178 
179 			mib[0] = CTL_MACHDEP;
180 			mib[1] = CPU_CONSDEV;
181 			size = sizeof(dev_t);
182 			(void) sysctl(mib, 2, &ep->tdev, &size, NULL, 0);
183 		}
184 #endif
185 		if ((ep->idle = now - stp->st_atime) < 0)
186 			ep->idle = 0;
187 	}
188 	(void)fclose(ut);
189 
190 	if (header || wcmd == 0) {
191 		pr_header(&now, nusers);
192 		if (wcmd == 0)
193 			exit (0);
194 	}
195 
196 #define HEADER	"USER    TTY FROM              LOGIN@  IDLE WHAT\n"
197 #define WUSED	(sizeof (HEADER) - sizeof ("WHAT\n"))
198 	(void)printf(HEADER);
199 
200 	if ((kp = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nentries)) == NULL)
201 		err(1, "%s", kvm_geterr(kd));
202 	for (i = 0; i < nentries; i++, kp++) {
203 		struct proc *p = &kp->kp_proc;
204 		struct eproc *e;
205 
206 		if (p->p_stat == SIDL || p->p_stat == SZOMB)
207 			continue;
208 		e = &kp->kp_eproc;
209 		for (ep = ehead; ep != NULL; ep = ep->next) {
210 			if (ep->tdev == e->e_tdev && e->e_pgid == e->e_tpgid) {
211 				/*
212 				 * Proc is in foreground of this terminal
213 				 */
214 				if (proc_compare(&ep->kp->kp_proc, p))
215 					ep->kp = kp;
216 				break;
217 			}
218 		}
219 	}
220 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 &&
221 	     ioctl(STDERR_FILENO, TIOCGWINSZ, &ws) == -1 &&
222 	     ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1) || ws.ws_col == 0)
223 	       ttywidth = 79;
224         else
225 	       ttywidth = ws.ws_col - 1;
226 	argwidth = ttywidth - WUSED;
227 	if (argwidth < 4)
228 		argwidth = 8;
229 	for (ep = ehead; ep != NULL; ep = ep->next) {
230 		if (ep->kp == NULL) {
231 			ep->args = "-";
232 			continue;
233 		}
234 		ep->args = fmt_argv(kvm_getargv(kd, ep->kp, argwidth),
235 		    ep->kp->kp_proc.p_comm, MAXCOMLEN);
236 		if (ep->args == NULL)
237 			err(1, NULL);
238 	}
239 	/* sort by idle time */
240 	if (sortidle && ehead != NULL) {
241 		struct entry *from = ehead, *save;
242 
243 		ehead = NULL;
244 		while (from != NULL) {
245 			for (nextp = &ehead;
246 			    (*nextp) && from->idle >= (*nextp)->idle;
247 			    nextp = &(*nextp)->next)
248 				continue;
249 			save = from;
250 			from = from->next;
251 			save->next = *nextp;
252 			*nextp = save;
253 		}
254 	}
255 
256 	if (!nflag)
257 		if (gethostname(domain, sizeof(domain) - 1) < 0 ||
258 		    (p = strchr(domain, '.')) == 0)
259 			domain[0] = '\0';
260 		else {
261 			domain[sizeof(domain) - 1] = '\0';
262 			memmove(domain, p, strlen(p) + 1);
263 		}
264 
265 	if ((vis_args = malloc(argwidth * 4 + 1)) == NULL)
266 		err(1, NULL);
267 	for (ep = ehead; ep != NULL; ep = ep->next) {
268 		p = *ep->utmp.ut_host ? ep->utmp.ut_host : "-";
269 		if ((x = strchr(p, ':')) != NULL)
270 			*x++ = '\0';
271 		if (!nflag && isdigit(*p) &&
272 		    (long)(l = inet_addr(p)) != -1 &&
273 		    (hp = gethostbyaddr((char *)&l, sizeof(l), AF_INET))) {
274 			if (domain[0] != '\0') {
275 				p = hp->h_name;
276 				p += strlen(hp->h_name);
277 				p -= strlen(domain);
278 				if (p > hp->h_name && strcmp(p, domain) == 0)
279 					*p = '\0';
280 			}
281 			p = hp->h_name;
282 		}
283 		if (x) {
284 			(void)snprintf(buf, sizeof(buf), "%s:%s", p, x);
285 			p = buf;
286 		}
287 		(void)printf("%-*.*s %-2.2s %-*.*s ",
288 		    UT_NAMESIZE, UT_NAMESIZE, ep->utmp.ut_name,
289 		    strncmp(ep->utmp.ut_line, "tty", 3) ?
290 		    ep->utmp.ut_line : ep->utmp.ut_line + 3,
291 		    UT_HOSTSIZE, UT_HOSTSIZE, *p ? p : "-");
292 		pr_attime(&ep->utmp.ut_time, &now);
293 		pr_idle(ep->idle);
294 		if (ep->args != NULL) {
295 			arglen = strlen(ep->args);
296 			strvisx(vis_args, ep->args,
297 			    arglen > argwidth ? argwidth : arglen,
298 			    VIS_TAB | VIS_NL | VIS_NOSLASH);
299 		}
300 		(void)printf("%.*s\n", argwidth, ep->args);
301 	}
302 	exit(0);
303 }
304 
305 static void
306 pr_header(nowp, nusers)
307 	time_t *nowp;
308 	int nusers;
309 {
310 	double avenrun[3];
311 	time_t uptime;
312 	int days, hrs, i, mins;
313 	int mib[2];
314 	size_t size;
315 	char buf[256];
316 
317 	/*
318 	 * Print time of day.
319 	 *
320 	 * SCCS forces the string manipulation below, as it replaces
321 	 * %, M, and % in a character string with the file name.
322 	 */
323 	(void)strftime(buf, sizeof(buf),
324 	    __CONCAT("%l:%","M%p"), localtime(nowp));
325 	(void)printf("%s ", buf);
326 
327 	/*
328 	 * Print how long system has been up.
329 	 * (Found by looking getting "boottime" from the kernel)
330 	 */
331 	mib[0] = CTL_KERN;
332 	mib[1] = KERN_BOOTTIME;
333 	size = sizeof(boottime);
334 	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 &&
335 	    boottime.tv_sec != 0) {
336 		uptime = now - boottime.tv_sec;
337 		uptime += 30;
338 		days = uptime / SECSPERDAY;
339 		uptime %= SECSPERDAY;
340 		hrs = uptime / SECSPERHOUR;
341 		uptime %= SECSPERHOUR;
342 		mins = uptime / SECSPERMIN;
343 		(void)printf(" up");
344 		if (days > 0)
345 			(void)printf(" %d day%s,", days, days > 1 ? "s" : "");
346 		if (hrs > 0 && mins > 0)
347 			(void)printf(" %2d:%02d,", hrs, mins);
348 		else {
349 			if (hrs > 0)
350 				(void)printf(" %d hr%s,",
351 				    hrs, hrs > 1 ? "s" : "");
352 			if (mins > 0)
353 				(void)printf(" %d min%s,",
354 				    mins, mins > 1 ? "s" : "");
355 		}
356 	}
357 
358 	/* Print number of users logged in to system */
359 	(void)printf(" %d user%s", nusers, nusers > 1 ? "s" : "");
360 
361 	/*
362 	 * Print 1, 5, and 15 minute load averages.
363 	 */
364 	if (getloadavg(avenrun, sizeof(avenrun) / sizeof(avenrun[0])) == -1)
365 		(void)printf(", no load average information available\n");
366 	else {
367 		(void)printf(", load averages:");
368 		for (i = 0; i < (sizeof(avenrun) / sizeof(avenrun[0])); i++) {
369 			if (i > 0)
370 				(void)printf(",");
371 			(void)printf(" %.2f", avenrun[i]);
372 		}
373 		(void)printf("\n");
374 	}
375 }
376 
377 static struct stat *
378 ttystat(line)
379 	char *line;
380 {
381 	static struct stat sb;
382 	char ttybuf[MAXPATHLEN];
383 
384 	(void)snprintf(ttybuf, sizeof(ttybuf), "%s/%s", _PATH_DEV, line);
385 	if (stat(ttybuf, &sb))
386 		err(1, "%s", ttybuf);
387 	return (&sb);
388 }
389 
390 static void
391 usage(wcmd)
392 	int wcmd;
393 {
394 	if (wcmd)
395 		(void)fprintf(stderr,
396 		    "usage: w: [-hin] [-M core] [-N system] [user]\n");
397 	else
398 		(void)fprintf(stderr, "uptime\n");
399 	exit (1);
400 }
401